1 .pr_agent_auto_best_practices
root edited this page 2025-06-26 01:54:37 +00:00

Pattern 1: Add null checks and validation before accessing object properties or calling methods to prevent null reference exceptions and runtime errors. This includes checking if objects, arrays, or references exist before using them.

Example code before:

public void ProcessData(Schema schema) {
    var key = schema.PrimaryKey; // Risk of null reference
    this.features.join(','); // Risk if features is not array
}

Example code after:

public void ProcessData(Schema schema) {
    if (schema == null) throw new ArgumentNullException(nameof(schema));
    var key = schema.PrimaryKey;
    if (Array.isArray(this.features) && this.features.length > 0) {
        this.features.join(',');
    }
}
Relevant past accepted suggestions:
Suggestion 1:

Fix null reference exception risk

The null check for schema should occur before accessing schema.PrimaryKey to prevent potential null reference exceptions. Move the null validation to the beginning of the constructor.

WelsonJS.Toolkit/WelsonJS.Esent/EsentDatabase.cs [35-41]

 public EsentDatabase(Schema schema, string workingDirectory, ICompatibleLogger logger = null)
 {
+    if (schema == null)
+        throw new ArgumentNullException(nameof(schema));
+
     _logger = logger ?? new TraceLogger();
-
     _primaryKey = schema.PrimaryKey;
 
-    if (schema == null)
-

Suggestion 2:

Fix grammar and add validation

The comment contains a grammatical error ("an unwanted features" should be "unwanted features"). Additionally, consider adding validation to ensure disableFeatures is an array before calling join() to prevent runtime errors.

lib/chrome.js [323-324]

-// disable an unwanted features
-cmd.push("--disable-features=" + this.disableFeatures.join(','));
+// disable unwanted features
+if (Array.isArray(this.disableFeatures) && this.disableFeatures.length > 0) {
+    cmd.push("--disable-features=" + this.disableFeatures.join(','));
+}

Suggestion 3:

Add null check

The function doesn't check if promptEditorRef.current exists before calling methods on it, which could lead to runtime errors if the ref isn't initialized.

WelsonJS.Toolkit/WelsonJS.Launcher/editor.html [195-202]

 const invoke = () => {
     try {
-        const updated = promptEditorRef.current.get();
-        promptMessagesRef.current = updated;
+        if (promptEditorRef.current) {
+            const updated = promptEditorRef.current.get();
+            promptMessagesRef.current = updated;
+        }
     } catch (e) {
         console.error("Invalid JSON structure", e);
     }
 };

Pattern 2: Validate string length and bounds before performing substring operations or string manipulations to prevent ArgumentOutOfRangeException and ensure safe string processing.

Example code before:

string result = path.Substring("prefix/".Length);
bool isValid = Regex.IsMatch(path, @"^[^/@]+@[^/]+/");

Example code after:

string result = path.Length > "prefix/".Length ? path.Substring("prefix/".Length) : path;
bool isValid = Regex.IsMatch(path, @"^(@[a-z0-9-]+\/[a-z0-9-]+|[a-z0-9-]+)@([0-9]+\.[0-9]+\.[0-9]+|latest|[^/]+)/");
Relevant past accepted suggestions:
Suggestion 1:

Prevent substring exception

The JqueryCdnPrefix transform is removing the "jquery/" prefix from the path, but this could cause issues if the path doesn't have sufficient length. Add a check to prevent potential ArgumentOutOfRangeException when the path is too short.

WelsonJS.Toolkit/WelsonJS.Launcher/ResourceServer.cs [196-210]

 private async Task<bool> TryServeFromCdn(HttpListenerContext context, string path)
 {
     bool isNodePackageExpression = Regex.IsMatch(path, @"^[^/@]+@[^/]+/");
 
     var sources = new (bool isMatch, string configKey, Func<string, string> transform)[]
     {
         (path.StartsWith("ajax/libs/"), "CdnJsPrefix", p => p),
         (isNodePackageExpression, "UnpkgPrefix", p => p),
         (isNodePackageExpression, "SkypackPrefix", p => p),
         (isNodePackageExpression, "EsmShPrefix", p => p),
         (isNodePackageExpression, "EsmRunPrefix", p => p),
         (path.StartsWith("npm/") || path.StartsWith("gh/") || path.StartsWith("wp/"), "JsDeliverPrefix", p => p),
-        (path.StartsWith("jquery/"), "JqueryCdnPrefix", p => p.Substring("jquery/".Length)),
+        (path.StartsWith("jquery/") && path.Length > "jquery/".Length, "JqueryCdnPrefix", p => p.Substring("jquery/".Length)),
         (true, "BlobStoragePrefix", p => p) // fallback
     };

Suggestion 2:

Improve package detection regex

The regex pattern for detecting node package expressions might not handle all valid package formats. Consider using a more comprehensive pattern that accounts for scoped packages (starting with @) and various version formats.

WelsonJS.Toolkit/WelsonJS.Launcher/ResourceServer.cs [198]

-bool isNodePackageExpression = Regex.IsMatch(path, @"^[^/@]+@[^/]+/");
+bool isNodePackageExpression = Regex.IsMatch(path, @"^(@[a-z0-9-]+\/[a-z0-9-]+|[a-z0-9-]+)@([0-9]+\.[0-9]+\.[0-9]+|[0-9]+\.[0-9]+|[0-9]+|latest|next|[^/]+)/");

[Auto-generated best practices - 2025-06-26]