psfdx-logs/psfdx-logs.psm1

function Import-PsfdxSharedModule {
    [CmdletBinding()]
    param(
        [string] $ModuleName = 'psfdx-shared'
    )

    if (Get-Module -Name $ModuleName -ErrorAction SilentlyContinue) {
        return
    }

    $candidates = @()

    $repoManifest = Join-Path -Path $PSScriptRoot -ChildPath (Join-Path '..' (Join-Path $ModuleName "$ModuleName.psd1"))
    $candidates += $repoManifest

    $moduleParent = Split-Path -Path $PSScriptRoot -Parent
    if ($moduleParent) {
        $siblingManifest = Join-Path -Path $moduleParent -ChildPath (Join-Path $ModuleName "$ModuleName.psd1")
        $candidates += $siblingManifest

        $moduleRoot = Split-Path -Path $moduleParent -Parent
        if ($moduleRoot) {
            $sharedBase = Join-Path -Path $moduleRoot -ChildPath $ModuleName
            if (Test-Path -LiteralPath $sharedBase) {
                try {
                    $versionDirectories = Get-ChildItem -Path $sharedBase -Directory -ErrorAction Stop | Sort-Object -Property Name -Descending
                    foreach ($dir in $versionDirectories) {
                        $candidates += Join-Path -Path $dir.FullName -ChildPath "$ModuleName.psd1"
                    }
                } catch {
                    # ignore directory inspection failures
                }
                $candidates += Join-Path -Path $sharedBase -ChildPath "$ModuleName.psd1"
            }
        }
    }

    $available = Get-Module -ListAvailable -Name $ModuleName -ErrorAction SilentlyContinue | Sort-Object -Property Version -Descending
    foreach ($item in $available) {
        if ($item.Path) {
            $candidates += $item.Path
        }
    }

    foreach ($candidate in $candidates | Where-Object { $_ } | Select-Object -Unique) {
        if (Test-Path -LiteralPath $candidate) {
            Import-Module -Name $candidate -ErrorAction Stop
            return
        }
    }

    Import-Module -Name $ModuleName -ErrorAction Stop
}

Import-PsfdxSharedModule

#region Debug Logs

function Watch-SalesforceDebugLogs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $DebugLevel,
        [Parameter(Mandatory = $false)][switch] $SkipTraceFlag,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $command = "sf apex log tail"
    if ($DebugLevel) { $command += " --debug-level $DebugLevel" }
    if ($SkipTraceFlag) { $command += " --skip-trace-flag" }
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --color"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    return Invoke-Salesforce -Command $command @commonParams
}

function Select-SalesforceDebugLogs {
    [CmdletBinding()]
    Param([Parameter(Mandatory = $false)][string] $TargetOrg)
    $command = "sf apex log list"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $result
}

function Get-SalesforceDebugLogs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $OutputDir,
        [Parameter(Mandatory = $false)][string] $LogId,
        [Parameter(Mandatory = $false)][int] $Last,
        [Parameter(Mandatory = $false)][switch] $Raw,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    if (-not $LogId -and -not $Last) {
        throw "Specify -LogId or -Last to fetch a debug log."
    }
    if ($LogId -and $Last) {
        throw "Provide only one of -LogId or -Last, not both."
    }

    $command = "sf apex log get"
    if ($OutputDir) {
        if ((Test-Path -Path $OutputDir) -eq $false) {
            throw "Folder $OutputDir does not exist"
        }
        $command += " --output-dir `"$OutputDir`""
    }
    if ($LogId) { $command += " --log-id $LogId" }
    if ($Last) { $command += " --number $Last" }
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }

    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters

    if (-not $Raw) {
        return Invoke-Salesforce -Command $command @commonParams
    }

    $command += " --json"
    $response = Invoke-Salesforce -Command $command @commonParams
    $response = $response | ConvertFrom-Json
    if ($response.status -ne 0) {
        throw "Error retrieving log: $($response.message)"
    }
    $logs = ""
    foreach ($log in $response.result.log) {
        $logs += $log + "`n"
    }
    return $logs.TrimEnd("`n")
}

function Export-SalesforceDebugLogs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][int] $Limit = 50,
        [Parameter(Mandatory = $false)][string] $OutputFolder = $null,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    if (($OutputFolder -eq $null) -or ($OutputFolder -eq "") ) {
        $currentFolder = (Get-Location).Path
        $OutputFolder = $currentFolder
    }
    if ((Test-Path -Path $OutputFolder) -eq $false) {
        throw "Folder $OutputFolder does not exist"
    }
    Write-Verbose "Output Folder: $OutputFolder"

    $logs = Select-SalesforceDebugLogs -TargetOrg $TargetOrg | Select-Object -First $Limit
    if (-not $logs -or (($logs | Measure-Object).Count -eq 0)) {
        Write-Verbose "No Logs"
        return
    }

    $logsCount = ($logs | Measure-Object).Count
    $i = 0
    foreach ($log in $logs) {
        $fileName = $log.Id + ".log"
        $filePath = Join-Path -Path $OutputFolder -ChildPath $fileName
        Write-Verbose "Exporting file: $filePath"
        Get-SalesforceDebugLogs -LogId $log.Id -Raw -TargetOrg $TargetOrg | Out-File -FilePath $filePath
        $i = $i + 1
        $percentCompleted = ($i / $logsCount) * 100
        Write-Progress -Activity "Export Salesforce Debug Logs" -Status "Completed $fileName" -PercentComplete $percentCompleted
    }
}

function Convert-SalesforceDebugLog {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline, Mandatory = $true)][string] $Log
    )

    begin {
        Write-Warning "Function still in Development"
    }

    process {
        $results = @()
        $lines = ($Log -split "`r?`n") | Select-Object -Skip 1 # Skip Header
        foreach ($line in $lines) {
            if ([string]::IsNullOrWhiteSpace($line)) { continue }
            $statements = $line.Split('|')

            $result = New-Object -TypeName PSObject
            $dt = if ($statements.Count -ge 1) { ($statements[0]).Trim() } else { $null }
            $lt = if ($statements.Count -ge 2) { ($statements[1]).Trim() } else { $null }
            $st = if ($statements.Count -ge 3) { ($statements[2]).Trim() } else { $null }
            $de = if ($statements.Count -ge 4) { ($statements[3]).Trim() } else { $null }
            if ($dt -eq 'NULL') { $dt = $null }
            if ($lt -eq 'NULL') { $lt = $null }
            if ($st -eq 'NULL') { $st = $null }
            if ($de -eq 'NULL') { $de = $null }
            $result | Add-Member -MemberType NoteProperty -Name 'DateTime' -Value $dt
            $result | Add-Member -MemberType NoteProperty -Name 'LogType' -Value $lt
            if (($null -ne $st) -and ($st -ne '')) { $result | Add-Member -MemberType NoteProperty -Name 'SubType' -Value $st }
            if (($null -ne $de) -and ($de -ne '')) { $result | Add-Member -MemberType NoteProperty -Name 'Detail' -Value $de }
            $results += $result
        }
        return $results
    }
}

#endregion

#region Debug Logging

function Enable-SalesforceDebugLogging {
    [CmdletBinding(DefaultParameterSetName = 'Id')]
    Param(
        [Parameter(Mandatory = $true, ParameterSetName = 'Id')][string] $TracedEntityId,
        [Parameter(Mandatory = $true, ParameterSetName = 'Username')][string] $Username,
        [Parameter(Mandatory = $true, ParameterSetName = 'ApexClass')][string] $ApexClass,
        [Parameter(Mandatory = $true, ParameterSetName = 'ApexTrigger')][string] $ApexTrigger,
        [Parameter(Mandatory = $true)][string] $DebugLevel,
        [Parameter(Mandatory = $false)][ValidateSet('DEVELOPER_LOG', 'USER_DEBUG')][string] $LogType,
        [Parameter(Mandatory = $false)][ValidateRange(1, 1440)][int] $Duration,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters

    if ($PSCmdlet.ParameterSetName -ne 'Id') {
        switch ($PSCmdlet.ParameterSetName) {
            'Username'    { $object = 'User';        $field = 'Username'; $name = $Username }
            'ApexClass'   { $object = 'ApexClass';   $field = 'Name';     $name = $ApexClass }
            'ApexTrigger' { $object = 'ApexTrigger'; $field = 'Name';     $name = $ApexTrigger }
        }
        $query = "SELECT Id FROM $object WHERE $field = '" + ($name -replace "'", "''") + "' LIMIT 2"
        $records = @(Select-SalesforceRecords -Query $query -TargetOrg $TargetOrg @commonParams)
        if ($records.Count -eq 0) {
            throw "No $object found with $field '$name'."
        }
        if ($records.Count -gt 1) {
            # e.g. a managed package class with the same name as a local one
            throw "More than one $object found with $field '$name'. Use -TracedEntityId instead."
        }
        $TracedEntityId = $records[0].Id
        Write-Verbose "Resolved $object '$name' to $TracedEntityId"
    }

    $command = "sf apex trace create --traced-entity-id $TracedEntityId"
    $command += " --debug-level `"$DebugLevel`""
    if ($LogType) { $command += " --log-type $LogType" }
    if ($Duration) { $command += " --duration $Duration" }
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --json"
    $result = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $result
}

function Get-SalesforceDebugLogging {
    [CmdletBinding()]
    Param([Parameter(Mandatory = $false)][string] $TargetOrg)
    $command = "sf apex trace list"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $result
}

function Disable-SalesforceDebugLogging {
    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][Alias('Id', 'TraceFlagId')][string] $TraceId,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    process {
        $command = "sf apex trace delete --trace-flag-id $TraceId"
        if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
        $command += " --json"
        $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
        $commonParams.Remove('WhatIf'); $commonParams.Remove('Confirm')
        if ($PSCmdlet.ShouldProcess($TraceId, 'Disable debug logging (delete trace flag)')) {
            $result = Invoke-Salesforce -Command $command @commonParams
            Show-SalesforceResult -Result $result
        }
    }
}

#endregion

#region Flows

function Get-SalesforceFlowInterviews {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][ValidateSet('Error','Paused','Running', 'Completed', 'VersionPaused', 'Autosaved', 'Expired', 'All')] [string] $Type = 'All',
        [Parameter(Mandatory = $false)][datetime] $After,
        [Parameter(Mandatory = $false)][int] $Limit = 200,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    # Build SOQL
    $query = ""
    $query += "SELECT Id, CreatedDate, InterviewLabel, InterviewStatus, Error "
    $query += "FROM FlowInterview "
    if ($Type -eq 'All') {
        $InterviewStatus = "'Error','Paused','Running','Completed','VersionPaused','Autosaved','Expired'"
    } else {
        $InterviewStatus = "'$Type'"
    }
    $query += "WHERE InterviewStatus IN ($InterviewStatus) "
    if ($After) {
        $afterIso = $After.ToString('s') + 'Z'
        $query += "AND CreatedDate >= $afterIso "
    }
    $query += "ORDER BY CreatedDate DESC "
    $query += "LIMIT $Limit"

    # Execute via sf data query
    $command = "sf data query --query `"$query`" --result-format json"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $raw = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $raw -ReturnRecords
}

#endregion

#region Logins

function Get-SalesforceLoginHistory {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][datetime] $After,
        [Parameter(Mandatory = $false)][datetime] $Before,
        [Parameter(Mandatory = $false)][string] $Username,
        [Parameter(Mandatory = $false)][int] $Limit,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    # Build SOQL for LoginHistory
    $query = "SELECT Id, LoginTime, UserId, SourceIp, Application, Status FROM LoginHistory"
    $conditions = @()
    if ($After)    { $conditions += ("LoginTime >= " + ($After.ToString('s') + 'Z')) }
    if ($Before)   { $conditions += ("LoginTime <= " + ($Before.ToString('s') + 'Z')) }
    # LoginHistory has no Username column, so filter through a User subquery on UserId
    if ($Username) { $conditions += ("UserId IN (SELECT Id FROM User WHERE Username = '" + ($Username -replace "'", "''") + "')") }
    if ($conditions.Count -gt 0) { $query += (" WHERE " + ($conditions -join " AND ")) }
    $query += " ORDER BY LoginTime DESC"
    if ($Limit -gt 0) { $query += " LIMIT $Limit" }

    # Query LoginHistory
    $command = "sf data query --query `"$query`" --result-format json"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $raw = Invoke-Salesforce -Command $command @commonParams
    $records = Show-SalesforceResult -Result $raw -ReturnRecords

    # No LoginHistory records found
    if ((-not $records) -or (($records | Measure-Object).Count -eq 0)) {
        Write-Verbose "No LoginHistory records found"
        return @()
    }

    $userParams = @{ TargetOrg = $TargetOrg }
    if ($Username) {
        $userParams.Username = $Username
        $userParams.Limit = 1
    }
    $users = Get-SalesforceUsers @userParams
    foreach ($record in $records) {
        $user = $null
        if ($users) {
            $user = $users | Where-Object { ($_.Id -eq $record.UserId) -or ($_.Username -eq $record.Username) } | Select-Object -First 1
        }
        if ($user) {
            foreach ($prop in 'Username','Name','Email','IsActive','LastLoginDate') {
                $userProperty = $user.PSObject.Properties[$prop]
                if ($userProperty) {
                    $record | Add-Member -NotePropertyName $prop -NotePropertyValue $userProperty.Value -Force
                }
            }
        } elseif (-not $record.PSObject.Properties['Username']) {
            $record | Add-Member -NotePropertyName Username -NotePropertyValue $null -Force
        }
    }

    # Already filtered in SOQL when -Username is provided
    return $records
}

function Get-SalesforceLoginFailures {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][datetime] $After,
        [Parameter(Mandatory = $false)][datetime] $Before,
        [Parameter(Mandatory = $false)][int] $Limit,
        [Parameter(Mandatory = $false)][string] $Username,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    $records = Get-SalesforceLoginHistory @PSBoundParameters
    if ((-not $records) -or (($records | Measure-Object).Count -eq 0)) {
        return @()
    }
    $records | Where-Object { $_.Status -ne 'Success' }
}

#endregion

#region Event Monitoring

function Select-SalesforceEventFiles {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $EventType,
        [Parameter(Mandatory = $false)][datetime] $After,
        [Parameter(Mandatory = $false)][datetime] $Before,
        [Parameter(Mandatory = $false)][int] $Limit,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    # Build SOQL for Event Monitoring (EventLogFile)
    $query = "SELECT Id, EventType, LogDate, LogFileLength, Sequence, Interval, CreatedDate"
    $query += " FROM EventLogFile"
    $where = @()
    if ($EventType) { $where += "EventType = '$EventType'" }
    if ($After)     { $where += ("LogDate >= " + ($After.ToString('s') + 'Z')) }
    if ($Before)    { $where += ("LogDate <= " + ($Before.ToString('s') + 'Z')) }
    if ($where.Count -gt 0) { $query += (" WHERE " + ($where -join " AND ")) }
    $query += " ORDER BY LogDate DESC"
    if ($Limit -gt 0) { $query += " LIMIT $Limit" }

    $command = "sf data query --query `"$query`" --result-format json"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $raw = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $raw -ReturnRecords
}

function Get-SalesforceEventFile {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Id,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $apiVersion = (Get-SalesforceLatestApiVersion -TargetOrg $TargetOrg)
    $command = "sf api request rest /services/data/$apiVersion/sobjects/EventLogFile/$Id/Logfile"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command $command @commonParams
}

function Export-SalesforceEventFile {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Id,
        [Parameter(Mandatory = $false)][string] $OutputFolder = $null,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    if (($OutputFolder -eq $null) -or ($OutputFolder -eq "")) {
        $OutputFolder = (Get-Location).Path
    }
    if ((Test-Path -Path $OutputFolder) -eq $false) {
        throw "Folder $OutputFolder does not exist"
    }

    $record = Get-SalesforceEventFile -Id $Id -TargetOrg $TargetOrg
    if (-not $record) {
        Write-Verbose "No EventLogFile record found for Id $Id"
        return
    }

    $fileName = "$Id.csv"
    $filePath = Join-Path -Path $OutputFolder -ChildPath $fileName
    $record | Out-File -FilePath $filePath -Encoding utf8
    Write-Verbose ("Exported EventLogFile record to: " + $filePath)
}

function Export-SalesforceEventFiles {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $EventType,
        [Parameter(Mandatory = $false)][datetime] $After,
        [Parameter(Mandatory = $false)][datetime] $Before,
        [Parameter(Mandatory = $false)][int] $Limit = 200,
        [Parameter(Mandatory = $false)][string] $OutputFolder = $null,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    if (($OutputFolder -eq $null) -or ($OutputFolder -eq "")) {
        $OutputFolder = (Get-Location).Path
    }
    if ((Test-Path -Path $OutputFolder) -eq $false) {
        throw "Folder $OutputFolder does not exist"
    }

    # Build SOQL for Event Monitoring (EventLogFile)
    $query = "SELECT Id, EventType, LogDate, LogFileLength, Sequence, Interval, CreatedDate"
    $query += " FROM EventLogFile"
    $where = @()
    if ($EventType) { $where += "EventType = '$EventType'" }
    if ($After)     { $where += ("LogDate >= " + ($After.ToString('s') + 'Z')) }
    if ($Before)    { $where += ("LogDate <= " + ($Before.ToString('s') + 'Z')) }
    if ($where.Count -gt 0) { $query += (" WHERE " + ($where -join " AND ")) }
    $query += " ORDER BY LogDate DESC"
    $query += " LIMIT $Limit"

    $command = "sf data query --query `"$query`" --result-format json"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $raw = Invoke-Salesforce -Command $command @commonParams
    $records = Show-SalesforceResult -Result $raw -ReturnRecords
    if (-not $records -or (($records | Measure-Object).Count -eq 0)) {
        Write-Verbose "No EventLogFile records found"
        return
    }

    $total = ($records | Measure-Object).Count
    $i = 0
    foreach ($record in $records) {
        $i++
        Export-SalesforceEventFile -Id $record.Id -OutputFolder $OutputFolder -TargetOrg $TargetOrg
        $percent = [int](($i / $total) * 100)
        Write-Progress -Activity "Export Salesforce Event Files" -Status "Exported $i of $total" -PercentComplete $percent
    }
    Write-Progress -Activity "Export Salesforce Event Files" -Completed
    Write-Verbose ("Exported $i EventLogFile record(s) to: " + $OutputFolder)
}

#endregion

#region Utilities

function Out-Notepad {
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline, Mandatory = $true)][string] $Content)

    process {
        # $IsWindows does not exist on Windows PowerShell 5.1, where it would silently
        # evaluate to $null and skip the launch entirely.
        if (-not (Test-SalesforceIsWindows)) {
            Write-Verbose "Out-Notepad is only supported on Windows"
            return
        }
        $filename = New-TemporaryFile
        $Content | Out-File -FilePath $filename -Encoding utf8
        Start-Process -FilePath 'notepad' -ArgumentList $filename | Out-Null
    }
}

function Test-SalesforceIsWindows {
    [CmdletBinding()]
    Param()
    return [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)
}

#endregion