Skip to content
| Marketplace
Sign in
Visual Studio Code>Programming Languages>Saropa UtilsNew to Visual Studio Code? Get it now.
Saropa Utils

Saropa Utils

Saropa

|
3 installs
| (0) | Free
Finds where your code could use saropa_dart_utils and repeated code worth extracting. Useful with or without the package. Keeps the package version in sync with the scanner.
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

saropa_dart_utils banner

Stop writing the same utility functions in every Flutter project. This library contains 400+ production-hardened extension methods and utilities extracted from a real-world Flutter app with thousands of active users.

pub.dev pub points coverage methods style: saropa lints license: MIT

🏅 Every utility meets one standard

Each method in this library is held to the same bar — no exceptions:

  • World-class code. Pure, tree-shakeable, null-safe Dart that passes dart analyze and the full saropa_lints rule set (1,000+ rules) with zero issues.
  • Detailed documentation. Every public member carries dartdoc that explains the why — the failure mode it guards, the edge cases it handles, and a runnable example.
  • Bullet-proof test coverage. Every method is backed by unit tests covering happy paths, empty/null inputs, Unicode, and boundary conditions (5,900+ tests and counting).

If a contribution does not clear all three, it does not ship.

Production-Proven, Not Theoretical

These utilities aren't academic exercises—they're dog-fooded daily in Saropa Contacts, a production Flutter app available on both Google Play and the App Store. Every method has been refined through real user feedback and edge cases you only discover in production.

What this means for you:

  • Edge cases already handled (empty strings, nulls, Unicode, timezone issues)
  • Performance optimized for mobile devices
  • API design proven intuitive through actual usage
  • Bugs already found and fixed by real users

Why Choose This Library

Before After
text != null && text.isNotEmpty ? text : fallback text.orDefault(fallback)
if (date != null && date.isAfter(start) && date.isBefore(end)) date.isBetween(start, end)
list.length > index ? list[index] : null list.itemAt(index)
"${n}${n == 1 ? 'st' : n == 2 ? 'nd' : ...}" n.ordinal()
Writing regex for email extraction text.between("@", ".")

One import. Zero boilerplate. Full null-safety.

What's Included

📒 Full index: CAPABILITIES.md is a complete, per-symbol catalog — every public utility with a one-line description and its import path, grouped by category. The table below is the high-level map; that file is the searchable detail for teams evaluating the library.

Category Scope Highlights
String 110+ extensions, 30+ utils Case conversion, truncation, wrapping, searching, grammar, diacritics, Unicode-safe ops; Levenshtein, slug/mask/template, diff (Myers), fuzzy search, excerpt, markdown, HTML sanitizer, name parsing
DateTime 50+ extensions, 10+ utils Age calculation, range checks, date arithmetic, leap years, week numbers; bounds, business days, duration format/parse, fiscal, relative, time rounding, injectable clock
List/Iterable 40+ extensions Safe access, deduplication, frequency analysis, order-independent comparison; chunks, partition, groupBy, run-length, binary search, rotate
Collections 38 modules LIS, LCS, sliding window, reservoir sampling, trie, disjoint set, Damerau–Levenshtein, knapsack, bloom filter, n-way merge, ring buffer, multiset, histogram, k-means, weighted interval, string pool, seeded shuffle, and more
Graph 15 modules BFS/DFS, Dijkstra, A*, connected components, topological sort, MST, critical path, bipartite, tree utils, DAG scheduler
Stats 16 modules Robust stats, moving average, normalization, quantile summary, correlation, linear regression, confidence intervals, funnel, retention, sampling, outlier (MAD), feature encoding
Validation 12 modules Validation errors, path/input shaping, guards, cross-field validation, safe temp names, password strength, PII detection, data redaction, safe parse, typed positives, IP/CIDR, JWT structure
Async 22 modules Debounce, throttle, delay, retry (with backoff/policy), memoize future, sequential/batch, cancel previous, semaphore, mutex, stream buffer/window, exponential backoff, circuit breaker, barrier, timeout policy, race/cancel, idempotent, heartbeat
Number 25+ extensions, 15+ utils Ordinals (1st, 2nd, 3rd), range clamping, digit ops; math (gcd, lcm), lerp, stats (variance, median, percentile), prime, factorial, locale format/parse, safe division
Map 15+ extensions, 5+ utils Nested access, pretty printing, null-safe ops; deep merge/copy, flatten keys, diff, invert, pick/omit, transform
Parsing 22 modules CSV, email, phone (E.164), Luhn, ISBN, SemVer, version compare, hex color, bool, list-from-string; config precedence, CSV dialect, canonicalize JSON, changelog section, JSON diff/patch, nested query, varint
Caching 4 modules LRU cache, TTL cache, size-limited cache, memoize (sync)
URL/Path 8+ modules Path join/extension/normalize, URL encode/query/build/absolute, path_more (directory, base name, bearer token)
Bool 8+ Flexible string parsing ("yes"/"1"/"true"), iterable analysis
Niche 10+ Color (hex/rgb, luminance, contrast), name (abbreviate, initials), pad/format, random string, hash, string diff, checksum, natural sort, UUID v4
Object/Pipe 12+ Pipe, compose, once; nullable (whenNonNull, mapNonNull, tryCast); assert, coalesce, require, shallow copy, copyWithDefaults
Utilities 25+ JSON validation/type/iterables, Base64, UUID, Hex, HTML entities, gesture types, regex common/match, debug (testing)

Installation

Run from your project directory:

flutter pub add saropa_dart_utils

Or for a pure Dart project:

dart pub add saropa_dart_utils

Then import it:

import 'package:saropa_dart_utils/saropa_dart_utils.dart';

For minimal bundle size, import only what you use (tree-shaking friendly):

import 'package:saropa_dart_utils/string/string_extensions.dart';
import 'package:saropa_dart_utils/datetime/date_time_extensions.dart';
import 'package:saropa_dart_utils/async/debounce_utils.dart';  // or throttle_utils, retry_utils, etc.

Tree-shaking checklist

Your release binary only carries the utilities you actually call — the barrel import is not a hidden "pull in everything" cost. Confirm:

  • ✅ Barrel or leaf import — same shipped size. Importing saropa_dart_utils.dart brings names into scope, not code into the binary. AOT (flutter build, dart compile) and dart compile js keep only what's reachable from your main(). Leaf imports help namespace hygiene and debug-build load time, not release size.
  • ✅ Extensions shake per method. Call one method on an extension and only that method (plus its transitive calls) survives — not the whole file.
  • ✅ No startup cost from unused code. The package adds no vm:entry-point pragmas, no dart:mirrors, and no eager top-level side effects; its internal regex/const helpers are lazy finals that never run unless a used method touches them.
  • ⚠️ Tree-shaking is a release-build behavior. Debug/JIT runs (flutter run, dart run) load everything by design — judge size from a release build, never a debug one.
  • ⚠️ Download size is separate. pub get still fetches the full source into .pub-cache; that's disk, not app binary, and is unaffected by tree-shaking.

Quick Start Examples

Drop-in solutions for common Flutter development tasks:

String Extensions (110+ methods)

// Null safety
String? text;
text.isNullOrEmpty;        // true
"hello".isNotNullOrEmpty;  // true

// Case manipulation
"hello world".titleCase();           // "Hello world"
"hello world".capitalizeWords();     // "Hello World"

// Formatting
"Saropa".wrapSingleQuotes();         // 'Saropa'
"Saropa".encloseInParentheses();     // (Saropa)

// Truncation
"Long text here".truncateWithEllipsis(10);  // "Long text …"

// Cleaning
"www.saropa.com".removeStart("www.");  // "saropa.com"
"  extra   spaces  ".compressSpaces(); // "extra spaces"
"abc123".removeNonNumbers();           // "123"

// Searching
"test@example.com".between("@", ".");  // "example"

// Grammar
"apple".pluralize(3);    // "apples"
"John".possess();        // "John's"
"apple".grammarArticle(); // "an"

// Diacritics
"cafe".removeDiacritics();  // "cafe"
String examples with their output: emoji-safe truncation, word-preserving ellipsis, diacritic removal, email and phone redaction, space compression, grammar article

DateTime Extensions (50+ methods)

DateTime date = DateTime(2024, 1, 15);

// Comparisons
date.isToday();
date.isBeforeNow();
date.isSameDateOnly(otherDate);
date.isBetween(start, end);

// Manipulation
date.addYears(1);
date.addMonths(2);
date.addDays(10);
date.nextDay();
date.prevDay();

// Age calculation
DateTime(1990, 5, 15).calculateAgeFromNow();
birthDate.isUnder13();

// List generation
DateTime.now().generateDayList(7);  // 7 days, starting today
DateTime examples with their output: month-end and leap-day arithmetic, age calculation, business days, relative time, ordinal day of month

List Extensions (30+ methods)

// Comparison
[1, 2, 3].equalsIgnoringOrder([3, 2, 1]);  // true
['a', 'a', 'b'].topOccurrence();           // 'a'

// Safe access
[1, 2, 3].itemAt(10);  // null (no exception)

// Null-safe operations
items.addNotNull(maybeNull);

// Deduplication
[1, 2, 2, 3].toUnique();  // [1, 2, 3]
List examples with their output: safe index access, deduplication, order-independent equality, most frequent item, exclusion, null-or-empty check

Number Extensions (25+ methods)

// Ordinals
1.ordinal();   // "1st"
22.ordinal();  // "22nd"

// Range operations
15.forceBetween(1, 10);  // 10
5.isBetween(1, 10);      // true

// Digit counting
12345.countDigits();  // 5
Number examples with their output: ordinals, compact formatting and parsing, clamping, safe division, percentages

Iterable Extensions (10+ methods)

[1, 2, 3, 4, 5].randomElement();
[1, 2, 3].containsAll([1, 2]);
[1, 2, 3, 4, 5].countWhere((n) => n > 3);  // 2

Map Extensions (15+ methods)

final pretty = {'name': 'John', 'age': 30}.formatMap();  // Pretty print
data.removeKeys(['a', 'c']);
Map examples with their output: safe nested access, key flattening, deep merge, picking keys, diffing two maps

Bool Extensions (8+ methods)

"true".toBool();           // true
[true, true, false].countTrue;  // 2
[false, false].anyTrue;         // false

Enum Extensions (2+ methods)

enum Status { active, inactive }

Status.values.byNameTry("active");   // Status.active
Status.values.byNameTry("invalid");  // null (safe)
Status.values.byNameTry("ACTIVE", isCaseSensitive: false);  // Status.active

Utility Classes (25+ methods)

// Hex
255.intToHex();   // 'ff'
'FF'.hexToInt();  // 255

// Random
CommonRandom(42).nextInt(10);  // 0 to 9, repeatable with a seed
CommonRandom().nextDouble();   // 0.0 up to, not including, 1.0

// URL
Uri.parse("https://example.com?key=value").hasQueryParameter("key");  // true

Async (debounce, throttle, retry, circuit breaker, and more)

// Debounce a callback (no-arg)
final debouncedSearch = debounce(() => fetchSuggestions(), Duration(milliseconds: 300));
debouncedSearch();  // call when user types; runs after 300 ms of no further calls

// Retry with exponential backoff
final result = await retryWithBackoff(() => http.get(uri), maxAttempts: 3);

// Limit concurrency
final semaphore = AsyncSemaphoreUtils(2);
await semaphore.run(() => heavyWork());
Async examples with their output: retry with backoff, timeout with fallback, batched mapping, memoized future

Collections, Graph, Stats, Validation

// Longest increasing subsequence (top-level function)
lisLength([3, 1, 4, 1, 5, 9, 2, 6]);  // 4

// Shortest distances from source (Dijkstra)
final distances = dijkstraDistances(weightedGraph, source);

// Safe parsing (no-throw, returns ParseOk/ParseErr)
final result = safeParse(int.parse, formValue);
final width = result.valueOrNull;  // int? (null if parse failed)

Real-World Use Cases

These aren't contrived examples—they're patterns we use constantly:

// User profile display
String displayName = user.firstName.capitalizeWords();
String initials = "${user.firstName.firstCharacter()}${user.lastName.firstCharacter()}";
String age = birthDate.calculateAgeFromNow().toString();

// Form validation
bool isValidInput = email.isNotNullOrEmpty && phone.removeNonNumbers().length >= 10;

// Date logic for subscriptions
bool isTrialActive = signupDate.addDays(14).isAfterNow();
bool isBirthdayThisMonth = birthDate.isSameMonth(DateTime.now());

// Safe API response handling
String? city = (response['address'] as Map<String, dynamic>?)?.getChildString('city');
List<String> tags = (response['tags'] as List?)?.whereType<String>().toUnique() ?? [];

// UI text formatting
String preview = longDescription.truncateWithEllipsis(100);
String itemCount = "item".pluralize(cart.length);  // "item" or "items"

Finding opportunities with saropa_scan (optional tooling)

saropa_scan is a separate, optional developer tool that lives in this repo. Its main job is to find places in your code where a saropa_dart_utils call could replace hand-written code. It also finds repeated code worth extracting, which is useful with or without this package. It is not part of the published saropa_dart_utils package (/tool/ and /extension/ are listed in .pubignore), so adding the library to your app does not pull it in. You run it from a checkout of this repository.

What it does:

  • Finds hand-written code a saropa_dart_utils call replaces (for example name[0].toUpperCase() + name.substring(1) → name.capitalize()), with a confidence score and a safety tier per suggestion.
  • Finds repeated code with dupes (or scan --repeated): near-identical code in your project that should become one shared function. It works even when your project does not use saropa_dart_utils.
  • Fixes with undo and provenance: fix applies safe fixes (try --dry-run first), records a run journal so fix --undo can revert it, and can leave a provenance comment at each fixed site.
  • VS Code extension "Saropa Utils" (extension/, id saropa.saropa-utils): a companion that shows both kinds of result as two peer groups in one view, in the Problems panel with quick fixes, and in the status bar (for example 12 utils · 5 repeated). It can also suggest adding or upgrading saropa_dart_utils in your project, always showing the exact command first. See VS Code extension: Saropa Utils below.

Where it lives: the CLI is in tool/scanner (see its README and user guide); the extension is in extension/.

Run it in three commands (needs the Dart SDK; the executable is saropa_scan, run dart run saropa_scan:saropa_scan --help to list every command):

cd tool/scanner && dart pub get
dart run saropa_scan:saropa_scan scan /path/to/your/project --repeated
dart run saropa_scan:saropa_scan fix /path/to/your/project --dry-run

Drop --repeated to scan for saropa_dart_utils opportunities only. For a faster, Dart-free start, dart compile exe bin/saropa_scan.dart -o saropa_scan builds a standalone binary.

Status: pre-release (scanner 0.1.0), not published to pub.dev or the VS Code Marketplace; the extension (version equal to this package) has its own Status below. Findings are suggestions: review them before applying anything beyond the safe tier.

Older script: suggest_saropa_utils

A CLI tool scans Dart files and suggests places where saropa_dart_utils can replace boilerplate (e.g. name[0].toUpperCase() + name.substring(1) → name.capitalize(), items.sublist(items.length - n) → items.takeLast(n), s ?? '' → s.orEmpty()). Every suggestion is audited against the real API and checked not to degrade your code — it will not push you toward getters like isNullOrEmpty that defeat Dart's null promotion. Run from this repo:

# With path: non-interactive, report to stdout (e.g. for CI)
dart run tool/suggest_saropa_utils.dart /path/to/your/flutter_app

# Without path: interactive — asks Y/N/? for directory, output format, and apply
dart run tool/suggest_saropa_utils.dart

dart run tool/suggest_saropa_utils.dart --help

Only [path], --help, and --version are accepted. Interactive prompts ask for directory, report vs JSON, and whether to apply (apply not yet implemented). Type ? on any prompt for help. No edits are made; use the report to refactor manually.

VS Code extension: Saropa Utils

The companion extension for the saropa_dart_utils package. It finds where your code could use saropa_dart_utils and repeated code worth extracting, and it is useful with or without the package installed. Extension id: saropa.saropa-utils; its version always equals the saropa_dart_utils package version in pubspec.yaml (a test enforces it), and it has no README or changelog of its own: this section and the Extension: entries in CHANGELOG.md are the source. Commands, views and settings use the saropaUtils. prefix (renamed from saropaScanner., see Migration). It runs the saropa_scan command line scanner for you.

Two peer results, both first-class:

  • saropa_dart_utils opportunities: hand-written code that a package member replaces ("nullIfEmpty - 14 places"), with one-click quick fixes.
  • Repeated code: near-identical code inside your own project that should become one shared function. Works even when saropa_dart_utils is not a dependency; the extension then offers to add it.

Status

Pre-release, not published to the Marketplace. The extension compiles, type-checks and has unit tests for its pure logic (npm test, no Dart needed, plus an opt-in test against the real CLI). It has run once in a real VS Code 1.105.1 Extension Host (through code-server driven by headless Chromium, see extension/test-host/README.md), in a trusted and an untrusted workspace, against a compiled saropa_scan: activation, commands, scan to Problems, tree, status bar, quick fix, report tab, version nudge toast and trust gating passed. That run found an activation-order crash that unit tests could not see; it is fixed in the current code. Not yet verified:

  • The Electron desktop app (the run used the web workbench with the real Extension Host), Windows and macOS, a real Dart-Code installation (a fixture stood in for the dart language id), remote/SSH hosts, scan-on-save under load, and the pub.dev lookup.
  • The download flow has not been tried against a real release; the release pipeline (plans/scanner/RELEASE_PIPELINE.md) has not run, so there are no bundled platform binaries or manifest yet.

Known limitations:

  • Virtual workspaces are not supported (the scanner runs a local process on files on disk).
  • Untrusted workspaces are supported only in a limited way (see Workspace trust).
  • It activates only when the workspace contains a pubspec.yaml (root or one folder down).
  • Quick fixes need the Dart language to be registered (the Dart extension); without it the code actions do not apply.

Features

  • Findings view: one "Saropa Utils" view in the Explorer with two peer top-level groups, both expanded when they have results: "saropa_dart_utils opportunities" first, "Repeated code" second. "Group Findings By..." (util member, rule, folder, kind) applies to both; the choice is remembered per workspace. An empty view offers both commands.
  • Commands: "Find opportunities to use saropa_dart_utils" is first in the palette; "Find repeated code" is its peer; "Scan Workspace (both)" runs both.
  • Status bar: headline with both counts, for example 12 utils · 5 repeated; the tooltip shows the CLI in use and the package version line. It shows a waiting hint while a save-triggered scan yields to a busy machine.
  • Problems panel: one diagnostic per finding (source: saropa_scan, code: <ruleId>), capped by saropaUtils.maxFindings.
  • Quick fixes: "Replace with ...", "Replace all in file", "Replace all in workspace (safe only)", "Ignore here". When a finding says its util needs a newer saropa_dart_utils than installed, the fix is "Upgrade package then replace" (runs the upgrade, then applies the fix). The scanner is expected to provide the requirement as requiresVersion (also read: minUtilVersion, sinceVersion, needsUpgrade.minVersion); without it nothing is marked.
  • Report screen: headline "N opportunities to use saropa_dart_utils", a saropa_dart_utils <version> (catalog built for <version>) line, the scanner in use and its version; section 1 opportunities by util and location, section 2 repeated-code clusters, then breakdowns, adoption trend and JSON/Markdown/CSV export.
  • Version sync (below), Doctor, Explain This Finding, Add to Exclude List, .saropa_scan/ logs.
  • Scan on save: scans only the saved file with the fast utils scan (catalog and library match). Repeated-code analysis is whole-project, so it is not run on save purely for cost; saropaUtils.scanOnSave.includeRepeatedCode turns it on.

Version sync

The extension reads every pubspec.yaml (and the nearest pubspec.lock) under the workspace, including pub workspaces and melos layouts, and records per package whether saropa_dart_utils is a dependency, from where (hosted, path, git, dev dependency, override) and which version is resolved. It compares that with the version the scanner catalog was built for (saropa_scan doctor --json, check versions, field catalogTarget).

  • It can show one notification, at most once per session per workspace, only in a trusted workspace:
    • Add saropa_dart_utils when it is absent but findings suggest it. Runs dart pub add saropa_dart_utils (or flutter pub add ... when the pubspec depends on Flutter).
    • Upgrade to when the resolved version is older than the catalog target (or, if you opt in, the latest on pub.dev). Runs dart|flutter pub upgrade saropa_dart_utils (with --major-versions when the constraint does not admit the target). Path dependencies are never nudged.
    • Not now (quiet for 24 hours) and Don't ask again for this workspace (stored in workspaceState).
  • Nothing runs silently: every action opens a modal showing the exact command and folder, then runs it as a visible task terminal. With several pubspecs you choose which one.
  • No network call by default. saropaUtils.versionCheck.pubDev (off, user-level) allows one cached request per day to pub.dev for the latest version; it never blocks, sends nothing about you, and failures are cached too.
  • Commands: Check saropa_dart_utils Version, Add saropa_dart_utils to a Package, Upgrade saropa_dart_utils. The API has getUtilsVersionInfo().

The scanner and being a good neighbour

The extension runs the saropa_scan CLI; it does not scan itself. It finds the CLI in this order: saropaUtils.cli.path, the binary bundled in the platform VSIX (bin/<platform>-<arch>/), saropa_scan on PATH, a previously downloaded copy, an on-demand download, and finally dart run (with a warning). The download asks once and shows the URL, size and SHA-256 from the release manifest (saropa_scan-manifest.json, pinned to the bundled scannerVersion tag); the file is verified against that SHA-256 before it is ever run, and a mismatch deletes it. Declining falls back to the Dart source and is remembered ("Download Scanner CLI" asks again). The scanner version is compared with the range derived from scannerVersion in package.json, and a warning appears if it is outside it.

  • One scan at a time per window (not configurable, because two concurrent scans only compete for CPU and the cache and make a loaded machine, for example one running Saropa Lints, slower): save-triggered scans cancel the running one; explicit commands queue behind it. Across windows the CLI's own lock decides.
  • Polite mode (saropaUtils.politeMode, default on): scans pass --priority low --jobs auto --lock wait when the installed CLI supports them (probed once with --help; unknown flags are omitted). Exit code 75 means another scan holds the lock: the extension shows "Another scan is already running (waiting...)" and retries with a growing delay (2 s up to 30 s, about 10 minutes at most), never in a tight loop.
  • Busy machine: before a save-triggered scan it checks the 1-minute load (above 70% of cores, or 50% while the Saropa Lints extension is active) and free memory (saropaUtils.minFreeMemoryMb). If busy, the scan waits, with a status-bar hint, and runs when the machine settles. Explicit commands always run (at low priority). Load average is not available on Windows, where only the memory check applies.
  • No scanner process stays alive when idle. On cancel, window close or deactivate the child and its process group are killed (taskkill /T on Windows). If the extension host itself crashes a child could outlive it; the CLI lock keeps that harmless.

Requirements

  • VS Code 1.85 or newer.
  • The saropa_scan CLI: bundled in platform VSIXes, or downloaded on first use, or built from a checkout of saropa_dart_utils (needs the Dart SDK; not published to pub.dev):
cd tool/scanner
dart pub get
dart run saropa_scan:saropa_scan --help   # sanity check

Then point the extension at it. Open Settings and set saropaUtils.scannerPath to the scanner package folder (for example tool/scanner; relative paths resolve against the workspace folder). saropaUtils.command (default dart run saropa_scan:saropa_scan) is run with that folder as working directory. To use a compiled binary instead (dart compile exe bin/saropa_scan.dart -o saropa_scan, see tool/scanner/docs/USER_GUIDE.md for catalog notes), set saropaUtils.command to the binary path.

Migration from "Saropa Dart Scanner" (saropaScanner.*)

Commands, views, context keys and settings were renamed to saropaUtils.*. Settings under the old prefix are still read as a fallback (only when the new key was never set, and for machine-scoped keys only from user settings), so existing configuration keeps working; save a setting once under the new name to migrate it. Whether VS Code returns values for a no-longer-contributed prefix has not been tried in a live host. The old command ids are not kept as aliases.

Workspace trust

Scanning runs an external command, so the extension declares limited support for untrusted workspaces: scanning is disabled until you trust the folder, and a prompt offers "Manage Workspace Trust". saropaUtils.command, scannerPath, cli.path, changedSince and fix.git/commitPer/comment (everything that becomes a process or a command line argument) are machine-scoped and restricted; changedSince is also validated as a plain git ref (no leading -) and passed as --changed-since=<ref>, and exclude globs as --exclude=<glob>, so a workspace's .vscode/settings.json cannot change them; set them in your user settings. The HTML report also needs a trusted workspace.

Commands

Title Command id
Find opportunities to use saropa_dart_utils saropaUtils.findOpportunities
Find repeated code saropaUtils.runDupes
Scan Workspace (both) saropaUtils.scanWorkspace
Scan File saropaUtils.scanFile
Check saropa_dart_utils Version saropaUtils.checkVersions
Add saropa_dart_utils to a Package saropaUtils.addPackage
Upgrade saropa_dart_utils saropaUtils.upgradePackage
Download Scanner CLI saropaUtils.downloadCli
Upgrade Package Then Replace (hidden; takes {id}) saropaUtils.upgradeThenFix
Fix All Safe saropaUtils.fixAllSafe
Open HTML Report saropaUtils.openHtmlReport
Show Run Log saropaUtils.showRunLog
Refresh Catalog saropaUtils.refreshCatalog
Doctor saropaUtils.doctor
Explain This Finding saropaUtils.explainFinding
Cancel Running Scan saropaUtils.cancel
Reveal Finding saropaUtils.revealFinding
Open Report Screen saropaUtils.openReport
Add to Exclude List saropaUtils.excludeAdd
Open Settings saropaUtils.openSettings
Group Findings By... saropaUtils.groupBy
Edit Exclude List saropaUtils.excludeList
Fix Finding saropaUtils.fixFinding

revealFinding and fixFinding are hidden from the Command Palette (they take a finding {id}); scanFile appears for Dart files, in the editor and Explorer context menus.

Settings

Setting Type Default Description
saropaUtils.command string dart run saropa_scan:saropa_scan Command used to launch the scanner CLI. Run with the scanner package as working directory unless scannerPath is set. Machine-scoped.
saropaUtils.scannerPath string "" Directory of the saropa_scan package (e.g. tool/scanner). Relative paths resolve against the workspace folder. Used as cwd for the command; empty means the workspace folder. Machine-scoped.
saropaUtils.minConfidence number 0.7 Minimum finding confidence (0-1).
saropaUtils.safetyLevel string (safe, review) safe Highest fix safety level applied by bulk fixes.
saropaUtils.lowPriority.mode string (skip, low, normal) low How tests, examples and tooling are treated: report separately (low), skip, or treat as normal.
saropaUtils.lowPriority.globs array ["**/test/**", "**/integration_test/**", "**/*_test.dart", "**/example/**", "**/benchmark/**", "**/tool/**"] Globs identifying low-priority code (tests, examples). Used to filter the Report screen.
saropaUtils.jobs number 0 Parallel scan jobs passed as --jobs. 0 lets the scanner choose (cores minus one).
saropaUtils.dupes.complexityWeight boolean true Rank duplicate clusters by code complexity as well as size. Off passes --no-complexity-weight.
saropaUtils.fix.comment string (off, brief, full) brief Machine-scoped. Provenance comment the CLI leaves at each fixed site (fix --comment).
saropaUtils.fix.git boolean false Machine-scoped. Let the CLI fix command commit applied fixes with provenance trailers. Off passes --no-git.
saropaUtils.fix.commitPer string (rule, cluster, run) run Machine-scoped. Commit granularity when saropaUtils.fix.git is on (fix --commit-per).
saropaUtils.exclude array ["**/build/**", "**/.dart_tool/**", "**/*.g.dart"] Glob patterns excluded from scanning (passed as --exclude). Use the Explorer context menu "Add to Exclude List" or the "Edit Exclude List" command.
saropaUtils.scanOnSave boolean true Scan the saved file (fast utils scan) on save; skipped or delayed while the machine is busy.
saropaUtils.scanOnSaveDebounceMs number 800 Debounce in milliseconds for scan-on-save.
saropaUtils.changedSince string "" If set, workspace scans use --changed-since=<ref>. Only plain git refs are accepted. Machine-scoped.
saropaUtils.cli.path string "" Absolute path of the saropa_scan executable (highest priority). Machine-scoped.
saropaUtils.politeMode boolean true Low priority, auto jobs, wait on the CLI lock.
saropaUtils.scanOnSave.includeRepeatedCode boolean false Also run the whole-project repeated-code analysis after a save scan (off only for cost).
saropaUtils.versionNudge.enabled boolean true Show the add/upgrade notification.
saropaUtils.versionCheck.pubDev boolean false Opt in to one cached daily pub.dev lookup for the latest version. Machine-scoped.
saropaUtils.maxFiles number 20000 Maximum number of Dart files indexed by the extension for previews (protects very large workspaces).
saropaUtils.maxFindings number 5000 Maximum findings published to the Problems panel; the Report screen still lists them.
saropaUtils.minFreeMemoryMb number 256 Delay scan-on-save while free memory is below this many MB. 0 disables the guard.

Large-workspace safeguards: file listing and Problems output are capped, scan-on-save is debounced and backs off under memory pressure, and the CLI is always spawned asynchronously.

API for other extensions

activate() returns a ScannerApi (extension/src/api/api-types.ts, apiVersion: 1): getVersion(), getFindings(filter?), getSummary(), getUtilsVersionInfo() (pubspec facts, resolved version, catalog target, and the latest version only when the pub.dev lookup is on), runScan({file?}) (resolves false if it failed, was cancelled or the workspace is untrusted) and onDidChange. Each finding may carry needsUpgrade: { minVersion } (the util needs a newer saropa_dart_utils) and root (absolute folder the relative file belongs to). Plain readonly data only; changes are additive within a version.

const api = vscode.extensions.getExtension<ScannerApi>('saropa.saropa-utils')?.exports;
if (api?.apiVersion === 1) { await api.runScan(); api.getFindings({ fixableOnly: true }); }

Stable deep-link command ids: saropaUtils.revealFinding {id}, saropaUtils.fixFinding {id}, saropaUtils.scanFile {uri | relative path}, saropaUtils.openReport. Finding ids come from getFindings().

Troubleshooting

  • Nothing happens / "scanning is disabled": trust the workspace (Manage Workspace Trust).
  • Scan fails to start: check the scanner line in the Report (which CLI is used), then run "Saropa Utils: Doctor". Check saropaUtils.scannerPath points at the scanner package and dart pub get was run there; check the output channel and "Show Run Log" (.saropa_scan/run.log).
  • Settings in the workspace are ignored: command, scannerPath, cli.path, changedSince and the fix.* options only work from user settings.
  • View is missing: it appears only in workspaces containing a pubspec.yaml.
  • Too few findings: lower minConfidence; tests, examples and tooling are reported as low priority by default (lowPriority.mode).
  • Slow in a huge workspace: lower jobs/maxFiles, add excludes, or set changedSince to a git ref.

Development

cd extension
npm install
npm run compile   # verify-nls + type-check + esbuild bundle to dist/
npm test          # vitest, pure logic; no Dart needed
npm run lint
npm run vsix      # package a .vsix

Tests cover pubspec/lock parsing, version comparison, nudge decisions, pub command building, CLI discovery order, manifest/SHA verification, exit-75 backoff, the scan queue, the busy-machine gate and argument safety. The real-host test is in test-host/ (see its README); it is not part of npm test. Press F5 in VS Code with the extension/ folder open to launch an Extension Development Host (not yet done by hand for this release; see Status).

Lint configuration

This package uses saropa_lints. Some rules are disabled for a pure Dart utility library (e.g. barrel file for the main entry point, non-ASCII in source for Unicode handling, static state for shared RegExp/constants). Others are satisfied by code fixes or inline suppressions (e.g. collapsed ifs in json_utils, named booleans in html_utils, redundant else removed, long-parameter-list and similar-names suppressed where intentional). Rationale for each override or resolution is in analysis_options_custom.yaml.

Documentation

  • API Reference — Full method documentation with examples
  • GitHub — Source code and issue tracking
  • Changelog — Version history

Contributing

We welcome contributions! These utilities grew from solving real problems—if you've got a helper that's saved you time, it might help others too.

  • Code of Conduct
  • Email: app.dev.utils@saropa.com
  • Slack

About Saropa

Saropa builds technology for personal safety and emergency preparedness. This utility library was extracted from Saropa Contacts—our production Flutter app for managing trusted emergency contacts—because we believe good utilities should be shared, not rewritten.

Google Play App Store

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
  • Your Privacy Choices
  • Consumer Health Privacy
© 2026 Microsoft