summary refs log tree commit diff
path: root/scripts/validateImports.cs
blob: 9008ecdb524b1734ec6cfff4db9d7a140ed08775 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/env dotnet
#:property Nullable=enable
#:property PublishAOT=false
#:package ArcaneLibs@1.0.1-preview.20260616-220331

using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using ArcaneLibs;
using ArcaneLibs.Attributes;
using ArcaneLibs.Extensions;

var logJson = false;

var importErrors = new Dictionary<string, List<ImportReference>>();

void LogError(string fileName, ImportReference import)
{
    importErrors.GetOrCreate(fileName).Add(import);
    Console.Write(
        $"\n{ConsoleUtils.ColoredString("!", 255, 49, 49)} {ConsoleUtils.ColoredString(fileName + ":" + import.Line + ":" + import.Position, 49 + 128, 49 + 128, 255)}: {(logJson ? import.ToJson(indent: false) : import.ToColorizedString())}");
}

foreach (var f in ReadDirRecursive("./src"))
{
    if (f.EndsWith(".test.ts")) continue; //ignore for now
    else
        await foreach (var import in GetImports(f))
        {
            // These files are completely idempotent and safe to import
            if (import.ImportSource.EndsWith("util/util/ProcessLifeCycle") &&
                import.ImportEntities.SequenceEqual(["ProcessLifecycle"])) continue;

            // Technically valid but what the heck
            if (import.ImportSource.StartsWith('#')) LogError(f, import);

            // file level
            else if (new FileInfo(f).Name == "start.ts")
            {
                if (import is
                    {
                        ImportSource: "module-alias" or "dotenv" or "./Server" // good imports
                        or "node:cluster" or "node:os" or "node:fs" // do we want to keep these around?
                    }) continue;
                LogError(f, import);
            }
            else if (f != "./src/bundle/Server.ts" && import is
                     {
                         ImportSource: "@spacebar/api"
                         or "@spacebar/cdn"
                         // or "@spacebar/gateway"
                         // or "@spacebar/webrtc"
                     }) LogError(f, import);
            else if (f == "./src/schemas/Validator.ts")
            {
                if (import is not { ImportSource: "ajv" or "ajv-formats" or "node:fs" or "node:path" })
                    LogError(f, import);
            }
            else if (f == "./src/database/Database.ts")
            {
                if (import is not { ImportSource: "picocolors" or "dotenv" or "typeorm" or "node:fs" or "node:path" })
                    LogError(f, import);
            }

            //directory level
            else if (f.StartsWith("./src/extensions"))
            {
                if (import.ImportSourceType == ImportSourceTypeValue.LocalPath) continue;
                LogError(f, import);
            }
            else if (f.StartsWith("./src/database"))
            {
                if (import.ImportSource == "typeorm"
                    || import.ImportSourceType == ImportSourceTypeValue.LocalPath
                    || import.ImportSource == "node:crypto"
                    || (import.ImportSource == "schemas" && import.IsTypeImport)
                    || (import.ImportSource == "../Database") // maybe?
                   )
                    continue;
                LogError(f, import);
            }
            else if (f.StartsWith("./src/schemas"))
            {
                LogError(f, import);
            }
            else if (f.StartsWith("./src/api"))
            {
                if (import.ImportSource == "express" &&
                    ((string[])["Request", "Response", "Router"]).ContainsAll(import.ImportEntities)) continue;
                LogError(f, import);
            }
        }

    if (importErrors.ContainsKey(f)) Console.Write("\n\n");
}

if (importErrors.Any())
    Console.WriteLine($"\rFinished with {importErrors.Sum(x => x.Value.Count)} warnings...\e[K");

Console.WriteLine();
// await foreach (var import in GetImports("./src/apply-migrations.ts"))
// {
//     Console.WriteLine(import.ToJson(indent: false));
// }

IEnumerable<string> ReadDirRecursive(string path)
{
    foreach (var f in Directory.GetFiles(path).OrderBy(x => x.TrimEnd(".ts").ToString()))
        yield return f;

    foreach (var d in Directory.GetDirectories(path).Order())
    foreach (var f in ReadDirRecursive(d))
        yield return f;
}

async IAsyncEnumerable<ImportReference> GetImports(string path)
{
    var basicImportRegex = new Regex(
        @"^import (?<typeSpecifier>type )?{?(?<entities>[a-zA-Z ,\n]+)}? from ""(?<source>.*)"";",
        RegexOptions.Multiline
    );
    var basicRequireRegex = new Regex(
        @"require\(""(?<source>.*)""\)(\.(?<entities>\w+))?",
        RegexOptions.Multiline
    );
    // Console.WriteLine(basicImportRegex);

    Console.Write($"\rReading imports for {path}: \e[K");
    var fileContents = await File.ReadAllTextAsync(path);
    Console.Write($"{fileContents.Length} chars");

    // if (basicImportRegex.IsMatch(fileContents)) Console.WriteLine("Match!");
    // else Console.WriteLine(fileContents + "\n^ Did not match regex " + basicImportRegex);

    ImportSourceTypeValue ClassifyImportSourceType(string p)
    {
        if (p.StartsWith("node:")) return ImportSourceTypeValue.Node;
        if (p.StartsWith("@types/")) return ImportSourceTypeValue.Types;
        if (p.StartsWith("@spacebar/")) return ImportSourceTypeValue.SpacebarAlias;
        if (p.StartsWith("lambert-server")) return ImportSourceTypeValue.VendoredModule;
        if (p.StartsWith("../")) return ImportSourceTypeValue.Path;
        if (p.StartsWith("./")) return ImportSourceTypeValue.LocalPath;
        if (p.StartsWith('#')) return ImportSourceTypeValue.Hashtag;

        return ImportSourceTypeValue.Npm;
    }

    ImportReference GetRef(Match m, bool isRequire) => new()
    {
        IsRequire = isRequire,
        IsTypeImport = m.Groups.ContainsKey("typeSpecifier") && m.Groups["typeSpecifier"].Success,
        ImportEntities = isRequire
            ? [m.Groups["entities"].Value.ReplaceLineEndings("")]
            : m.Groups["entities"].Value.ReplaceLineEndings("").Replace(" ", "").Split(","),
        ImportSource = m.Groups["source"].Value,
        ImportSourceType = ClassifyImportSourceType(m.Groups["source"].Value),
        Line = fileContents[..(m.Index)].CountInstances("\n"),
        Position = m.Index - fileContents[..(m.Index)].LastIndexOf('\n')
    };

    foreach (Match m in basicImportRegex.Matches(fileContents))
        yield return GetRef(m, false);

    foreach (Match m in basicRequireRegex.Matches(fileContents))
        yield return GetRef(m, true);
}

struct ImportReference
{
    public int Line { get; set; }
    public int Position { get; set; }
    public bool IsTypeImport { get; set; }
    public bool IsRequire { get; set; }
    public string[] ImportEntities { get; set; }
    public string ImportSource { get; set; }
    public ImportSourceTypeValue ImportSourceType { get; set; }

    public override string ToString()
    {
        var sourceType = ImportSourceType;
        return
            $"{ImportSourceType.GetType().GetMember((sourceType.ToString())).First().GetFriendlyName()} {(IsTypeImport ? "type " : "")}{(IsRequire ? "require" : "import")} from {ImportSource}, obtaining {string.Join(", ", ImportEntities)}";
    }

    public string ToColorizedString()
    {
        var sourceType = ImportSourceType.GetType().GetMember((ImportSourceType.ToString())).First();
        var sourceTypeClr = sourceType.GetColorOrNull();
        return
            $"{ConsoleUtils.ColoredString(sourceType.GetFriendlyName(), sourceTypeClr?.R ?? 255, sourceTypeClr?.G ?? 255, sourceTypeClr?.B ?? 255)} "
            + $"{(IsTypeImport ? ConsoleUtils.ColoredString("type ", 255, 127, 0) : "")}{(IsRequire ? ConsoleUtils.ColoredString("require", 255, 255, 0) : ConsoleUtils.ColoredString("import", 0, 255, 0))} "
            + $"from {ConsoleUtils.ColoredString(ImportSource, sourceTypeClr?.R ?? 255, sourceTypeClr?.G ?? 255, sourceTypeClr?.B ?? 255)}, "
            + $"obtaining {(string.Join(", ", ImportEntities.Select(x => ConsoleUtils.ColoredString(x, 150, 150, 150))))}";
    }
}

enum ImportType
{
    Unknown,
    Import,
    ImportType,
    Require
}

[JsonConverter(typeof(JsonStringEnumConverter<ImportSourceTypeValue>))]
enum ImportSourceTypeValue
{
    Unknown,

    [FriendlyName(Name = "NPM")] [Color(203, 56, 55)]
    Npm,

    [FriendlyName(Name = "NodeJS")] [Color(60, 135, 58)]
    Node,

    [FriendlyName(Name = "Types")] [Color(49, 120, 198)]
    Types,

    [FriendlyName(Name = "Spacebar internals")] [Color(11, 133, 255)]
    SpacebarAlias,

    [FriendlyName(Name = "Vendored module")] [Color(127, 255, 0)]
    VendoredModule,

    [FriendlyName(Name = "File path")] [Color(0, 255, 0)]
    Path,

    [Color(255, 255, 0)] [FriendlyName(Name = "Local file path")]
    LocalPath,

    [FriendlyName(Name = "Hashtag import")] [Color(255, 82, 82)]
    Hashtag
}