src/pipeline/Initialize-ScoutArmReferenceWalker.ps1

#Requires -Version 7.0
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$script:ScoutArmReferenceWalkerState = $null
<#
.SYNOPSIS
    Compiles the ARM reference walker: the same walk as Get-ScoutArmReference -UsePowerShell, in C#.
.DESCRIPTION
    The discovery index looks through every resource's properties (and provider-detail payload) for
    ARM resource ids, to build the relationship map. The PowerShell walk is one recursive function
    call per property node plus a Sort-Object pipeline on every object. On a 90-subscription tenant
    (281,529 index rows) it indexed about 100 rows a minute, which projected to days (#110). This
    compiles an equivalent walk once per session, the first time it is needed (not at module import).
    If compilation is unavailable (for example in constrained language mode), it returns $false and
    Get-ScoutArmReference keeps using the PowerShell walk.
 
    The walk is identical by construction and by test (tests/ArmReferenceWalker.Equivalence.Tests.ps1):
      - nodes are visited depth first; a node deeper than MaximumDepth is not visited;
      - a string that matches ^/(subscriptions|providers)/[^\s]+$ (any case) is a reference, reported
        with the path it was found at; other strings, value types and Uris are leaves;
      - dictionary entries are visited in key order, object properties (Note, Property, Alias and
        Script properties) in name order -- both culture-aware and case-insensitive, and stable, as
        Sort-Object orders them -- and list items in list order;
      - paths are built as "<path>.<name>" and "<path>[<index>]".
#>

function Initialize-ScoutArmReferenceWalker {
    [CmdletBinding()]
    [OutputType([bool])]
    param()

    if ($null -ne $script:ScoutArmReferenceWalkerState) { return [bool]$script:ScoutArmReferenceWalkerState }
    if ('AzureScout.ArmReferenceWalker' -as [type]) {
        $script:ScoutArmReferenceWalkerState = $true
        return $true
    }

    $source = @'
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
 
namespace AzureScout
{
    public static class ArmReferenceWalker
    {
        private static readonly Regex ArmId = new Regex(@"^/(subscriptions|providers)/[^\s]+$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
 
        private static object Unwrap(object value)
        {
            PSObject pso = value as PSObject;
            if (pso != null && !(pso.BaseObject is PSCustomObject)) { return pso.BaseObject; }
            return value;
        }
 
        // Returns [targetId, path] pairs in the order the PowerShell walk emits them.
        public static List<string[]> Find(object input, string path, int depth, int maximumDepth)
        {
            List<string[]> found = new List<string[]>();
            Walk(input, path, depth, maximumDepth, found);
            return found;
        }
 
        private static void Walk(object input, string path, int depth, int maximumDepth, List<string[]> found)
        {
            if (input == null || depth > maximumDepth) { return; }
            object baseObject = Unwrap(input);
 
            string text = baseObject as string;
            if (text != null)
            {
                if (ArmId.IsMatch(text)) { found.Add(new string[] { text, path }); }
                return;
            }
            if (baseObject.GetType().IsValueType || baseObject is Uri) { return; }
 
            IDictionary dictionary = baseObject as IDictionary;
            if (dictionary != null)
            {
                List<object> keys = new List<object>();
                foreach (object key in dictionary.Keys) { keys.Add(key); }
                foreach (object key in keys.OrderBy(k => k == null ? string.Empty : k.ToString(), StringComparer.CurrentCultureIgnoreCase))
                {
                    Walk(dictionary[key], path + "." + key, depth + 1, maximumDepth, found);
                }
                return;
            }
 
            IEnumerable enumerable = baseObject as IEnumerable;
            if (enumerable != null)
            {
                int index = 0;
                foreach (object item in enumerable)
                {
                    Walk(item, path + "[" + index + "]", depth + 1, maximumDepth, found);
                    index++;
                }
                return;
            }
 
            List<PSPropertyInfo> properties = new List<PSPropertyInfo>();
            foreach (PSPropertyInfo property in PSObject.AsPSObject(input).Properties)
            {
                PSMemberTypes type = property.MemberType;
                if (type == PSMemberTypes.NoteProperty || type == PSMemberTypes.Property || type == PSMemberTypes.AliasProperty || type == PSMemberTypes.ScriptProperty)
                {
                    properties.Add(property);
                }
            }
            foreach (PSPropertyInfo property in properties.OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase))
            {
                Walk(property.Value, path + "." + property.Name, depth + 1, maximumDepth, found);
            }
        }
    }
}
'@

    try {
        Add-Type -TypeDefinition $source -Language CSharp -ErrorAction Stop
        $script:ScoutArmReferenceWalkerState = $true
    }
    catch {
        Write-Verbose "Initialize-ScoutArmReferenceWalker: compiled walker unavailable, using the PowerShell walk: $($_.Exception.Message)"
        $script:ScoutArmReferenceWalkerState = $false
    }
    return [bool]$script:ScoutArmReferenceWalkerState
}