1.6.3
Audit-tooling fix only — no library changes.
1.6.2
Release-tooling hardening plus release-build input validation. The tooling work future-proofs the publish flow so a saropa_lints rule newly promoted to WARNING is caught before tagging instead of failing the tag-triggered publish one warning at a time (the v1.6.0 experience). The validation work converts assert-guarded preconditions on public-API input to if-throw guards so they hold in release builds, not just debug — a codebase-review sweep found that the dangerous subset degraded to a silent divide-by-zero, hang, or wrong result in production.
Changed
stableHashandHyperLogLogUtilsare now web-safe (stable_hash_utils.dart, hyperloglog_utils.dart) — both relied on 64-bit integer wrap that the web's 53-bit-doubleintmodel lacks (and shift operators truncate to 32 bits there), sostableHashproduced a different digest on web than the VM and the HLL estimate collapsed on web. The 64-bit FNV-1a multiply and the splitmix64 hash mixing / register-index-and-rank extraction are now computed in 32-bit limbs (16-bit split multiplies keep every intermediate under 2^53), so results are identical on every platform. The VM output is unchanged — the limb arithmetic reproduces the exact mod-2^64 result, verified against a BigInt ground truth over 200k (stableHash) and 500k (HLL) random inputs, so previously persistedstableHashdigests stay valid.stableHashgains a pinned-digest regression test.- Release-build precondition enforcement (18 files) — converted silent-failure
assertpreconditions on public-API input toif-throw guards (ArgumentError, orRangeErrorfor index/range args) so they run in every build, extending the v1.6.0FenwickTree/rolling_correlationprecedent to the rest of the library. Constructors validate through a static helper invoked in the initializer list, which keeps the throw out of the constructor body (soavoid_exception_in_constructorstays satisfied) and runs before any field initializer that would divide by the value.- Divide-by-zero / NaN:
SpatialGrid(cellSize),TimeDecayCounter(halfLifeMillis),TokenBucketRateLimiter(tokensPerSecond, capacity),binByWidth(bins, max > min),RateLimitSchedule(period),SlidingWindowRateLimiter(limit, window),TimeSeriesBuffer(bucketSizeMs, rawCapacity). - Hang / deadlock:
TaskScheduler(concurrency),BoundedWorkQueue(maxSize),ResourcePool(maxSize). - Silently-wrong result:
LruCache/MruCache/SizeLimitCachesize bounds;SegmentTree.update/query/valueAt(a negative index maps to a valid slot and corrupts the wrong leaf rather than throwing);IntervalEntry/IntervalTree.queryRange/hasOverlap(low > high);MultiIndexCollection(empty indexers);BkTree.search(negativemaxDistance);giniCoefficient(negative values). - Intentionally unchanged: the
constconstructorsQuietWindow,OpenWindow,RecurrenceSpeckeep theirasserts — aconstconstructor cannot throw and droppingconstwould be breaking;quantileBoundaries/binCountsalready degrade gracefully (return[]onbins < 2). - The matching precondition tests now expect
ArgumentError/RangeErrorinstead ofAssertionError.
- Divide-by-zero / NaN:
safeTempNamenow uses a cryptographically secure RNG (safe_temp_name_utils.dart) — was backed by a seedableRandom(), whose sequence is reproducible, so the generated temp-file names were predictable; an attacker who can guess the name can win a temp-file race or pre-create it. Switched toRandom.secure(). Also throwsArgumentErroron a non-positivelength(was silently returning an empty, always-colliding name).Map.getRandomListExceptaccepts an optionalRandom(map_extensions.dart) — previously shuffled with a fresh, non-injectableRandom(), making the result non-reproducible and untestable. Now takes an optionalrandom(defaults toRandom()), matching the injectable-RNG convention used elsewhere in the library. Backward-compatible (new optional parameter).hasInvalidUnicode/removeInvalidUnicodenow detect the real replacement character (string_analysis_extensions.dart) — the constant was56327(0xDC07, a lone low surrogate), not U+FFFD (65533) as the dartdoc said, so an actual�was never matched or removed. Fixed to65533; both methods now work as documented.- More grapheme-vs-code-unit slicing fixes (the same class as v1.6.0's
removeLastChar):removeFirstLastCharandremoveMatchingWrappingBrackets(string_manipulation_extensions.dart) counted code units but sliced with the grapheme-indexedsubstringSafe, so astral content shifted the result ('a😀b'.removeFirstLastChar()returned'😀b';'(😀)'kept the trailing bracket). Both now count graphemes, matchingremoveLastChars.removePrefix/removeSuffix(string_lower_extensions.dart) fed a code-unitprefix.length/suffix.lengthintosubstringSafe, dropping the wrong span when the prefix/suffix or content held astral chars ('😀ab'.removePrefix('😀')→'b'). Switched to code-unitsubstring, consistent withstartsWith/endsWith.
AsyncSemaphoreUtils.release()guards over-release (async_semaphore_utils.dart) — arelease()with no matchingacquire()(and no waiter) silently pushed_availableabovepermits, permanently letting the semaphore admit more thanpermitsconcurrent holders. It now throwsStateErrorinstead of corrupting the permit count.int.ordinal()— correct suffix for*11/*12/*13and negatives (int_string_extensions.dart) — the "teen" check was an absolute11..19window, so111.ordinal()returned'111st'(should be'111th'); likewise112/113/1011/213. And% 10on a negative gave the wrong suffix ((-21).ordinal()→'-21th'). Now tests the last two digits (11–13→th) and usesabs()for the ones digit, so111→'111th',101→'101st',(-21)→'-21st'. The class doc already promised negative support.flattenHierarchyno longer drops orphan-parent nodes (hierarchy_utils.dart) — a node whoseparentIdreferenced an id absent from the input was never a root and never reached by recursion, so it and its entire subtree silently vanished from the result. Such nodes are now treated as roots (level 0).formatNumberLocaleclampsdecimalPlaces(num_locale_utils.dart) —decimalPlaces > 20madetoStringAsFixedthrowRangeError. Now clamped to 20, matchingformatDouble.retryWithBackoffclamps the exponential shift (retry_utils.dart) —1 << (attempt - 1)was unclamped, so a largemaxAttemptsoverflowed the web's 32-bit shift and produced a wrong (small/negative) delay. Now clamped to<< 30, matchingexponential_backoff_utils/retry_policy_utils.
Deprecated
String?.isNullOrEmptyandString?.isNotNullOrEmpty(string_nullable_extensions.dart) — convenient shorthand, but both defeat Dart's null promotion: the analyzer cannot see the opaque getter impliesthis != null, so afterif (text.isNullOrEmpty) return;(or insideif (text.isNotNullOrEmpty) { … }) the variable stays nullable and callers are pushed toward!. Prefer the long formstext == null || text.isEmptyandtext != null && text.isNotEmpty, which the analyzer understands and which promotetextto non-null in the guarded scope. Kept for source compatibility; deprecated to steer new code.
Added
debounceCancelable/throttleCancelable(debounce_utils.dart, throttle_utils.dart) — variants ofdebounce/throttlethat return aCancelableCallback(a handle you invoke like a function and can alsocancel()). The plaindebounce/throttleclosures expose no cancel, so a pending timer fires even after the owner (e.g. a widget/controller) is disposed — a use-after-dispose and a Timer leak. The cancelable variants let callers drop the pending invocation on teardown. Non-breaking: the existingdebounce/throttleare unchanged; their docs now point to the cancelable variants.kRuleRemediationsrule-to-remediation mapping (rule_remediation_map.dart) — aconstdata table joining asaropa_lintscrash-prevention rule id to thesaropa_dart_utilspublic symbol that removes the runtime failure it flags (e.g.avoid_unsafe_reduce→sumBy,avoid_path_traversal→isPathSafe,geocoding_unchecked_first→firstWhereOrElse). This is the Saropa Suite Integration plan's R1 deliverable — the data that lets a sibling tool's quick fix upgrade from "enable rule X" to "enable rule X and useYfrom saropa_dart_utils." Ownership settled 2026-06-14 against the sibling changelogs: Lints owns rule→crash-signature, this package owns rule→util-symbol, joined onruleId. Every mapped symbol is pinned by a test that exercises it in compiled code, so alib/rename breaks the build rather than shipping a dead suggestion.kCrashCoverageAuditcrash-family remediation coverage audit (crash_coverage_audit.dart) — the Suite Integration plan's R3 deliverable. For each of the 12 stable crash families the suite recognizes at runtime (Log Capture'sCRASH_SIGNATURE_IDS), records whether this package covers it (coveredwith the owned symbol — e.g.state-error-no-element→singleOrNull,range-error-index→getOrNull,type-error-cast→castOrNull,format-exception→toIntNullable,concurrent-modification→forEachSnapshot) or is not remediable by a utility (notApplicable, e.g.late-init,out-of-memory,anr). No open gaps. Pinned by a test that asserts the family-id set equals the suite contract (a new upstream family fails until triaged) and exercises everycoveredsymbol in compiled code.List.forEachSnapshot(list_mutate_during_iteration_extensions.dart) — runs an action for each element of a point-in-time snapshot of the list, so the body may safely add to or remove from the list during iteration withoutConcurrentModificationError. Closes the suite'sconcurrent-modificationcrash family (R3 follow-up). Documents the snapshot semantics (added elements are not visited this pass; a removed element is still visited if it was present at snapshot time) and points pure conditional removal at the built-inremoveWhere.
Security
isPathSafedirectory-traversal bypass fixed (path_validator_utils.dart) — the escape check measured depth from the filesystem root (depth < 0) while depth started at the root's own depth, so a path could climbrootParts.lengthlevels above the supplied root and still be reported safe.isPathSafe('../secret', 'home/user')returnedtruethough it resolves tohome/secret(outside the root). Now rejects the moment the path climbs above the root directory itself. If you relied on this for sandboxing, re-test: some previously-"safe" paths are now correctly unsafe.
Fixed
pathExtension/pathWithoutExtensiononly treat a dot in the final segment as an extension (path_extension_utils.dart) — searching the whole path made a dot in a directory name look like the extension:pathExtension('/a.b/file')returned'b/file'andpathWithoutExtension('/a.b/c')returned'/a.b/c'→'/a'. Both now confine the dot search to the basename (and ignore a leading-dot dotfile).pathChangeExtensioninherits the fix.Map.renameKey/renameKeysno longer lose data or drop null values (map_more_extensions.dart) — they mutated the copy while iterating it, so a chained rename ({'a':'b','b':'c'}) overwrote'b'before renaming it ({'a':1,'b':2}→{'c':1}, value2lost); and anif (v != null)guard silently dropped entries whose value was null. Both now rebuild into a fresh map in one pass, preserving null values; a genuine target collision resolves last-wins (documented).JsonUtils.cleanJsonResponsestrips outer quotes around astral content (json_utils.dart) — used the grapheme-indexedsubstringSafewith a code-unit length, so a quoted value containing a non-BMP grapheme (e.g."🎉") kept its closing quote and then failed to decode. Switched to code-unitsubstring.formatFileSize(..., decimals: 0)keeps integer-part zeros (pad_format_utils.dart) —9728(9.5 KB) rounded to"10", and the unconditional0+$trailing-zero strip turned it into"1 KB". The strip now runs only after a decimal point.Map.deepMergereturns a fully independent result (map_deep_merge_extensions.dart) — nested maps/lists carried through unchanged were shared by reference with the inputs, so mutating the merged map mutated the receiver orother(also affectedcopyWithDefaults). Carried-through values are now deep-cloned.parseIpv4rejects non-canonical octets (ip_cidr_utils.dart) —int.tryParseaccepted a leading sign, surrounding whitespace, and leading zeros ('+1',' 1','01'), soparseIpv4('+1.2.3.4')parsed. Octets must now match a canonical decimal form (no sign/whitespace/leading-zero) — closes an octal-vs-decimal parser differential that can bypass IP allow/deny lists.isImageUri/fileExtensionuse code-unit slicing (url_extensions.dart) — fed a code-unitlastIndexOf('.')into the grapheme-indexedsubstringSafe, returning a wrong extension for filenames with astral characters. Switched to code-unitsubstring.parseQueryStringdecodes+as space (url_query_utils.dart) —Uri.decodeComponentdoes not translate+, so form/browser-produced query strings (a=hello+world) kept the literal+. Now+→space (a literal+arrives as%2B, sobuildQueryStringround-trips are unaffected).num.isNotZeroOrNegative/isZeroOrNegativehandle NaN (num_extensions.dart) —this != 0 && !isNegativeclassifiedNaNas positive. Rewritten asthis > 0/this <= 0, soNaNis correctly neither.roundToSignificantDigitsis correct at exact powers of ten (num_format_extensions.dart) — the decimal exponent was derived from a floatlog10that is fuzzy at powers of ten (e.g.log10(1000)≈ 2.9999997), mis-sizing the scale. Now nudges the exponent to the true integer with apowcomparison.FenwickTree(size)enforcessize >= 0in release (fenwick_tree_utils.dart) — the constructor used a release-strippedassert;size == -1slipped pastList.filled(0)into an unusable tree. Now throwsArgumentErrorvia a static validator (v1.6.0 fixed only the methods).prettyPrintindents entries correctly (debug_utils.dart) — keys/items were prefixed with the parent level's pad, so they were one level too shallow (top-level entries had no indent). Entries are now indented one level deeper than the closing brace.rangeDoubleavoids float drift and a zero-step infinite loop (debug_utils.dart) — computedx += step(accumulating error, so a0.1step could drop/add the endpoint) and would loop forever forstep == 0. Now guardsstep == 0and computes each element asstart + i*step.
1.6.1
Clears every pub.dev "Pass static analysis" point deduction (was 40/50): the seven dangling library doc comments pana reported plus the other eleven plugin findings it counts in the same check. dart analyze is now fully clean.
Fixed
stats/rolling_correlation_utils.dart: replaced two release-strippedasserts withif-throw guards (nowArgumentError) so equal-length andwindow >= 2preconditions are enforced in release builds, not just debug.collections/skip_list_utils.dart: replaced a!null-assertion inaddwith an explicit invariant guard that throwsStateError, and switched three[0]reads tofirstOrNull(added thepackage:collectionimport) so neither the unsafe-collection nor null-assertion lint fires.
1.6.0
Adds 35 advanced utilities from the roadmap — order-statistic trees, multi-source graph search, time-series analytics, calendar/billing helpers, and async cancellation; then a second batch of range-query trees, approximate string search, spatial indexing, async write caches, graph simplification/serialization, and rate-limited scheduling — plus a null-year-tolerant day-count helper. Then a full-project correctness audit of all 476 library files: ~40 algorithm/crash/concurrency bug fixes (incl. a semaphore permit race and two process hangs), ~30 documentation-accuracy corrections, 40 new regression tests, and a per-method audit-date stamp on every method. All fixes preserve existing signatures (backward-compatible).
Fixed
-
FenwickTreebounds checks now enforce in release builds (fenwick_tree_utils.dart) —update,prefixSum, andrangeSumguarded their index/range arguments withassert, which the Dart compiler strips from release builds (avoid_assert_in_production). In production a negativeindexpassed toupdatewould makei & -i == 0and spin the update loop forever (a hang, not a no-op); an out-of-range index toprefixSum/rangeSumwould return a silently wrong sum. All three now throwRangeErrorso the checks run in every build.valueAt's redundant assert is removed (it delegates to the now-validatedrangeSum). The two bounds tests now expectRangeErrorinstead ofAssertionError. -
removeLastChar()/removeLastChars(count)now count by grapheme cluster (string_manipulation_extensions.dart) — both methods bounded by code-unitString.lengthbut sliced with the grapheme-indexedsubstringSafe, an incoherent hybrid: it subtracted a code-unit count from a code-unit length, then used the result as a grapheme index. The visible effect depended on how many code units each trailing grapheme spanned — e.g.'a😀'.removeLastChar()returned'a😀'unchanged (the emoji's two code units left the grapheme index past the end), and the dartdoc's "counts UTF-16 code units / can split a cluster" claim was the opposite of what the code did. Both now count user-perceived characters: thecountargument is a count of visible characters, a trailing emoji or base+combining-mark sequence is removed whole, and the dartdoc matches.'a😀'.removeLastChars(1)→'a'; decomposed'Café'.removeLastChars(1)drops the whole accented cluster →'Caf'. Pure-ASCII behavior is unchanged. The three pre-existing emoji/combining-mark tests are rewritten to pin the coherent grapheme results, plus a newremoveLastCharemoji case. -
pathRelativenow emits leading..for up-traversal (path_join_utils.dart) —pathRelative('a/b/c', 'a/b/d')returned'd'instead of'../d'. The function computed the correct climb-out segments but joined them throughpathJoin, which treats a leading..as a pop with nothing above it and discards it. It now joins the already-clean segments directly, so any relative path that must ascend out ofbaseis correct ('a/b/c/d'→'a/x'yields'../../../x', pure ascent yields'../..'). Identical paths still yield'';pathJoin/pathNormalizepop semantics are unchanged for their other callers. Pinned by three new up-traversal tests. -
Project audit pass 7 — caching / int / double / json / bool / base64 + singletons (~43 files):
formatPrecision(double_extensions.dart) clampsprecisionto 0–20 (the rangetoStringAsFixedaccepts) instead of throwing a RangeError on a negative or >20 value.- Doc accuracy:
toBoolJson(json_type_utils.dart) documented as a truthy coercion that returnsfalse(notnull) for unrecognized non-null input — only anullargument yieldsnull(matching its tested behavior);int.ordinalexample114th(was101th);hexToIntexamples drop the false "prints a warning" claim;double.leastOccurrencescomment fixed (was a copy-paste of "highest"). - The cache implementations (LRU/MRU/TTL/size-limit/write-through), UUID v4 version/variant bits, HTML entity decoding, color packing/WCAG, and base64 round-trips were all audited and verified correct.
- 1 new regression test; per-method audit-date stamps across all files.
-
Project audit pass 6 — iterable / map / list / validation / url / object / niche (97 files):
jwtPayload(jwt_structure_utils.dart): two fixes — the base64url padding calc appended a spurious====block when the payload length was already a multiple of 4 (rejecting otherwise-valid tokens), and the bytes were decoded as raw code units instead of UTF-8 (mojibake for multi-byte claims). Now(block - len%block) % blockpadding andutf8.decode.mapDiff(map_diff_utils.dart): a genuinely-nullvalue (nullable V) is now reported as added/changed/removed instead of being skipped as if absent (key-presence based, not value-null based).lastWhereOrElse(iterable_first_last_extensions.dart) andrunLengthEncode(run_length_utils.dart): a matched/prevnull(nullable T) is no longer mistaken for "no match"/"no run" — the?? orElseandprev == nullsentinels are replaced.truncateToByteLength(niche_more_utils.dart): counts UTF-8 bytes per RUNE, so a non-BMP emoji is 4 bytes (not 6) and is never split into an invalid surrogate half.unflattenKeys(map_flatten_extensions.dart) andsetNested(map_nested_extensions.dart): a scalar/branch key collision now actually stops instead of writing the leaf into the wrong (outer) map.- Guards:
takeLast(negative n → empty, was RangeError);randomAlphanumeric(non-positive length → '', was a crash);parseQueryString(malformed percent-escape → literal text, was FormatException);getRandomListExcept(negative count clamped);shapeString(result never exceeds maxLength, was returning'...'for maxLength 2). - Doc accuracy:
map_initials_sortexample corrected;list_top_k"(partial sort)" → full-sort note;truncateToByteLengthdoc updated to code-point boundaries. - 5 new regression-test groups; per-method audit-date stamps across all 97 files.
-
Project audit pass 5 — string corrections (lib/string, 78 files):
SoundexUtils.encode(soundex_utils.dart) now treats vowels (A,E,I,O,U,Y) as adjacency-breakers (resetting the run) while H/W stay transparent — same-coded consonants separated by a vowel are re-coded, soGauss→G200instead ofG000.substituteTemplate(string_template_extensions.dart) does a single regex pass so a value containing another key's placeholder is not re-substituted (was chainedreplaceAll).markdownToPlainText(markdown_plain_utils.dart) strips image syntaxbefore the link rule, so it no longer leaves a stray leading!.chunkText(text_chunk_utils.dart) forces at least one char of forward progress, sooverlap >= maxCharsterminates instead of looping forever / overflowing the buffer.parseSearchQuery(search_query_parser_utils.dart) skips a bare-token instead of emitting an empty negated term.extractUrlsWithContext(url_extract_utils.dart) trims trailing sentence punctuation the greedy match swallowed (https://a.com.→https://a.com), leaving brackets intact for paren-bearing URLs.- Doc accuracy:
truncateMiddleandredactPhoneexample outputs corrected;String.reverseddocumented as rune-based (breaks grapheme clusters);template_engine_utilsno longer claims conditionals;textFingerprintdocumented as an order-sensitive identity hash, NOT a simhash (its Hamming distance is not a similarity measure). - 6 new regression-test groups; per-method audit-date stamps across all 78 files.
-
Project audit pass 4 — async & parsing corrections (lib/async 34, lib/parsing 37):
AsyncSemaphoreUtils(async_semaphore_utils.dart) fixed a permit double-counting race:releaseincremented_availableeven when handing the permit directly to a waiter while the wokenacquiredecremented again, so a fast-path acquirer in the wake-up gap could admit a second holder and drive the count negative.releasenow hands off without touching the pool.- Hang guards:
mapBatched(batch_async_utils.dart) treats a non-positive batch size as 1 instead of looping forever;raceFirst(race_cancel_utils.dart) fails fast on an empty producer list instead of returning a never-completing future;retryWithJitter(retry_policy_utils.dart) guards a zero jitter (nextInt(0)RangeError) and clamps the backoff shift;bufferCount/windowCountclamp a non-positive count to 1. SemverUtils.compareTo(semver_utils.dart) now compares pre-release identifiers per semver §11 (numeric-vs-numeric numerically, numeric below alphanumeric, longer ranks higher) instead of a plain string compare that madealpha.2 > alpha.10.encodeVarint/decodeVarint(varint_utils.dart) round-trip negative and >2^35 values: encode uses a logical shift + mask test (negatives emit the full 10-byte form), decode's cap is raised to 64 bits.parseHexColor(hex_color_utils.dart) rejects an embedded non-hex char instead of stripping it and parsing the coincidentally-valid remainder (#a1z2c3d→ null).parseChangelogSections(changelog_section_utils.dart) slices with code-unitsubstring, not the grapheme-indexedsubstringSafe, so emoji/non-BMP content no longer misaligns section bodies.parseNestedQuery(nested_query_parser_utils.dart) skips a scalar/nested key collision (a=1&a[b]=2) instead of leaking the nested leaf to the root.- Doc accuracy:
CircuitBreakerUtilsdocumented as two-state (no real half-open gating);memoizeFuturenotes failures are cached permanently;compareVersionswarns it ignores pre-release suffixes;raceFirstheader no longer claims it cancels losers. - 5 new regression-test groups; per-method audit-date stamps across all 71 files.
-
Project audit pass 3 — datetime corrections (lib/datetime, 57 files):
- Two unbounded-loop guards:
expandRecurrence(recurrence_iterator_utils.dart) now abandons an impossible rule (e.g.FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=30) after a long empty run instead of hanging even under.take(n);fillMissing(timeseries_gap_utils.dart) returns the input sorted for a non-positive interval instead of spinning forever / OOM. - DST / calendar-field correctness:
heatmapGrid/_weekStart(calendar_heatmap_utils.dart),dayOfYear/numOfWeeks(and thusweekOfYear/weekNumber) (date_time_calendar_extensions.dart),getNthWeekdayOfMonthInYear(date_time_extensions.dart), andsplitByMonth(period_split_utils.dart) now step dates with calendar fields / UTC date-only endpoints instead ofDuration(days:n)on local time, which drifted off midnight (and one day off, fordayOfYear) across DST transitions. parseIsoWeekString(date_time_week_extensions.dart) now rejects a week the year does not have (e.g.2025-W53) by validating the week's Thursday-year, instead of returning a date in the following ISO year.isAnnualDateInRange(date_time_comparison_extensions.dart) no longer matches a Feb-29 annual date against Mar 1 in non-leap years (DateTime silently rolls Feb 29 over).- Doc accuracy:
getEmojiDayOrNightno longer claims error-handling/logging it does not do;convertDaysToYearsAndMonthsexamples corrected (365 days is 11 months, not 1 year;45with remaining days is15, not14). - 6 new regression tests; per-method audit-date stamps across all 57 files.
- Two unbounded-loop guards:
-
Project audit pass 2 — collections corrections (lib/collections, 64 files):
kmeans2D(kmeans_utils.dart) now seeds centroids with maximin (greedy k-means++) spreading instead of placing all k atpoints[0]— the old seeding collapsed the output to at most two clusters for any k because identical centroids never diverge under Lloyd's algorithm.bucketByTime(time_bucket_utils.dart) andTimeSeriesBuffer(timeseries_buffer_utils.dart) now FLOOR the epoch-to-bucket division instead of truncating toward zero, so pre-1970 (negative-epoch) timestamps land in the correct bucket.bucketByTimealso returns empty for a non-positive bucket width instead of dividing by zero.BloomFilterUtils(bloom_filter_utils.dart) sizes the bit array withdart:math.loginstead of a hand-rolled natural-log approximation that mis-sized the filter.DifferenceArrayUtils.addRange(difference_array_utils.dart) now ignores a reversed range (l > r) as a no-op instead of silently corrupting the recovered array.- Doc accuracy:
StreamQuantileUtilsdocumented as the exact O(n) estimator it is (not the "P²-style fixed-memory" the title implied; removed the dead no-op buffer sort);PriorityMapUtilsdocumented as draining buckets in priority-insertion order, NOT by comparing key value;toColumnardocumented as using the first row's keys as the schema;topKIndicesdocumented as returning an unspecified order;pivot_unpivot_utilsnotesunpivotis not implemented. - 4 new regression tests; per-method audit-date stamps across all 64 files.
-
Project audit pass 1 — graph & num algorithm corrections (stats/graph/num categories):
floydWarshall(floyd_warshall_utils.dart) now seeds the distance matrix with the minimum edge weight per(i, j), not the last one — parallel edges in a multigraph and positive self-loops no longer overwrite a shorter distance or the diagonal0.dagSchedule(dag_scheduler_utils.dart) now appliespriorityas a tiebreaker among nodes that are simultaneously ready (priority-aware Kahn), instead of sorting the whole topological order by priority — the old form could place a dependency after its dependent, breaking topology.douglasPeuckerIndices(line_simplify_utils.dart) perpendicular distance now divides by the chord length (sqrt(dx²+dy²)), not the squared length —epsilonis once again a true distance tolerance; the degenerate zero-length chord uses Euclidean distance.dijkstraDistances/dijkstraWithParents/astar/bfs/dfs/criticalPathDistancesnow guard an empty graph or out-of-range start/source/goal instead of throwingRangeError(astar returnsnull, matching its no-path contract).nextPowerOfTwo(num_more_extensions.dart) bit-smear now reaches>> 32, fixing wrong results for 64-bit inputs above 2³².lcm(math_utils.dart) divides before multiplying to avoid 64-bit overflow on large operands.- Doc accuracy:
outlierIndicesByMADno longer claims the modified z-score cutoff (it omits the 0.6745 constant — now documented);divideSafedrops the impossible "or null" divisor note;NumUtils.generateIntListdrops the "prints a warning" claim (it does not print). - 6 new regression tests pin the corrected behaviors. Per-method audit-date stamps added across stats/graph/num doc headers.
-
List<String>helper tests pinned to real Dart casing/trim behavior (list_string_extensions_test.dart) — corrected two test expectations that asserted behavior Dart does not have, plus the matching source dartdoc. (1) The eszett case test claimed['straße'].toUpperCase()yields['STRASSE'], but Dart'sString.toUpperCase()is a 1:1 code-point map that leaves'ß'unchanged ('STRAßE'); the test and theListStringExtensions.toUpperCasedartdoc (which wrongly stated'ß'->'SS') now state the real no-expansion behavior. (2) TheremoveTrimmedEmpty(trim: false)test expected[' a ', ' ']to drop the whitespace-only' ', contradicting the documentednullIfEmpty(trimFirst:false)contract (and the sibling tests at the same group) under whichtrim:falsedrops only a literal''and keeps' '; the test now asserts both entries survive. Source behavior was correct in both cases — only the wrong expectations and the stale dartdoc changed. ComputeStreamTransformernon-sendable-closure test no longer hangs the suite (compute_stream_transformer_test.dart) — the test passed a closure capturing aStreamController(a non-sendable native receive port) throughcompute()and asserted the stream surfaced an error. That "non-sendable closure rejects" behavior is a real-isolate (on-device) contract that is unobservable in the Flutter test VM: sending such a closure leaves a dangling_RawReceivePortthat never closes, so the test isolate could not quiesce and the case ran to the 30-second timeout — the platform sensitivity the spec already flags. Reworked the test to assert the observable, supported half of the contract (a top-levelComputeCallbackcomputes correctly) and documented why the closure-rejection path is intentionally not exercised here. Source unchanged — it already propagates compute failures correctly (covered by the passingonError/ rethrow tests).DateTime.getSimpleRelativeDay/getRelativeDayResultnow count whole calendar days across a DST spring-forward (simple_relative_day_utils.dart) — the date-only normalize built LOCAL midnights, so on a spring-forward day (e.g. Mar 10→11 2024 in a US zone, a 23-hour local day)difference().inDaystruncated a genuine one-calendar-day gap to0, misbucketing tomorrow as today. The normalizer now builds UTC midnight from the calendar fields, so two normalized dates are always an exact multiple of 24 hours apart and the day count is correct regardless of DST or the receiver's UTC-vs-local kind.String.removeEndnow strips a code-unit suffix that falls inside a grapheme cluster (string_manipulation_extensions.dart) —removeEndmatched the suffix with UTF-16endsWithbut sliced with the grapheme-awaresubstringSafe, which reinterpreted the code-unit cut indexlength - end.lengthas a grapheme index and refused to split a base+combining-mark cluster, leaving the suffix un-stripped. So('e' + U+0301).removeEnd(U+0301)returned the unchanged'é'instead of'e'. Switched the slice to plainString.substring— afterendsWithis true the cut point is a guaranteed-valid code-unit boundary, so it never throws — making the strip consistent with the documented UTF-16 code-unit contractremoveEndNullableinherits. ASCII/BMP suffixes are unaffected.TextDirectionParseUtils.tryParsenow rejects a BOM-prefixed token (text_direction_parse_utils.dart) — Dart'sString.trim()strips U+FEFF (BOM / zero-width no-break space) as whitespace, so'ltr'was incorrectly parsing asltrinstead ofnull. The SPEC pins BOM as NOT whitespace (it is a formatting char, unlike NBSP / thin / ideographic space, which stay trimmed), so a private_trimhelper now re-attaches any leading/trailing BOM thattrim()removed, keeping the token unrecognized while preserving real-Unicode-whitespace trimming. Aligns the source with the existing zero-width-space (U+200B) handling.-
DateTime.toDateFormatnow returns''for an invalid pattern (date_time_intl_display_extensions.dart) — the documented "invalid pattern →'', never throws" contract relied solely on a try/catch, but intl'sDateFormatdoes NOT throw on an unrecognized field letter such as'q': it echoes the letter as literal text ('q'.toDateFormat('q')returned'q'), so the catch never fired. Added an up-front_patternHasUnknownFieldguard that rejects any unquoted ASCII letter outside intl's implemented field set (GyMkSEahKHcLQdDmsvzZ, sourced from intl's own pattern matcher), returning''before formatting. Letters inside single-quoted literal sections are exempt, so a literal pattern like'q'(quoted) still renders. -
Corrected the
compareAgesinstant-equality test (date_time_compare_age_extensions_test.dart) so it constructs the UTC and local operands from ONE instant (utc.toLocal()) instead of buildingDateTime.utc(2020, 1, 1)andDateTime(2020, 1, 1)independently. The old form assumed they were the same moment, butDateTime(...)is wall-clock local time — a different absolute instant fromDateTime.utc(...)on any host not at UTC+0 — so the instant-basedcompareTocorrectly returned-1, failing the assertion. The source comparator was correct; the test fixture was wrong. - Corrected the
ColorUtils.getColorshade500 test (material_color_utils_test.dart) so it compares ARGB values (toARGB32()) instead of objects.getColor(shade500, Colors.red)returns the plainColorat[500]; the old assertion compared it to theColors.redMaterialColorobject, which never equals a plainColorbecause the two are different runtime types even when the tone is identical. Now both sides are reduced to theirtoARGB32()integer (replacing the deprecated.value), matching the spec intent that shade500 is the swatch's primary tone. The source was correct; the test fixture was wrong. - Fixed
findUnicodeClassType(value, ignoreWhitespace: false)(unicode_class_utils.dart) to classify whitespace runes into their Unicode block instead of returningnull. The function calledvalue.trim()unconditionally, and Dart'strim()strips Unicode space separators (NBSP U+00A0, en-space U+2002, ideographic space U+3000, ogham space U+1680), so a whitespace-only string was emptied before the scan ran — makingignoreWhitespace: falseunreachable for exactly those runes. The trim now only runs whenignoreWhitespaceistrue; when the caller opts in to classifying whitespace, the original string reaches the rune loop, so NBSP →Latin1Supplement, en-space →GeneralPunctuation, and ideographic space →CJKSymbolsAndPunctuationas the spec's Bulletproofing list requires. The defaultignoreWhitespace: truepath is unchanged. - Corrected two
HebrewDateConvertertest expectations (hebrew_date_converter_test.dart) against SPEC-datetime-hebrew-converter.md. (1) The cross-cycle leap-boundary test asserted 5774→5777 as the last-leap/first-leap pair, but the closed-form(year*7+1)%19 < 7(used by the test's own far-future case and the source) places the seventh and final leap of a 19-year cycle at cycle-position 19, making 5776 the last leap and 5779 the first of the next cycle; 5774 is position 17 (the sixth leap). (2) The proleptic-day-before-epoch test (DateTime(-3760, 9, 6), JD 347997) expected month 13/day 29, but Hebrew year 0 is a degenerate proleptic year (its molad-derived length is 321 days, not a real 383–385-day leap year), so the month-walk lands on month 11, day 25 — the test now pins the algorithm's actual floor output. The source was correct in both cases; the test expectations were wrong.
Added
Roadmap batch — 25 advanced, tree-shakeable utilities (each its own file + full test suite; 276 new tests):
FenwickTree(fenwick_tree_utils.dart, roadmap #483) — Binary Indexed Tree for O(log n) point updates and prefix/range sums overnum; 1-based internal tree behind a 0-based public API, withFenwickTree.fromListbulk build.MinMaxHeap<T>(min_max_heap_utils.dart, roadmap #499) — double-ended priority queue (min-max heap) giving O(1)min/maxpeek and O(log n)removeMin/removeMaxfrom a single backing array, withminOrNull/maxOrNullfor the empty case.SkipList<T>(skip_list_utils.dart, roadmap #502) — probabilistic ordered set withcontains/add/remove, ascendingvalues, andfloor/ceilingorder-statistic lookups; injectableRandomfor deterministic tests.clusterBySimilarity/dedupBySimilarity(similarity_dedup_utils.dart, roadmap #461) — single-link (transitive) near-duplicate clustering via union-find over a caller-supplied similarity predicate, preserving first-seen order.weightedSubset(constrained_subset_utils.dart, roadmap #476) — weighted random subset selection without replacement (Efraimidis–Spirakis) honoring exclusion sets and non-positive-weight skipping; injectableRandom.clusterIntoSessions/sessionsWithBounds(session_clustering_utils.dart, roadmap #485) — gap-based sessionization of timestamped items (clickstream/login/GPS bursts); sorts input and splits on gaps exceedingmaxGap, optionally returning each session's start/end bounds.BacktrackingSolver<State, Choice>(backtracking_utils.dart, roadmap #486) — generic depth-first backtracking with pruning callbacks and a solutionlimit;solveFirst/solveAll(verified on N-Queens and subset-sum).permutations/combinations/cartesianProduct/powerSet(lazy_combinatorics_utils.dart, roadmap #488) — lazysync*combinatorics that yield fresh lists on demand, so huge spaces are enumerable without materializing them.ItemSimilarityModel<T>(item_similarity_utils.dart, roadmap #490) — co-occurrence item-to-item recommender; Jaccard similarity over per-item basket sets with rankedrecommend(item, topN).multiSourceBfsDistances/multiSourceBfsNearest(multi_source_bfs_utils.dart, roadmap #535) — single-sweep multi-source BFS giving each node its hop distance to (and identity of) the nearest seed;-1sentinel for unreachable nodes.pageRank(pagerank_utils.dart, roadmap #541) — power-iteration PageRank with dangling-node mass redistribution and tolerance-based early stop; scores sum to ~1.enumeratePaths(path_enumeration_utils.dart, roadmap #543) — all simple (no repeated node) paths between two nodes with an optionalmaxDepthedge cap.reachabilitySets/reachabilityMatrix/canReach(reachability_utils.dart, roadmap #551) — transitive closure; a node reaches itself only when it lies on a cycle.cusumChangePoints(change_point_cusum_utils.dart, roadmap #568) — two-sided CUSUM change-point detection with configurable threshold/drift, resetting on each detection.giniCoefficient(gini_utils.dart, roadmap #573) — inequality metric in [0,1] via the sorted-rank formula;0for equal distributions, NaN for empty, asserts non-negative inputs.rollingCorrelation(rolling_correlation_utils.dart, roadmap #577) — Pearson correlation over a sliding window of two equal-length series; NaN where a window has zero variance.binByWidth/quantileBoundaries/binByBoundaries/binCounts(data_binning_utils.dart, roadmap #585) — equal-width, quantile, and custom-boundary binning with out-of-range clamping and frequency counts.billingDateInMonth/nextBillingDate/billingSchedule/currentCycle(billing_cycle_utils.dart, roadmap #609) — monthly billing anniversaries with end-of-month clamping (anchor 31 → Feb 28/29) and cycle-bounds resolution.RecurrenceSpec+RecurrenceFrequency+humanizeRecurrence(humanize_recurrence_utils.dart, roadmap #599) — human-readable recurrence text ("every 2 weeks on Tuesday", "every 2nd Tuesday of the month") with a correct English-ordinal helper.dailyCounts/heatmapGrid/heatmapStats(calendar_heatmap_utils.dart, roadmap #603) — GitHub-style heatmap data: per-day event counts, a week-aligned grid over a date range, and max/total/active-day stats.findGaps/fillMissing/forwardFill(timeseries_gap_utils.dart, roadmap #606) — detect missing samples in a roughly-regular series (tolerance-based), generate the complete regular grid, and forward-fill null values.parseCacheControl/parseMaxAge/parseETag/parseRetryAfterSeconds(http_header_parse_utils.dart, roadmap #632) — dependency-free parsing of common HTTP caching headers (directive map, weak/strong ETag, numeric Retry-After).stableHash/canonicalString(stable_hash_utils.dart, roadmap #649) — order-stable structural checksum (FNV-1a 64-bit, sorted map keys, order-preserving lists) rendered as a fixed 16-char lowercase hex; no crypto dependency.flattenMap/explode(flatten_explode_utils.dart, roadmap #648) — flatten nested maps/lists into dotted/indexed keys and explode an array field into one row per element for tabular/BI export.CancellationToken/CancellationException/runCancellable(cancellation_token_utils.dart, roadmap #674) — cooperative cancellation: idempotentcancel,throwIfCancelled,whenCancelledfuture, fire-onceonCancelcallbacks, and a task-vs-cancellation race helper.
Roadmap batch 2 — 10 more advanced, tree-shakeable utilities (each its own file + full test suite; 80 new tests):
SegmentTree(segment_tree_utils.dart, roadmap #495) — iterative segment tree for O(log n) range sum / min / max with O(log n) point updates;SegmentTree.sum/.min/.maxnamed constructors with identity-aware empty handling.BkTree(bk_tree_utils.dart, roadmap #493) — metric-tree index for approximate string matching:search(query, maxDistance)prunes via the triangle inequality (default Damerau–Levenshtein, injectable metric), set-semantics inserts.SpatialGrid<T>(spatial_grid_utils.dart, roadmap #506) — uniform-grid spatial index for 2D points; O(1)insertandqueryRadius(x, y, r)that scans only overlapping cells then filters by true Euclidean distance.TimeSeriesBuffer+TimeBucket(timeseries_buffer_utils.dart, roadmap #510) — bounded series that keeps the last N raw points verbatim and folds evicted points into fixed-width count/sum/min/max/mean buckets for raw-recent + aggregated-history views.WriteThroughStore<K, V>/WriteBackStore<K, V>(write_through_cache.dart, roadmap #508) — async cache wrappers that coordinate writes to a backing store (the read-throughWriteThroughCache#523 does not): write-through persists on everyput; write-back buffers dirty keys and coalesces them onflush.MruCache<K, V>(mru_cache.dart, roadmap #509) — fixed-capacity cache with most-recently-used eviction (the right policy for cyclic scans) plus per-key access-frequency tracking viafrequencyOf.simplifyDegree2Chains(graph_simplify_utils.dart, roadmap #545) — contracts maximal chains of degree-2 pass-through nodes in an undirected graph into single junction-to-junction edges; preserves anchorless pure cycles so connectivity is never lost.serializeAdjacency/parseAdjacency(graph_serialize_utils.dart, roadmap #554) — loss-free compact text codec (0>1,2;1;2>0) for directed adjacency-list graphs; nodart:convertdependency, preserves neighbor order and isolated nodes.diffCalendars+CalendarEvent(calendar_diff_utils.dart, roadmap #608) — classifies two event snapshots (keyed by id) into added / removed / changed, where "changed" compares start, end, and title; the core of sync reconciliation and "what changed" UIs.-
RateLimitSchedule(rate_limit_schedule_utils.dart, roadmap #612) — shapes requested event times to honor a rolling-window quota (max N per period) plus a minimum cooldown, pushing rather than dropping events to the earliest compliant instant. -
findUnicodeClassType(String)+UnicodeClassTypeenum +isUnicodeWhitespace(int)(unicode_class_utils.dart, unicode_class_type.dart) — script/block detector that inspects a string's runes and returns the Unicode named block (BasicLatin,Cyrillic,Arabic,CJKUnifiedIdeographs,Hiragana,HangulSyllables,CurrencySymbols,Arrows, ...) the first qualifying rune falls into, mirroring the .NET "Supported Named Blocks" table across the Basic Multilingual Plane (U+0000–U+FFFF). Useful for language/script detection, input validation, sort-bucket selection, and font-fallback decisions. Options:ignoreBasicLatinskips the Latin block so a Latin-prefixed string reports the trailing non-Latin script;firstCharOnly(defaulttrue) classifies only the first qualifying rune vs. scanning to the first non-ignored match;ignoreWhitespace(defaulttrue) skips whitespace runes. Returnsnullfor an empty/whitespace-only string, for unassigned gaps between blocks, and for astral-plane runes above U+FFFF (most emoji) — the function is BMP-only and the three surrogate enum blocks are unreachable from valid Dart strings. Never throws (best-effort contract; any failure degrades tonull). The companionisUnicodeWhitespace(int rune)is the pure-Dart whitespace predicate (ASCII controls plus the Unicode space separatorstrimdoes not always strip, e.g. narrow no-break space, ideographic space) replacing the originalquiver.isWhitespacedependency, and the backingunicodeClassRangestable is exposed for meta-tests asserting it stays sorted, non-overlapping, and one-entry-per-enum-value. Pure Dart, no Flutter or external dependencies. String?.compareStringFolded()/foldedCompare()/List<String>.sortedFolded()(string_folded_compare_extensions.dart) — diacritic-folding sort comparator. Folds Latin diacritics and ligatures (á→a,ß→ss,æ→ae) so accented names interfile with their base letter instead of sorting afterzby code unit; case-insensitive by default, with an optionalnaturalnumeric mode (img2beforeimg10), null grouping (nullsLast), and a deterministic raw-string tie-break so two distinct strings that fold to the same key ("Foo"vs"fóò") never compare equal — safe as aSplayTreeMapcomparator (a0compare silently drops a key). Composes the existingremoveDiacritics()andnaturalCompare(); pure Dart, no new dependencies. Latin-focused: non-Latin scripts (CJK, Cyrillic, ...) pass through and order by code point; NOT locale-aware ICU collation.DateTimeIntlDisplayExtensionsonDateTime(date_time_intl_display_extensions.dart) — locale-correct date/time display viaintlskeletons (yMMMd,MMMEd,jm,Hms, ...), the one opt-in module inlib/datetime/that pulls theintldependency (the rest stays intl-free by design). Unlike the fixed-layoutDateFormatNamespresets, these REORDER components per locale (en_US "Jan 15, 1945", fr_FR "15 janv. 1945", ja_JP "1945年1月15日") and auto-detect each locale's 12h/24h clock from thejmskeleton. Members:dateDisplay(abbreviated/full month, optional English ordinal, current-year suppression),makeDisplayDate(weekday + year,year > 0guard for placeholder dates),makeDisplayTime(locale clock with minute-eliding and a U+00A0 non-breaking clock so "8:31 PM" never wraps),utcTimeDisplay(fixed presets via the newUtcTimeDisplayEnum),fullDateDisplay,formatByLocale,toDateFormat(explicit pattern + millisecond suffix), andgetUtcOffset(pure-DartUTC+5/UTC±0/UTC+5:30). All display methods catch and degrade (null/'') rather than throw on an unloaded locale. The top-levelformatUtcOffset(Duration, {verbose})formats a fixed offset deterministically (no host-TZ read) for testability. Callers formatting non-English locales must callinitializeDateFormatting()once per process first. Requires theintlpackage (re-enabled inpubspec.yaml).String.removeEndNullable(String? find)(string_manipulation_extensions.dart) — nullable-aware companion toremoveEnd, sitting beside it onStringManipulationExtensions. Returns the receiver unchanged whenfindisnullor empty (nothing to strip); returnsnullonly for the empty-receiver-with-a-real-suffix case (an empty source cannot carry the requested suffix, sonullmarks "no source" distinctly from'"stripped to nothing"); otherwise delegates toremoveEnd, so a whole-string match strips to'(notnull) and only ONE trailing occurrence is removed. Matching is case-sensitive UTF-16 code-unit suffix matching (not grapheme-aware), so a surrogate-pair emoji or whole combining mark strips cleanly while a bare combining mark off a cluster can split it. Pure Dart, no Flutter or external dependencies.bool.compareTo(bool other)(bool_sort_extensions.dart) — adds theBoolSortingHelperextension so aboolcan be used as a sort key.booldoes not implementComparableindart:core, so[true, false].sort()throws; this fills the gap with aComparable.compareTo-shaped comparator (truesorts BEFOREfalse, the "flagged first" convention): returns0for equal values,-1when this istrueandotherisfalse, and1for the reverse. Drops intoitems.sort((a, b) => a.isPinned.compareTo(b.isPinned))or any tie-break comparator. Pure Dart, no Flutter or external dependencies; the closed two-value domain has no failure path.FilterValue<T>(filter_value.dart) — optional-write wrapper forcopyWithparameters that need three intents instead of two:FilterValue.unset()(the const default) keeps the current value,FilterValue(v)overrides withv, andFilterValue(null)explicitly clears to null — the case the?? this.fieldidiom can't express and that the*ForceNullcompanion-parameter workaround doubled the parameter surface to express.resolve(current)performs the keep-vs-override decision in one call; the wrapper holds its value by reference (no copy) and defines nooperator ==. Pure Dart, zero dependencies.DateTime.toAnnualDate/DateTime.toDayRange()(date_time_bounds_extensions.dart) — two members added toDateTimeBoundsExtensions.toAnnualDatepins month/day to sentinel year 0 (the canonical recurring-annual-date form for birthdays/anniversaries) — the blessed producer for the existingDateTimeComparisonExtensions.isAnnualDateInRangeconsumer, dropping time-of-day and surviving Feb 29 (year 0 is a leap year).toDayRange()returns the full local calendar day as aDateTimeRangeby composing the existingstartOfDay/endOfDaygetters, so the end is microsecond-precise (23:59:59.999999), not millisecond-truncated, with a single source of truth for the bounds.DateTimeUtils.monthDayCountSafe({int? year, required int month})(date_time_utils.dart) — null-year-tolerant, non-throwing companion tomonthDayCount. Whenyearis null, February returns 28 (a leap year cannot be resolved without the year); a known leap year still yields 29. An out-of-rangemonth(0,13,-1, very large ints) returns 30 instead of throwing, so callers holding partial date parts get a defined value. Negative years follow the proleptic Gregorian leap rule. Backed by newDateConstants.daysInThirtyOneDayMonth/daysInThirtyDayMonth.Duration.displayTime()/Duration.formatDuration()/Duration.reverse()(duration_clock_format_extensions.dart) — a newDurationClockFormatExtensionswith three pure-Dart formatters.displayTime()renders a stopwatch/media clock string ('HH:MM:SS.mmm', or'MM:SS.mmm'withshowHours: false) and never rolls hours into days, soDuration(hours: 25)shows'25:00:00.000'— distinct from the day-aware top-levelformatDuration(d, ...)it sits alongside.formatDuration()renders a comma-joined human list of non-zero units down to microseconds ('1 hr, 2 mins, 3 secs, 4 ms, 5 μs'), returning'Instantaneous'forDuration.zero, with optionalshowLeadingZerosand short/longshortFormwords (microsecond short form is the Greek muμs).reverse()returns the sign-negated duration. Reuses the library'sString.pluralize; no Flutter, nointl.Uint8List.toIntList()/List<int>.toUint8List()(uint8list_extensions.dart) — two reciprocal byte/integer bridges in new extensionsUint8ListExtensionandIntListExtension.toIntList()copies a fixed-lengthUint8Listinto a fresh growable, independentList<int>(the form binary APIs — file bytes, crypto output, network frames, image decoders — need when they must append or mutate).toUint8List()copies anyList<int>into a fresh fixed-lengthUint8ListviaUint8List.fromList, storing each element modulo 256 (low 8 bits):256 → 0,257 → 1,-1 → 255, and even platform-max/min ints reduce to their low byte without throwing — narrowing that holds for typed-data sources (Int8List/Int16List) too. Both directions produce independent buffers, so post-conversion mutation never crosses over. Pure Dart (dart:typed_dataonly), no Flutter, no external packages.StopRangeenum (gradient_stop_range.dart) — four named easing categories (easeIn,easeOut,easeInOut,linear) mapped via.stopsto a fresh normalized two-elementList<double>in the 0..1 range ([0, 0.5],[0.5, 1],[0.25, 0.75],[0, 1]). Drops straight into any stops-accepting gradient API (FlutterGradient.stops, a CSS/SVG string builder, a custom shader). Pure Dart, no Flutter or external dependencies; each read returns an independent list so caller mutation can't corrupt the constants.double.toAspectRatio()(double_aspect_ratio_extensions.dart) — converts a decimal ratio (e.g. an image'swidth / height) into a GCD-simplified integer pair(int, int)?, quantizing the fractional part to three decimal places (× 1000) and reducing viaIntUtils.findGreatestCommonDenominator. Pure Dart, no dependencies; reuses the package'shasDecimalsgetter and GCD utility. Whole numbers return(1, value); the tuple order is(denominator-side, value-side), locked by a regression test. Returnsnullfor NaN,±Infinity, and negative fractional input — the non-finite guard keeps the integral path from throwingUnsupportedErrorontoInt(). The 3-decimal quantization truncates toward zero and is intentionally lossy, so canonical small ratios such as16:9are not recovered (16 / 9→(1000, 1777)).DarkColorsenum +DarkColorsUtils.darkColorMap(dark_colors.dart) — 20-value enum (Red…Black) mapped to fixed, fully-opaque Material 700Colorconstants (e.g.Red → 0xFFD32F2F). A brand-agnostic palette of legible-on-light dark colors for category tags, avatar backgrounds, chart series, and labels. Compile-timeconstdata table; every swatch is distinct, alpha0xFF, and verified by tests to clear a 3.0 WCAG contrast floor against white (cross-checked via the package's owncontrastRatio). Enum order is index-stable (Red= 0,Black= 19) so values persisted by index never silently remap. Flutter-typed (needsColor); kept in its own file so the pure-Dartcolor_utils.dartmath stays Flutter-free.SimpleRelativeDayenum +DateTime.getSimpleRelativeDay()/getRelativeDayResult()(simple_relative_day_utils.dart) — calendar-day relative classifier that buckets a date against a referencenowintotoday/yesterday/tomorrow/beforeYesterday/afterTomorrow/lastWeekday/nextWeekday(±3..±13 days) /lastMonth/nextMonth, returningnullfor dates outside the ~2-month window (same month beyond ±2 weeks, or more than one calendar month away) so callers get a typed label only when one is useful. Covers BOTH past and future at single-day resolution — net-new alongside the past-only stringrelativeDateBucketand the free-textrelativeTimeString. Time-of-day is dropped (calendar days, not 24-hour spans) via an internal kind-preserving date-only normalize, so a 23:59-vs-00:01 pair reads as one day and a DST short day still counts whole days; the month delta folds the year ((year*12 + month)) so Dec→Jan reads as next month.getRelativeDayResulttakes a caller-suppliedweekdayFormatterfor the "Last/Next [Weekday]" label so the core staysintl-free and never touches app locale state — the formatter is invoked at most once and only for weekday buckets (a throwing formatter propagates rather than being swallowed). The four unreachableThisWeek/LastWeek/NextWeek/ThisMonthvalues from the source app were dropped at inclusion (the classifier never emitted them). Pure Dart, no Flutter, no external packages.num.formatNumber({format, locale})(num_intl_format_extensions.dart) — a newNumIntlFormatExtensionsthat renders anynumwith CLDR-accurate, locale-aware grouping/decimal separators by delegating tointl'sNumberFormat(format, locale).format(this).formatis an arbitrary ICU number pattern (default'#,##0'; e.g.'#,##0.00'two decimals,'##,##,##0'Indian 2-2-3 grouping,'#,##0;(#,##0)'parenthesized negatives,'#,##0%'which scales the receiver by 100,'00000'zero-pad).localeis a BCP-47 string ('de_DE'produces'1.234','es_ES'produces'1.234.567','fr_FR'groups with U+202F a NARROW no-break space, not U+00A0); when null it follows the process-globalIntl.defaultLocale. This is the CLDR-accurate counterpart to the dependency-freeformatNumberLocalefree function (which inserts hand-supplied separator strings with no locale data and cannot express non-3-digit grouping or decimal-comma locales) — both are kept, trading theintldependency against accuracy. Rounding is half-up (2.5produces'3');double.infinity/negativeInfinity/nanrender the locale symbols (infinity, minus-infinity, NaN),-0.0is preserved as'-0', and an unknown/emptylocalethrowsArgumentErrorrather than silently falling back. Opt-in module pulling the already-presentintldependency, mirroringdate_time_intl_display_extensions.dart.DayInMonthCalculations(month_weekday_named_extensions.dart) — named, readability-focused wrappers over the existingMonthWeekdayUtilscore for the exact phrasings DST and public-holiday rule tables are written in:firstMonday/secondMonday/thirdMonday,firstThursday/firstFriday/firstSaturday/firstSunday,secondFriday/secondSaturday/secondSunday,thirdSaturday/thirdSunday, pluslastMonday/lastThursday/lastFriday/lastSaturday/lastSunday. Every 1st/2nd/3rd/4th andlast*occurrence is non-null (a calendar invariant —thirdSaturday/thirdSundaycorrected from the over-cautious nullable original to matchthirdMonday); an out-of-rangemonththrows a namedStateErrorrather than returning a plausible-but-wrong neighboring-month date, and the genuinely-absent-able 5th-occurrence query stays onMonthWeekdayUtils.nthWeekdayOfMonth. AddsdaysInFebruary(year)(leap-aware via the day-0-of-March trick, correct for ÷4/÷100/÷400, year 0, and negative years), plusfirstDayOfMonth(year, month)andlastDay(year, month)month-boundary helpers (the latter handles the December month-13 roll-over). All results are local midnightDateTime. Pure Dart, no Flutter, no external packages.-
RelativeTimeUtils(date_time_relative_predicate_extensions.dart) —DateTimeextension with four net-new calendar-day predicates plus a descriptive relative-time formatter.isTomorrow/isYesterdaycompare date-only viaisSameDateOnly(time-of-day irrelevant, so 23:59 vs 00:01 of the adjacent day still matches);isOlderThanToday/isOlderThanYesterdayuse exclusive start-of-day instant boundaries viaisBefore(the exact midnight returnsfalse, one microsecond earliertrue). Each takes an optionalnowfor deterministic tests. The two families intentionally diverge on UTC-vs-local (field comparison vs instant comparison) and are documented as not-DST-safe across a transition (the fixed 24h add/subtract).relativeTime({now, isDescriptive, isDescriptiveTimeSuffix, roundUp})returns verbose ("a moment ago","about an hour from now","23 years ago") or terse ("now","~1h","2y") phrasing, with an optionalago/from nowsuffix and floor-vs-round numeric units. Year-level spans use date-based calendar arithmetic (subtract years, back off one if the anniversary has not yet passed) instead ofdays / 365.25, fixing the off-by-one near anniversary boundaries (a2000-12-31birthday reads23 yearson2024-06-15, not24). Pure Dart; depends only onisSameDateOnlyandString.pluralize. The existing top-levelrelativeTimeStringis untouched — this is a distinct, additive API with a different output dialect. -
Map<String, V>.sortMap()(map_initials_sort_extensions.dart) —InitialsSortingUtilsextension returning aSplayTreeMap<String, V>ordered "letters before numbers" (from SPEC-sort-utils.md): letter-initial keys sort alphabetically and come first, number-initial keys follow with PURE integers in numeric order so'10'sorts after'2'(not before, the lexicographic trap). Letter detection is ASCII-only ([a-zA-Z]), so accented/non-Latin/emoji/symbol/empty initials fall to aString.compareTolexicographic fallback — documented and tested. Fixes a latent correctness bug in the source: two distinct pure-int keys of equal value ('007'vs'7') madeint.compareToreturn0, which would silently DROP one entry from theSplayTreeMap; a lexicographic tie-break now retains every entry. Signed ('-5') andint-overflowing ('99999999999999999999') keys correctly fall through to lexicographic without throwing. Pure Dart (dart:collectiononly), no Flutter or external packages. sortNullableStringListInPlace(List<String?>)(list_nullable_string_sort_extensions.dart) — top-level helper that sorts aList<String?>in place, case-insensitively, withnulls grouped to the front, returningtrueon success (thefalsebranch is defensive — the comparison cannot throw forString?). Delegates to the library's existingcompareStringNullable(single source of truth for null-aware string ordering) rather than re-implementing the lowercase/null-coalescing, and wraps the comparison so callers avoid the extension-on-List<String?>lint at each call site. Comparison is lowercased UTF-16 code-unit order, NOT locale-aware:'é'(U+00E9) sorts after'z', andnull/''both collate as the empty string. Pure Dart, no Flutter or external packages.compareAges(DateTime? a, DateTime? b, {bool ascending = true})(date_time_compare_age_extensions.dart) — nulls-LAST nullableDateTimecomparator with a direction flag, the counterpart tocompareDateTimeNullable(which placesnullFIRST and has no direction option). Twonulls are equal (0); a singlenullsorts LAST in BOTH directions because the null branches return1/-1BEFORE theascendingmultiplier is applied (a regression that reordered them would float nulls to the top — pinned by tests). Non-null values compare by absolute instant (DateTime.compareTo), so UTC-vs-local of the same moment is equal, DST transitions and calendar boundaries are irrelevant to ordering, and a one-microsecond difference is not truncated. Pure Dart, no Flutter or external packages.MaterialShade/MaterialShadeName/MaterialShadeLevels(color/material_shade.dart) — Flutter-scoped type-safe model of the tenMaterialColorintensities (50–900).valuegives the swatch index integer (Colors.blue[shade.value]),onShadereturns the contrast-correct foreground (black on the50–400band, white on500–900) per Material accessibility convention so callers never recompute luminance, anddisplayName/displayNameAnnotatedgive UI labels ("Shade 500", with(Lightest)/(Middle)/(Darkest)on the band endpoints, plain ASCII space so persisted/compared labels stay stable).MaterialShadeLevelsexposes the canonicallightShades/darkShades/ combinedshadesconst lists plus a seededrandomShade({bool? isLightBackground, int? seed})that draws from the high-contrast band for the given background —isLightBackground: truedeliberately yields a DARK shade for a light background. The picker reuses the library ownIterable.randomElement(the app-internalRandomList.randomItemdependency was dropped).ComputeStreamTransformer<TInput, TOutput>(async/compute_stream_transformer.dart) — genericStreamTransformerBasethat runs each incoming event through Flutter'scompute()(a one-shot background isolate) and emits the result, keeping CPU-bound per-event work (model mapping, parsing, serialization, byte decoding) off the UI thread. A thin, type-parametric wrapper overstream.asyncMap((d) => compute(fn, d)):asyncMapawaits each computation before pulling the next event, so output order always equals input order even when a later payload computes faster.computeFunctionmust be a top-level/static function (acomputerequirement — capturing closures cannot be sent to an isolate) and its payload must be isolate-sendable. The optionalonErrorrecovers a compute failure into a fallback value (one fallback per failing event, no collapsing) instead of erroring the stream; a SOURCE-stream error is forwarded untouched because it is not a compute failure, and a throwingonErrorsurfaces its error rather than swallowing it. On webcompute()runs inline (no real isolate) but still produces correct results. Flutter-typed (needspackage:flutter/foundation.dart); the app-specific contact-conversion specializations from the source were dropped as proprietary.String.toColor/Color.toHex/Color.darken/Color.lighten/Color.readableOn(flutter/color_extensions.dart) -- FlutterColor<-> hex-string conversion plus HSL lightness adjustment and a WCAG-contrast convergence helper (from SPEC-color-utils.md).String.toColor()parses a 6-digitRRGGBB(forced opaque) or 8-digitAARRGGBBhex string --#optional, case-insensitive, whitespace-trimmed -- returningnullfor empty/wrong-length/non-hex input (a0xprefix, leading sign, 3-digit shorthand, full-width or Arabic-Indic digits all yieldnull; embedded#is stripped everywhere).Color.toHex({includeAlpha})formats as uppercase, zero-padded, fixed-width#AARRGGBB/#RRGGBB, clamping wide-gamut channels above1.0so the width never breaks.darken/lightenadjust HSL lightness preserving hue/saturation/alpha and return the color unchanged for out-of-range,NaN, or infinite amounts (lenient, no-throw contract).readableOn(background, {minRatio = 4.5, step = 0.04, maxSteps = 16})darkens (light bg) or lightens (dark bg) the foreground until it clears the WCAG target, capped bymaxStepsso an unreachable pair (mid-gray on mid-gray, identical fg/bg,step == 0) returns best-effort instead of spinning. Flutter-typed; kept in its ownlib/flutter/file so the pure-Dartniche/color_utils.dartint-channel math stays Flutter-free.TextDirectionParseUtils.tryParse+TextWritingDirectionenum (string/text_direction_parse_utils.dart) — pure-Dart parser for the universal CSS/HTML/Unicodeltr/rtldirection tokens, returning a package-localenum TextWritingDirection { ltr, rtl }(from SPEC-string-text-direction.md). The Flutter-typedTextDirectionform from the source app was deliberately NOT ported — returningdart:ui'sTextDirectionfor a one-line wrapper would pull Flutter into this otherwise Flutter-free package; callers map to the framework type at the UI boundary.tryParseis case-insensitive and strips only LEADING/TRAILING whitespace viaString.trim()— which also strips Unicode whitespace (U+00A0 NBSP, thin space, ideographic space) but NOT zero-width chars (U+200B, U+FEFF BOM) or the direction marks themselves (LRM U+200E, RLM U+200F), all of which therefore yieldnull. No substring or partial matching ('ltrx','l t r','ltr;'→ null) and no Unicode normalization/folding (full-width'ltr', accented'ĺtr', emoji → null). ASCII-only lowercasing makes the result locale-independent (no Turkish-I pitfall). Total function: returnsnull(never throws) for null, empty, whitespace-only, numeric strings, control characters, and arbitrarily long junk. Pure Dart, no Flutter, no external packages.List<String>.joinWithFinal/anyContains/removeTrimmedEmpty/firstNotEqualTo/toLowerCase/toUpperCase, plusList<String?>.toLowerCase/toUpperCase/removeNullsAndTrimmedEmpty(list/list_string_extensions.dart) — seven members added to the existingListStringExtensionsplus a newNullableListStringExtensions on List<String?>(from SPEC-string-list-helpers.md).joinWithFinal({separator, finalSeparator})joins a list into a British-style sentence with a distinct final connector (['a','b','c']->'a, b and c') — distinct fromjoinDisplayList's Oxford-comma form: it adds no comma before the connector and does no trim/dedupe, so a blank entry survives (['a','','c']->'a, and c'); returnsnullfor empty and the sole item for length 1.anyContains(check, {caseSensitive})is true when any element containscheckas a substring (null/emptycheckor empty list ->false; case-insensitive lowercases both sides once).removeTrimmedEmpty({trim})drops entries empty after trimming and returnsnull(never[]) so a caller distinguishes "no items" from a result; withtrim: falseonly literally empty strings are dropped (a' 'survives).firstNotEqualTo(value)returns the first element not equal tovalue(case-sensitive), or the first element whenvalueis null, elsenull.toLowerCase/toUpperCaseare invariant-culture element-wise mappings (Turkish'i'->'I', German'ß'->'SS', emoji round-trip unchanged). The nullable variants drop nulls via core-DartnonNullsfirst. Pure Dart; reusespackage:collection(firstOrNull/firstWhereOrNull) and the library's ownString.nullIfEmpty(trimFirst:)/List.nullIfEmpty().ColorUtils(flutter/material_color_utils.dart) — three Flutter Material palette helpers with no app-domain knowledge (from SPEC-color-material.md).materialColorsis the canonical ordered, duplicate-free, immutableconstlist of the 19 primaryMaterialColorswatches (Colors.red…Colors.blueGrey) for indexing a fixed palette (charts, avatars, tags, deterministic per-index colors).getWhiteContrastColor(int)maps ANY int — negatives, values past 99, andintmin/max — deterministically to one of 100 fully-opaque colors biased to contrast against white, normalizing via((n % 100) + 100) % 100so the0–9palette indices stay in range on the VM and on web (JS-double ints) alike, then alpha-blending a tens-digit primary over a ones-digit secondary; every result is alpha1.0and clears a measured WCAG contrast floor against white (lightest blend ≈1.22).getColor(MaterialShade, MaterialColor)is a typed, exhaustive-switch swatch accessor replacing the stringlycolor[500]!. Reuses the sharedMaterialShadefromlib/color/material_shade.dartrather than redefining it. Flutter-typed (needsColor/MaterialColor); no external packages.HebrewDateConverter(datetime/hebrew_date_converter.dart) — net-new Gregorian→Hebrew (Jewish) lunisolar calendar converter and formatter (from SPEC-datetime-hebrew-converter.md), the library's first non-Gregorian calendar system. Implements the fixed arithmetic Hebrew calendar from "Calendrical Calculations" (Reingold & Dershowitz) via a Julian-Day-Number bridge: deterministic, offline, nointl, no I/O.fromGregorian(DateTime)returns a plain({int year, int month, int day})record (Hebrew year 57xx, month 1–13 in display order, day 1–30);isHebrewLeapYear/monthsInHebrewYear(12 or 13) /daysInHebrewYear(353–355 regular, 383–385 leap) /daysInHebrewMonth(29 or 30, with variable-length Cheshvan/Kislev and the four Rosh-Hashanah postponement rules) expose the calendar arithmetic.getMonthName(month, year, {useHebrew})resolves the leap-year Adar I / Adar II split (and plain Adar in a regular year) in English transliteration or Hebrew script;formatDayHebrew/formatYearHebrewrender gematria numerals (with the 15→ט״ו / 16→ט״ז substitutions that avoid spelling a divine name, and the thousands digit elided for years);format/formatDayMonthcompose the full strings ('1 Tishrei 5785'or'א׳ תִּשְׁרֵי תשפ״ה'). Civil-date mapping by design: only the input's year/month/day are read — time-of-day, UTC/local flag, and sunset are ignored, so an eveningDateTimeis NOT advanced to the next Hebrew day.abstract finalnamespace, all static; pure Dart, onlypackage:meta(@useResult).
1.5.1
Exact length (meters ↔ feet) and weight (kilograms ↔ pounds) unit conversions with full-precision factors, plus English string formatters that handle the 12-inch carry boundary, negative values, and non-finite input.
Added
LengthConversionUtils/WeightConversionUtilsinlib/num/unit_conversion_utils.dart: dependency-freeconvert*primitives (NaN/infinity propagate) and*ToStringformatters.feetToStringcarries rounded inches into feet so it never renders "12 inches", signs negative heights, and falls back safely on NaN/∞.String.preventOrphans({int minWrapChars = 4})(string_wrap_extensions.dart) — typography helper that swaps a breaking space for a non-breaking space (U+00A0) wherever a wrap there would strand a token shorter thanminWrapChars(a lone…,I,(5),the). Symmetric rule (fuses when EITHER adjacent token is short, anywhere in the line), idempotent, pure-Dart with no dependencies. Splits on a single ASCII space only; code-unit length, not grapheme width.
1.5.0
Ten advanced algorithm utilities from the roadmap-to-700 batch — quote-aware text folding, language detection, TF-IDF keyphrases, line-based redline diffs, Gale–Shapley stable matching, hierarchical clustering, HyperLogLog distinct counts, Pareto frontiers, time-decayed counters, and an LRU/LFU hybrid cache — each its own tree-shakeable file so apps pull in only what they use.
Added
foldText/unfoldText/FoldOptions(text_fold_utils.dart) — quote-aware hard-wrap and unwrap for email-reply text:foldTextwraps each line toFoldOptions.widthwhile repeating the leading quote prefix (>,> >) on every continuation;unfoldTextmerges soft-wrapped continuations back into one logical line per quote level. Words longer than the available width are emitted whole (never split — no infinite loop), blank lines are paragraph boundaries, and quote-depth changes are join boundaries. Roadmap #412.detectLanguage/LanguageGuess(language_detect_utils.dart) — best-effort dominant-language detection over a short string using character-trigram out-of-place rank distance against six compact built-in profiles (en/es/fr/de/it/pt). Returns the closest match with a0..1confidence, ornullwhen the text is too short (fewer than 3 trigrams) to decide. Heuristic, no data files, Unicode-safe. Roadmap #428.extractKeyphrases/Keyphrase/KeyphraseOptions(keyphrase_utils.dart) — TF-IDF keyphrase extraction over a single document against a corpus, returning the top-K ranked phrases (optional bigrams). Smoothed IDF guards the single-doc div-by-zero case; built-in English stopword filtering; deterministic tie-breaking. (termFrequenciesis also defined here but hidden from the barrel — the establishedtext_similarity_utilsexport keeps that name; import the file directly to use this one.) Roadmap #432.redlineDiff/RedlineEntry/RedlineOp(redline_utils.dart) — line-based track-changes diff: an LCS alignment classifies each line as unchanged / added / removed / changed (adjacent remove+add runs paired intochanged), each entry carrying its old and new line numbers. Immutable result, built for diff UIs. Roadmap #433.stableMatching/StableMatchingPrefs(stable_matching_utils.dart) — proposer-optimal Gale–Shapley stable matching from two-sided strict preference lists. Handles unequal set sizes and incomplete lists (unranked parties stay unmatched), and throwsArgumentErroron malformed input. Roadmap #448.hierarchicalCluster/cutClustersByCount/cutClustersByDistance/ClusterLinkage(hierarchical_cluster_utils.dart) — agglomerative hierarchical clustering on numeric vectors with single / complete / average linkage (Lance–Williams updates), producing a dendrogram you can cut at K clusters or a distance threshold. Default Euclidean distance, pluggable viaVectorDistance. Small-N intent (naive O(n³)). Roadmap #450.HyperLogLogUtils(hyperloglog_utils.dart) — HyperLogLog-lite approximate distinct count: configurable precision (2^pregisters), register-of-leading-zeros over a SplitMix64-mixed hash, harmonic-mean estimator with linear-counting small-range correction, and a pure register-wisemerge. Roadmap #454.paretoFrontier/ParetoOptions/ParetoDirection(pareto_frontier_utils.dart) — Pareto frontier (dominance filtering) over 2–3 objectives with per-dimension minimize/maximize directions; returns the non-dominated set in original order, retaining duplicates and all-equal points. Roadmap #463.TimeDecayCounter(time_decay_counter_utils.dart) — exponential time-decayed counter with O(1) memory via lazy decay (stored value + last-updated millis), a configurable half-life, and explicit injected timestamps (no wall-clock reads, fully deterministic). Defends against out-of-order timestamps. Roadmap #479.LruLfuCacheUtils(lru_lfu_cache_utils.dart) — bounded cache with hybrid eviction: lowest frequency first, least-recently-used as the tie-breaker.get/put/remove/length, with documented behavior for capacity 0/1 and key updates. Roadmap #480.
1.4.1
Small ergonomic utilities pulled from the Saropa Contacts adoption review — trailing-character trim, an integer-string predicate, and a natural-language Oxford-comma list join — so the app can delete its hand-rolled local copies.
Added
String.removeLastChars(int count)(string_manipulation_extensions.dart) — drop the last N characters, bounds-safe: a zero/negativecountis a no-op and acountat or abovelengthreturns''rather than throwing — so consumers stop hand-rolling thesubstring(0, length - n)guard (Saropa Contacts carried exactly this instring_utils_local.dart). Generalizes the existing single-characterremoveLastChar. Counts UTF-16 code units likeString.length, not graphemes (documented). ENH-001.String.isNumber(string_number_extensions.dart) — a getter that istruewhen the string parses as an integer viaint.tryParse, so consumers stop writingint.tryParse(s) != nullinline. Stricter than the existingisNumeric()(which parses asdouble): a decimal ('4.2') or scientific-notation ('1e3') value isfalsehere buttrueforisNumeric(). Inheritsint.tryParse's rules — accepts a leading sign and0x/0Xhex prefix, trims surrounding whitespace, and returnsfalsefor a magnitude that overflows the native 64-bitint. ENH-002.List<String>.joinDisplayList(...)(list_string_extensions.dart) — join strings into the natural-language form ('Alice','Alice and Bob','Alice, Bob, and Carol') instead ofjoin()'s barea, b, c. Trims each entry and drops blank/whitespace-only ones, de-duplicates by default (isUnique, via the existingtoUnique), and returnsnull— not''— for an effectively-empty input so callers can distinguish "no items". The three joiners (joiner/doubleJoiner/lastJoiner, the last defaulting to the Oxford comma', and ') are named params for locale/style control. ReusestoUnique+takeSafe. ENH-003.Iterable<T>.randomElement({int? seed})(iterable_extensions.dart) — the existing no-argrandomElement()gains an optionalseed, so the pick can be made deterministic (same seed + same iterable → same element) for reproducible demo data and stable widget tests. Routes through the library's ownCommonRandomRNG, replacing the baredart:mathRandom(). Default (no seed) behavior is unchanged — still a fresh pick each run. Picks byelementAt, so the iterable is not materialized to a list. ENH-004.String?.compareStringNullable(...)(string_compare_extensions.dart) — a null-tolerant string comparator, the counterpart to the existingcompareDateTimeNullableforDateTime?. Sorting aList<String?>(or objects by a nullable string field) no longer needs a hand-rolled(a ?? '').compareTo(b ?? ''). Mirrors the DateTime convention —nullsorts before non-null by default — with acaseSensitiveflag (default case-insensitive) and anullsLastflag to pushnulls to the end. Comparison isString.compareTo(UTF-16 code unit, not locale collation; documented). New file, exported from the barrel. ENH-005.StreamDebounceExtensions<T> on Stream<T>—debounce/debounceDistinct/debounceAfterFirst(stream_debounce_utils.dart) — the existing top-leveldebounceStreamfunction gains a chainable extension form so reactive pipelines read asstream.debounce(d).map(...). Plus two variants a database-watch UI needs:debounceDistinct(d, {equals})debounces and suppresses unchanged values, anddebounceAfterFirst(d)emits the first value instantly then debounces the tail — the correct shape for a.watch()stream (Drift, IsarfireImmediately: true) where the initial render must be instant but bulk writes should coalesce.debounceStreamis unchanged (back-compat); its deferred-listen single-subscription controller — which guarantees a late subscriber still receives the first emission (a fixed perpetual-spinner bug) — is now shared by all variants and has a dedicated regression test. ENH-006.MonthWeekdayUtils.nthWeekdayOfMonth/lastWeekdayOfMonth(month_weekday_utils.dart) — static(year, month)-keyed weekday-occurrence helpers, the no-seed counterpart to the existingDateTime.getNthWeekdayOfMonthInYearinstance extension. Calendar-construction code (DST rules, holiday tables) computes occurrences for an arbitrary year/month with no seedDateTimeto hang the instance call on; these take the year/month explicitly.nthWeekdayOfMonth(year, month, n, weekday)returns the nth weekday ornullwhen it does not exist (a 5th Friday in a 4-Friday month), guarding out-of-rangen/month/weekdayso an invalid argument can't compute a neighboring month;lastWeekdayOfMonth(year, month, weekday)("last Sunday of October") has no prior equivalent — the extension only counts from the start. Reuses the instance algorithm for the nth case. New file, exported from the barrel. ENH-007.parseCsv+CsvParseResult/CsvRowError(csv_parse_utils.dart) — an error-accumulating multi-line CSV parser layered over the existing single-lineparseCsvLine, for user-facing imports that must report every bad row rather than abort on the first. Splits on\n(strips trailing\r, skips blank lines), and sends a row toresult.errors(with 1-based line number, raw line, and reason) instead ofresult.rowson an unterminated quote (odd"count) or a column-count mismatch — the expected width coming fromexpectedColumnsor, whenhasHeaderis true, the header row. ENH-008 (part 1).retryWithPolicygainsretryIf(retry_policy_utils.dart) — abool Function(Object error)? retryIfpredicate so only transient failures are retried; returningfalserethrows immediately without consuming the remaining attempts, the delay, or firingonRetry(which already existed).retryWithJitteris intentionally untouched. ENH-008 (part 2).partialRatio/tokenSortRatio/tokenSetRatio(fuzzy_search_utils.dart) — fuzzywuzzy-style standalone string-similarity scores in[0, 1], so a consumer doing single-best-match selection with its own threshold can compute these directly and drop the externalfuzzywuzzydependency. (The per-resultscoreonfuzzySearchwas already public — this adds the missing ratio variants.)partialRatioslides a window for the best substring alignment ('New York'vs'New York City'→ 1.0);tokenSortRatiosorts tokens first for order-insensitivity;tokenSetRatiocompares the shared token core against each side's remainder (forgiving of extra words). All case-insensitive, reusingLevenshteinUtils.ratio. ENH-008 (part 3).
1.4.0
Eleven more utilities from the Roadmap-to-700 set — INI/.env config parsing, RFC 5545 recurrence (parse + expand), a holiday-aware business-day calendar and SLA clock, ISO 8601 interval parsing, an interval-overlap tree, a dependency resolver, a priority task scheduler, a token-bucket rate limiter, and a resource pool — plus the capabilities catalog rebuilt from the Dart AST so every public symbol is listed.
Added
parseIni/parseEnv(ini_parser_utils.dart) — read the two near-universal flat-config formats with no dependency.parseInireturnssection → key → value(pre-header entries under the''global section, declared-empty sections preserved);parseEnvreturns a flatkey → valuemap for dotenv files and strips theexportprefix. The first=is the separator (sourl=http://host:80keeps its colon),#/;full-line comments and blanks are skipped, surrounding quotes are stripped (double-quoted values expand\n \t \r \\ \", single-quoted are literal), and#stays literal in values (no inline-comment stripping) so passwords/URLs/hex colors survive. A non-comment, non-section line lacking=throwsFormatException— strict so config typos surface. Roadmap #626.parseRrule+RecurrenceRule/RecurFrequency/RecurWeekday(rrule_parse_utils.dart) — parse a practical subset of the RFC 5545 recurrence rule used by iCalendar / Google Calendar exports (FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE,FR;COUNT=10) into an immutable, value-equalRecurrenceRule. SupportsFREQ(DAILY/WEEKLY/MONTHLY/YEARLY),INTERVAL,COUNT,UNTIL(yyyyMMdd[THHmmss][Z], UTC vs floating),BYDAY,BYMONTHDAY(1..31 / -1..-31),BYMONTH, andWKST; an optionalRRULE:prefix is tolerated. Part order is irrelevant and duplicates take the last value. Unsupported parts (e.g.BYSETPOS,BYHOUR) throwFormatExceptionrather than being silently dropped, so the subset boundary is explicit.RecurWeekdaycarries itsDateTime.weekdaynumber for the companion iterator. Roadmap #591.expandRecurrence(recurrence_iterator_utils.dart) — the companion toparseRrule: lazily generate the concrete occurrences of aRecurrenceRulefrom a start instant, in ascending order. Async*generator, so an unbounded rule is safe — bound it with the rule'scount/until, thelimitargument, or.take(n). Walks one FREQ×INTERVAL period at a time and expands the BY rules within it: WEEKLY BYDAY positioned relative to WKST, MONTHLY/YEARLY BYMONTHDAY (negative = from month-end) with non-existent days (e.g. day-31 in a 30-day month, Feb-29 off leap years) dropped, BYMONTH filtering. The start supplies each occurrence's time-of-day and UTC-ness and acts as DTSTART (earlier candidates skipped); date math uses calendar fields, notDuration, so it never drifts across DST. Roadmap #592.BusinessCalendar(business_calendar_utils.dart) — a holiday-aware, weekend-configurable working-day calendar, extending the weekend-only free functions indate_time_business_days_utils.dart. Construct with a holiday list (matched by calendar day, time/zone ignored) and an optional custom weekend set ({DateTime.friday, DateTime.saturday}for regions that rest Fri/Sat); reuse it forisBusinessDay/isWeekend/isHoliday,nextBusinessDay/previousBusinessDay,addBusinessDays(skips weekends + holidays, negative goes backward),businessDaysBetween(count,[start, end)), andbusinessDaysIn(the list). Immutable after construction; calendar-field date stepping avoids DST drift. Roadmap #593.TaskScheduler(task_scheduler_utils.dart) — runs async tasks under a fixed concurrency cap, dispatching the highest-priority waiter whenever a slot frees (FIFO among equal priorities). The piece the FIFOAsyncSemaphoreUtilscan't offer: a semaphore admits waiters in arrival order, whereas this reorders the backlog by importance so an urgent task jumps ahead of queued background work (without preempting jobs already running).schedule(task, {priority})returns a future for the task's result; a failed task never stalls the scheduler (the slot is always released). Exposesrunning/pendingfor monitoring; a sub-1concurrencyis rejected. Roadmap #655.TokenBucketRateLimiter(rate_limiter_utils.dart) — smooths bursts to a sustainable average rate: tokens refill continuously attokensPerSecondup to acapacity(the burst ceiling, starts full), and work spends them.tryAcquire([tokens])is the non-blocking allow/deny primitive (no partial spend);timeUntilAvailable([tokens])reports the wait until a denied request would succeed, so the caller chooses to drop, queue, or delay;availableTokens()exposes the current fractional count. Time is read through an injectablenowclosure (defaults toDateTime.now), so refill is fully deterministic under test with noTimeror wall-clock coupling; a backward clock step accrues nothing. Requesting more thancapacity(or fewer than 1) throwsArgumentError. Roadmap #670.ResourcePool<T>(resource_pool_utils.dart) — a bounded, reusing pool for expensive-to-create resources (DB connections, HTTP clients, isolates). Grows lazily up tomaxSize, reuses idle resources, and when all are busy makes further borrowers wait FIFO until arelease.use(action)is the leak-proof entry point (acquire → run → release, even on throw); lower-levelacquire/releaseare also exposed, plusidleCount/inUseCount/waitingCount. A failedcreaterolls back the slot so a transient factory error doesn't permanently shrink the pool.close()disposes idle resources via the optionalonDispose, fails waiting borrowers withStateError, and blocks new acquisitions; resources still checked out at close are the caller's to dispose. Roadmap #666.parseIsoInterval(iso_interval_parse_utils.dart) — parse an ISO 8601 time interval into aDateTimeRange, supporting all three forms:start/end,start/duration, andduration/end(separated by/). Timestamps use Dart's native ISO parsing; the duration half is an ISO 8601 duration (P[nY][nM][nW][nD][T[nH][nM][nS]], weeks folded into days, fractional time components allowed) applied with calendar arithmetic so years/months add as calendar units (Jan 31 + P1M normalizes correctly) and time-of-day + UTC-ness are preserved. A missing separator, a malformed half, two durations, or an inverted (startafterend) interval throwsFormatException. Roadmap #646.IntervalTree<T>+IntervalEntry<T>(interval_tree_utils.dart) — an overlap (stabbing) query index over inclusive[low, high]intervals:queryPoint(x)returns every interval containing a point,queryRange(lo, hi)every interval overlapping a range, andhasOverlap(lo, hi)short-circuits on the first hit — allO(log n + k)instead of anO(n)scan. Built once from a fixed set, balanced by median split and augmented with each subtree's max-highso branches prune. Distinct fromIntervalSchedulingUtils(max non-overlapping subset) andweightedIntervals(DP optimizer): this is the lookup for calendar conflicts, IP-range matching, gap detection. Results come back in ascendingloworder. Roadmap #494.resolveDependencies+PackageManifest/DependencyResolution(dependency_resolver_utils.dart) — resolve a set of root requirements against a universe of available package versions (each with its own dependency constraints), picking one concrete version per package and returning a topological install order (dependencies first). Constraint matching supports*/any, caret (^1.2.0, including 0.x minor-lock semantics), the comparison operators>= <= > < == =, bare exact versions, and space-separated compound constraints (AND). ReusescompareVersionsfor ordering andtopologicalSortfor the install order + cycle detection; throwsDependencyResolutionExceptionon an unknown package, an unsatisfiable constraint set, or a cycle. Greedy highest-version over a fixpoint worklist (terminating, no backtracking — documented as simple-lock-file scope, not a SAT solver). Roadmap #540.SlaCalculator+BusinessHours/OpenWindow(sla_calculator_utils.dart) — compute SLA deadlines and elapsed working time against a weekly open-hours schedule, optionally skipping holidays via aBusinessCalendar(#593).BusinessHoursholds open windows per weekday (OpenWindow(startMinute, endMinute), half-open) with auniformfactory for the common "9-to-5 on weekdays" case.addWorkingTime(start, amount)returns the instant N working hours later (rolling across close boundaries, weekends, and holidays; clamps a before-open start to open);workingTimeBetween(start, end)sums open-hour time in a span;isOpen(at)tests a single instant. Calendar-field stepping avoids DST drift; a fully-closed schedule throwsStateErrorrather than looping. Roadmap #595.QuietHours+QuietWindow(quiet_hours_utils.dart) — "do not disturb" time-of-day blackout windows for deferring notifications.QuietWindow(startMinute, endMinute)is a daily minute-of-day window that may wrap past midnight (start > end, e.g.1320→420= 22:00–07:00).isQuiet(at)tests membership;quietUntil(at)returns the instant quiet ends whenatis muted (else null), chaining back-to-back/overlapping windows into one contiguous stretch — so a held notification can be scheduled for exactly when quiet lifts. Adailyfactory covers the single-window case. Simpler thanBusinessHours(a per-weekday OPEN schedule); quiet windows apply every day. Roadmap #613.BoundedWorkQueue<T>(bounded_work_queue_utils.dart) — a fixed-capacity async producer/consumer channel with backpressure:push(item)returns a future that stays pending while the buffer is full (throttling a fast producer to the consumer's pace) andpull()waits while empty. Hand-off is FIFO and direct (a waiting consumer receives a pushed item without it touching the buffer). Non-blockingtryPush(false when full) /tryPull(null when empty) variants, pluslength/isFull/pendingProducers/pendingConsumers.close()blocks new pushes, fails blocked producers/consumers, and lets consumers drain already-buffered items before erroring. ComplementsTaskScheduler(which is for fire-and-forget concurrency, not flow control). Roadmap #654.SlidingWindowRateLimiter(sliding_window_rate_limiter_utils.dart) — enforces "no more thanlimitevents in any trailingwindow" exactly, by keeping recent event timestamps and counting those still inside the window. The precise counterpart to the token bucket (#670): the bucket smooths to an average rate with O(1) memory and allows bursts to its capacity, this gives an exact rolling-window count with O(limit) memory and no over-limit burst.tryAcquire()records-and-allows or denies;currentCount()andtimeUntilAvailable()(when the oldest event ages out) round it out. Time is read through an injectablenowclosure for deterministic tests; the window's lower bound is exclusive (an event exactlywindowold has expired). Roadmap #685.ReadWriteLock(read_write_lock_utils.dart) — an async reader/writer lock: manyread(action)scopes run concurrently OR onewrite(action)runs exclusively, never both — the right primitive for a read-heavy cache whereAsyncMutexUtilswould needlessly serialize reads. Writer-preference by default (a waiting writer blocks newly-arriving readers, so a stream of reads can't starve a write);writerPreferred: falseswitches to reader-preference for max read throughput. Both scopes release on throw and exposeactiveReaders/isWriteLocked/waitingReaders/waitingWriters. Roadmap #653.MultiIndexCollection<T>(multi_index_collection_utils.dart) — an in-memory table maintaining several secondary hash indexes at once, so the same items can be looked up by different keys in O(1) instead of scanning (a user list queried by id, by email, AND by city). Construct with named key extractors;add/addAll/removekeep every index in sync (empty buckets pruned).getBy(index, key)returns the matching list (non-unique by default),getOneBythe first match (unique-index convenience),containsKeytests presence;all/length/indexNamesexpose the contents. Distinct frombuildInvertedIndex(text search) and the row/column transposers. Roadmap #505.evaluateExpression/evaluateBool(expression_evaluator_utils.dart) — evaluate a string expression over a supplied variable map with NO host access (no function calls, no property access, noeval), so untrusted formula input (a rule, computed column, feature-flag condition) runs without executing arbitrary code. Supports numbers,'string'/"string"literals,true/false, named variables, arithmetic (+ - * / %, unary-), comparison (== != < <= > >=), boolean (&& || !), and parentheses, with correct precedence. Lexing reuses thetokenizepipeline (#434). Any syntax error, unknown variable, or type mismatch throwsFormatException;evaluateBoolis the convenience that requires a boolean result. Roadmap #634.filterRows/compileFilter+RowPredicate(sql_filter_utils.dart) — filter a list ofMap<String, Object?>rows with a SQLWHERE-style clause (age > 18 AND city LIKE 'New%') instead of a hand-written closure.compileFilterparses the clause once into a reusableRowPredicate;filterRowsapplies it. Grammar:AND/OR/NOT/parentheses, comparisons= <> != < <= > >=,LIKE(%any run,_one char, case-sensitive),IN (…),IS [NOT] NULL, and literals (number,'string',true,false,null); keywords are case-insensitive. Ordering across incomparable types yields no match (SQL's unknown→false). Record-oriented and SQL-flavored, distinct from the scalarevaluateExpression(#634); both reuse thetokenizelexer. Roadmap #633.expandUriTemplate(url_template_utils.dart) — expand RFC 6570 URI templates against a variable map, the way an API client builds a request URL from/users/{id}{?fields*}. Covers Levels 1–3 plus the prefix ({var:3}) and explode ({list*}) modifiers: simple{var}and multiple{a,b}, reserved{+var}/ fragment{#var}(keep reserved chars), and the. / ; ? &operators with their separators andname=formatting for the named ones. Values may be string/number/bool/List; an undefined variable contributes nothing; percent-encoding is UTF-8 and RFC 3986-correct. ComplementsUriPattern(#630, which matches paths) — this builds them. Roadmap #629.LogLineParser(log_line_parser_utils.dart) — parse log lines against a format template with{field}placeholders, extracting each field into aMap<String, String>. Literal text between placeholders (spaces, brackets, quotes) delimits the fields, so the common access-log shapes parse without a bespoke regex. PresetsLogLineParser.apacheCommon()/apacheCombined()/nginxCombined()cover the standard formats; a custom format is just a template string, and a field can carry an explicit regex ({status:\d+}) when the default lazy match would over-match.parse(line)returns the field map or null on a non-match;fieldslists the names in order. Roadmap #631.
1.3.0
Ten new utilities from the Roadmap-to-700 set: a forgiving JSON-to-model reader, a CSV writer, a path-template matcher, stream zip/combine operators, multi-key grouping, a swappable cache interface with a write-through loader, date-format presets, ICU plural/select message lite, timing wrappers, and a JSON pretty-printer.
Added
JsonModelReader(json_model_mapper_utils.dart) — reads typed fields (requireString/requireInt/requireBool/requireDouble/requireList/optionalString/child) from decoded JSON, accumulating aValidationErrorslist instead of throwing on the first bad field. Distinguishes missing (code: 'missing') from wrong-type (code: 'type'), widensint→double, and reports nested failures with dotted paths (address.city) on a shared collection. Roadmap #637.writeCsvLine/writeCsv(csv_writer_utils.dart) — the inverse ofparseCsvLine: encode rows to CSV with RFC 4180 auto-quoting (a field is quoted only when it contains the delimiter, a quote, CR, or LF; embedded quotes are doubled). Configurabledelimiter(TSV via\t),eol(CRLF default), andforceQuote. Round-trips withparseCsvLine. Roadmap #622.UriPattern(uri_pattern_utils.dart) — compile a path template (/users/{id}/posts/{slug}) andmatch()concrete paths to extract named segment params, or null on no match. Supports a typed{id:int}constraint (matches only integer segments) and ignores leading/trailing slashes. Segment-based, no regex. Roadmap #630.zipStreams/combineLatestStreams(stream_combine_utils.dart) —zipStreamspairs two streams by index (lock-step, drops the unpaired tail);combineLatestStreamsemits the combination of the latest values whenever either source emits, once both have produced a value. Both forward errors, complete when their sources do, and cancel sources on cancel.combineLatestsubscribes lazily on listen. Roadmap #661.groupByKeys/aggregateByKeys/MultiKey(multi_key_group_utils.dart) — group an iterable by several key selectors at once into value-equalMultiKeybuckets (a rawListcan't be a map key), then optionally reduce each bucket with an aggregator (count/sum/avg per(country, year)). Preserves first-seen order. Roadmap #477.Cache<K, V>interface +WriteThroughCache(cache_interface.dart) — a commonget/set/clearcontract now implemented byLruCache,TtlCache, andSizeLimitCache, so call sites can depend on "a cache" and swap the eviction policy freely.WriteThroughCachewraps anyCachewith an async loader: a miss loads once and stores (read-through), concurrent misses for the same key share one in-flight load (thundering-herd guard), and a failed load is not cached so the next call retries. Roadmap #523.formatDateShort/formatDateMedium/formatDateLong+DateFormatNames(date_format_preset_utils.dart) — dashboard date presets without theintldependency: short is ISO2026-06-10(locale-independent, sorts lexically), medium isJun 10, 2026, long isWednesday, June 10, 2026. Month/weekday names are injected viaDateFormatNames(English default) so the presets render in any language while the layout stays fixed. Roadmap #615.icuPlural/icuSelect(icu_message_utils.dart) — ICU MessageFormat lite:icuPlural(count, {zero, one, other})picks a plural form (English cardinal rules) and substitutes#with the count;icuSelect(value, cases, {other})picks a gendered/category form. No parser, nointl. UnlikeString.pluralize(appends ans), these choose among caller-supplied, locale-routable forms. Roadmap #414.observeAsync/observeSync(observability_utils.dart) — wrap an operation to measure its wall-clock duration and report the outcome through optionalonSuccess(elapsed, result)/onError(elapsed, error, stackTrace)hooks (logging, metrics, tracing), returning the result unchanged or rethrowing the original error. Transparent: timing only, never swallows a failure. Roadmap #680.prettyPrintJson(json_pretty_print_utils.dart) — render decoded JSON as an indented string with a configurableindentwidth (0for compact single-line) and optional recursivesortKeys(viacanonicalizeJson) for stable, diff-friendly output. Roadmap #436.tokenize+TokenRule/Token(tokenizer_pipeline_utils.dart) — a reusable lexer core: walk input taking the first orderedTokenRulethat matches as a prefix, emittingToken(type, value, start)or skipping (shouldSkiprules like whitespace/comments). Rule order resolves ambiguity deterministically; an unmatched position throwsFormatExceptionwith the offset; zero-width matches are rejected so the cursor always advances. Roadmap #434.diffSequences/diffWords/diffSentences+SeqDiffOp/SeqDiffKind(text_diff_structured_utils.dart) — LCS-based structured diff returning an orderedequal/insert/deleteedit script (not a rendered string) so a UI can color or animate changes.diffWords/diffSentencesreuse the existingtokenizeWords/tokenizeSentencessplitters; the genericdiffSequences<T>engine works on any list. Roadmap #415.empiricalCdf/cdfAt/cumulativeHistogram+CdfPoint(cdf_utils.dart) — the cumulative view of numeric samples:empiricalCdfreturns oneCdfPoint(value, p)per distinct value (p = fraction ≤ value),cdfAtevaluates the CDF at a point, andcumulativeHistogramis the running total of the existinghistogramFixed. Complements the bin-counting histogram utils. Roadmap #574.validateJsonSchema+FieldSchema/JsonType(json_schema_utils.dart) — declare a JSON object as afield → FieldSchemamap and validate it in one pass, collecting aValidationErrorslist: required presence (missing), type match (type), andallowed-set/enum membership (enum). A non-map input yields a single object-level type error. Companion toJsonModelReader. Roadmap #636.groupedStats+NumericStats(grouped_stats_utils.dart) — group an iterable by a key and compute the common numeric bundle (count, sum, min, max, mean) per group in a single pass, no custom reducer. Every returned group hascount ≥ 1(no divide-by-zero inmean). The "totals and averages per category" report in one call. Roadmap #571.
1.2.0
A handful of everyday helpers: skip nulls while mapping, a readable none() check, sum or average by a selector, middle-eliding for long strings and paths, and float comparison that shrugs off rounding error. The published download is slimmer, too.
Added
Iterable.none(predicate)(iterable_none_extensions.dart) — the boolean complement ofany; returnstruewhen no element matches (andtruefor an empty iterable, matchingevery). Reads as intent and removes the easy-to-misplace!any(...).Iterable.mapNotNull(selector)/Iterable<T?>.whereNotNull()(iterable_map_not_null_extensions.dart) — map-and-drop-nulls in a single lazy pass, recovering the non-nullable result type without a separatewhereType/cast.Iterable.sumBy(selector)/Iterable.averageBy(selector)(iterable_sum_by_extensions.dart) — numeric sum/mean over a selector, so reductions work on any element type.sumByreturns0for empty;averageByreturnsnullfor empty (no silentNaN).String.truncateMiddle(maxLength, {ellipsis})(string_truncate_middle_extensions.dart) — elides the middle while keeping both ends visible (paths, hashes, IDs). Grapheme-cluster safe, so emoji are never split; degrades to a leading cut when the budget is too small.double.isCloseTo(other, {relativeTolerance, absoluteTolerance})(double_close_to_extensions.dart) — tolerance-based float comparison ((0.1 + 0.2).isCloseTo(0.3)istrue). Combines an absolute floor (meaningful near zero) with a relative tolerance (scales to large magnitudes);NaNis never close, same-sign infinities are.nthSmallest/nthLargest(quickselect_utils.dart) — k-th order statistic via quickselect (median-of-three pivot), O(n) average without a full sort; returnsnullfor an out-of-range k and never mutates the input.Iterable.stableSortBy/stableSort(iterable_stable_sort_extensions.dart) — stable sort that preserves the input order of equal elements, unlike Dart'sList.sort(which is not guaranteed stable) — needed for correct multi-pass sorting.longestCommonSubsequence/longestCommonSubsequenceLength(lcs_sequence_utils.dart) — LCS of two lists (order-preserving, gaps allowed), distinct from the existing contiguous LCS-substring; the length variant uses O(min) space.deepFreeze(deep_freeze_utils.dart) — recursively unmodifiable copy of a map/list/set tree; any mutation at any depth throwsUnsupportedError. A copy, so later edits to the original do not show through.getByJsonPath(json_path_utils.dart) — read a value from decoded JSON by a simple$.a.b[0]path; returnsnullfor any missing/out-of-range segment. Deliberately not full JSONPath (no wildcards/filters/recursive descent).CronSchedule.tryParse+nextRunAfter(cron_utils.dart) — parse a 5-field cron expression (*, lists, ranges, steps) and compute the next run after a given time, with Vixie-cron OR semantics for the two day fields; returnsnullfor malformed expressions and for impossible schedules (no match within four years).parseAcceptLanguage(accept_language_utils.dart) — parse anAccept-Languageheader intoLanguageRanges ordered by quality (stable on ties); dropsq=0, skips malformed entries.parseRangeHeader(range_header_utils.dart) — parse an HTTPRangeheader (bytes=unit) intoByteRanges, supporting explicit, open-ended, suffix, and multi-range forms;nullon unsupported unit or any malformed range.canonicalizeUrl(url_canonicalize_utils.dart) — canonical URL form for dedupe/cache keys: lower-cased scheme/host, default port dropped, query parameters (and repeated values) sorted, optional fragment removal.-
debounceStream(stream_debounce_utils.dart) — re-emits stream values only after a quiet gap (latest-wins per burst); flushes the trailing pending value on close and forwards errors immediately. -
CAPABILITIES.md— a complete per-symbol index of every public utility (1,391 symbols across 352 files), grouped by category with one-line descriptions and per-file import paths, for teams evaluating or adopting the library. Covers every documented public member — methods, getters, functions, constructors, fields, enum values, setters, typedefs, classes, and extensions (verified: zero undocumented public members repo-wide). Generated bytool/gen_capabilities.pyfrom the documented public API; linked from the README's "What's Included" section.
Fixed
- First 1.2.0 publish attempt was rejected by pub.dev validation (exit 65), so the tag/release existed but pub.dev served nothing. Two artifacts —
.favorites.json(VS Code Favorites extension state) andcoverage/lcov.info(generated byflutter test --coverage) — were tracked in git while also matching.gitignorerules.dart pub publish --dry-runemits a warning for "checked-in files ignored by a.gitignore" and exits 65, which the publish workflow treats as a hard failure (the.pubignoretarball trim does not clear this warning — it is about git tracking state, not package contents). Both files are now untracked (kept on disk); the dry run passes and 1.2.0 reached pub.dev. Nolib/changes. - 16 implemented utilities were unreachable via the barrel import. Extensions and helpers that only had direct file imports —
cartesian,diff,firstWhereOrElse,flattenDeep,groupByTransform,mapIndexed,minBy/maxBy,consecutivePairs(and the rest ofiterable_more),allPairs,sortByThenBy,splitAt,symmetricDifference,shuffleWithSeed,topK,race/allSettled/retryTimes, andGestureUtils— are now exported frompackage:saropa_dart_utils/saropa_dart_utils.dart, honoring the README's "one import" promise. A newtest/barrel_exports_test.dartimports only the barrel and exercises each, so the reachability (and absence of any method-name ambiguity) is regression-guarded. The internalhtml_entity_data.dartdata table stays unexported by design.
1.1.6
A republish fix: 1.1.5's exact content reaches pub.dev now that a missing test dependency is declared. No library changes.
Fixed
- Release fix:
dart pub publishfailed validation (exit 65), so 1.1.5 never reached pub.dev.test/async/debounce_utils_test.dartandtest/async/heartbeat_utils_test.dartimportpackage:fake_async/fake_async.dart, butfake_asyncwas only available transitively (viaflutter_test) and was not declared inpubspec.yaml. pub.dev rejects publishing a package whose sources import an undeclared library. Addedfake_async: ^1.3.3todev_dependencies(matching the versionflutter_testresolves). Nolib/changes — this republishes the 1.1.5 content under 1.1.6.
1.1.5
We added a large batch of unit tests across the library and fixed the five correctness bugs they turned up — edit distance, value caching, an async barrier, CSV dialect detection, and search-query parsing.
Fixed
These five correctness bugs were surfaced by the new unit tests (see Maintenance → Tests) and are now fixed and covered by those tests:
damerauLevenshteinDistancescored an adjacent transposition as 2 instead of 1. The rolling-row optimization read the transposition term fromprevRow[j-2](rowi-1), but the OSA recurrence requiresd[i-2][j-2]— two rolling rows are insufficient. Now uses three rolling rows; e.g.'ca'→'ac'and'abc'→'acb'correctly return 1.singleValueCachere-ran its compute on every call when the result wasnull.cached ??= compute()never storesnull; replaced with an explicitcomputedflag so anull-returning compute runs exactly once, as documented. (memoize1was already correct viaputIfAbsent.)AsyncBarrierUtils.signal()threwBad state: Future already completedwhen called more thancounttimes. Added anisCompletedguard so extra signals are a no-op.detectCsvDialect('')(and any tab-free first line) returned a tab delimiter instead of the documented comma, because thetabs >= commastie-break picks tab on0 >= 0. Tab is now chosen only when tabs are actually present.SearchQueryParserUtils.parseSearchQuerykept the leading-in a negated word's text when it preceded a quoted phrase. The pre-phrase branch now strips-like the trailing-words branch; the negation is captured inisNegated.
1.1.4
We cleared three ambiguous-extension clashes that could break importing the package, and documented and tested the nullable helpers that shipped undocumented.
Fixed
-
Ambiguous extension clash — renamed the
T?.toListIfNotNull()method inlib/object/nullable_more_extensions.darttotoListOrEmpty(). It collided with the older, testedMakeListExtensions.toListIfNotNull()inlib/list/make_list_extensions.dart— both extendedT?with the same method name, so any consumer importing the package's barrel hit an ambiguous-extension error. The two have different semantics:toListIfNotNull()returnsList<T>?(nullfor a null receiver);toListOrEmpty()returnsList<T>(empty list for a null receiver). The new name matches its behavior, since "if not null" wrongly implied a nullable result. -
Ambiguous extension clash —
String.truncateWithEllipsis()(BUG-002) — removed the duplicate code-unit-basedtruncateWithEllipsis(int maxLength, [String ellipsis])fromStringLowerExtensions(lib/string/string_lower_extensions.dart). It collided with the established, grapheme-awareStringExtensions.truncateWithEllipsis(int? cutoff)— bothon String, both exported from the barrel — so consumers hit an ambiguous-extension error. Beyond the clash, the two diverged silently for emoji / multi-byte input (UTF-16 code units vs grapheme clusters), so the Unicode-correct version was kept. Added an emoji grapheme regression test. -
Ambiguous extension clash —
String.escapeForRegex()(BUG-003) — removed the duplicateescapeForRegex()(and its now-unused private_regexSpecialCharsRegex) fromStringManipulationExtensions(lib/string/string_manipulation_extensions.dart). It collided with the canonical, testedStringRegexExtensions.escapeForRegex()— bothon String, both exported from the barrel. Output is identical for all input, so no behavior changes.string_extensions.dartnow re-exportsstring_regex_extensions.dartso the method stays reachable via that file unchanged.
1.1.3
Publishing works again: we declared a dependency that was only transitive and fixed the static-analysis score that had been quietly blocking pub.dev.
Fixed
-
Publishing — declared
metaas a direct dependency (it was only transitive). The library importspackage:meta/meta.dartacross 118 files, and pub.dev rejects publishing a package that imports a library it only depends on transitively. This had silently failed every publish since 1.0.6 (the last version actually on pub.dev): the GitHub Actions workflow maskeddart pub publish's exit-65 validation error and reported the run green while pub.dev received nothing. -
Static analysis score — wrapped 52 single-statement
if/else/for/whilebodies in braces across 38 files inlib/to satisfycurly_braces_in_flow_control_structures. pub.dev's pana enforces this lint via the analysis server (which loads thesaropa_lintsplugin), butdart analyzeCLI does not load plugins, so the violations were invisible locally while docking the "Pass static analysis" score to 40/50. The rule is now also enabled explicitly inanalysis_options.yamlsodart analyzeand CI catch any recurrence before publish.
1.1.2
A version bump to push a release through publishing.
1.1.1
We fixed an invalid record return type and made map-key collisions explicit, so two source keys that collapse to one string no longer silently drop a value.
Fixed
parseVersion— removed invalid named positional fields from record return type(int major, int minor, int patch)→(int, int, int)to fixinvalid_field_nameanalyzer error.MapExtensions.toMapStringDynamic(BUG-010) — addedthrowOnDuplicateparameter so callers can detect when two source keys collapse to the sameString(e.g.int1andString'1') instead of silently losing a value. Collision policy is now explicit:throwOnDuplicatethrowsArgumentError,ensureUniqueKeykeeps the first value, default keeps the last. Behavior is unchanged for existing callers.
1.1.0
We dropped a dart:io dependency (you now pass the locale yourself), expanded HTML entity decoding to 278 named entities, and fixed a couple of async and name-collision bugs.
Breaking
DateTimeUtils.isDeviceDateMonthFirst()renamed toisDateMonthFirst({required String localeName})— removesdart:iodependency; caller now passes the locale string.
Enhanced
- HtmlUtils entity expansion: Replaced 35-entity regex-based
replaceAlldecoder with single-pass O(1) Map-lookup scanner covering 278 HTML5 named entities (268 fromhtml_unescapev2.0.0 basic set + 10 beyond Latin-1: trade, euro, bullet, ellipsis, dashes, typographic quotes). Supports all numeric entities (decimalAand hexA), legacy no-semicolon forms per HTML5 spec, and validates Unicode scalar values including surrogate rejection. Entity data derived from Filip Hracek'shtml_unescapepackage (BSD-3-Clause). Tests expanded from 31 to 49.
Fixed
- AsyncBarrierUtils: fixed
StateErrorwhen accessing.futureafter barrier already completed (double-complete guard). - retryWithBackoff name collision: renamed
retryWithBackoffinretry_policy_utils.darttoretryWithJitterto avoid conflict withretry_utils.dart.
1.0.8+1
A large expansion of the library (collections, graph, stats, validation, async, parsing, and many more string utilities), plus documentation and lint fixes.
Added
New and expanded APIs (all exported from package:saropa_dart_utils):
- Collections (
lib/collections/): lis_utils, lcs_substring_utils, sliding_window_aggregate_utils, reservoir_sampling_utils, interval_scheduling_utils, trie_utils, disjoint_set_utils, damerau_levenshtein_utils, knapsack_utils, bloom_filter_utils, nway_merge_utils, ring_buffer_utils, multiset_utils, online_mean_variance_utils, histogram_utils, difference_array_utils, bimap_utils, kmeans_utils, weighted_interval_utils, greedy_set_cover_utils, chunk_overlap_utils, pivot_unpivot_utils, run_detection_utils, stream_quantile_utils, inverted_index_utils, top_k_heap_utils, time_bucket_utils, multi_criteria_sort_utils, columnar_view_utils, window_functions_utils, balanced_partition_utils, bin_packing_utils, prefix_frequency_utils, rolling_hash_utils, dedup_set_expiry_utils, string_pool_utils, row_column_table_utils, priority_map_utils, seeded_shuffle_utils. - Graph (
lib/graph/): graph_utils, bfs_dfs_utils, dijkstra_utils, astar_utils, connected_components_utils, line_simplify_utils, hierarchy_utils, floyd_warshall_utils, topological_sort_utils, mst_utils, critical_path_utils, bipartite_utils, tree_utils, graph_diff_utils, dag_scheduler_utils. - Stats (
lib/stats/): robust_stats_utils, moving_average_utils, data_normalization_utils, quantile_summary_utils, correlation_utils, linear_regression_utils, bucketed_aggregate_utils, confidence_interval_utils, funnel_utils, outlier_mad_utils, percentile_rank_utils, retention_utils, sampling_utils, metric_rollup_utils, log_transform_utils, feature_encoding_utils. - Validation (
lib/validation/): validation_error_utils, path_validator_utils, input_shaping_utils, guard_utils, cross_field_validation_utils, safe_temp_name_utils, password_strength_utils, pii_detector_utils, data_redaction_utils, safe_parse_utils, typed_positive_utils, ip_cidr_utils, jwt_structure_utils. - String (extensions + utils): levenshtein_utils, string_slug/mask/template/regex/wildcard/line/wrap/indent/replace_n/highlight/csv/ansi/words/key_value/split/unicode/case_acronym_extensions; glob_utils, soundex_utils; myers_diff_utils, diff_render_utils, apply_patch_utils, ngram_utils, slug_dedup_utils, fuzzy_search_utils, excerpt_utils, text_similarity_utils, sensitive_scrub_utils, text_chunk_utils, html_sanitizer_utils, tokenize_sentences_utils, markdown_plain_utils, search_query_parser_utils, code_block_extract_utils, url_extract_utils, safe_html_excerpt_utils, template_engine_utils, acronym_extract_utils, text_normalize_pipeline_utils, duplicate_doc_utils, human_name_parser_utils, search_index_utils, markdown_snippet_utils, text_fingerprint_utils, spelling_key_lookup_utils, email_quote_strip_utils, did_you_mean_utils.
- Async: debounce_utils, delay_utils, memoize_future_utils, retry_utils, sequential_async_utils, throttle_utils, timeout_fallback_utils, batch_async_utils, cancel_previous_exception (cancelPrevious + CancelPreviousException), async_semaphore_utils, async_mutex_utils, stream_buffer_utils, exponential_backoff_utils, retry_policy_utils, batch_flush_utils, circuit_breaker_utils, async_barrier_utils, timeout_policy_utils, race_cancel_utils, idempotent_async_utils, stream_window_utils, heartbeat_utils.
- Parsing: csv_parse_utils, email_validation_utils, hex_color_utils, isbn_utils, luhn_utils, parse_bool_utils, parse_list_utils, phone_normalize_utils, semver_utils, size_parse_utils, validate_non_empty_utils, version_parse_utils, version_compare_utils, parsing_more_utils, config_precedence_utils, csv_dialect_utils, parser_error_utils, canonicalize_json_utils, changelog_section_utils, json_diff_patch_utils, nested_query_parser_utils, varint_utils.
- DateTime: date_time_more_extensions, time_rounding_utils, relative_date_bucket_utils, period_split_utils, injectable_clock_utils, timebox_exception (timebox + TimeboxException) (plus existing bounds, business days, duration format/parse, relative, fiscal, week, timezone, clamp, list, overlap).
- Map: map_pick_omit_extensions, map_more_extensions (plus existing deep merge/deep/utils, default, diff, flatten, from_entries, invert, merge, nested, transform, nullable).
- List: list_lower_extensions, list_default_empty_extensions (plus existing binary search, rotate, string, nullable, of_list, make_list, unique).
- Num: num_more_extensions (plus existing math, clamp, compact_parse, format, iterable, lerp, locale, min_max, modulo, prime, factorial, range, round_multiple, safe_division, stats, utils).
- Object / pipe: pipe_compose_utils, nullable_more_extensions (plus existing assert, cast, coalesce, copy_with_defaults, default_value_extensions, identity, pipe, require, shallow_copy).
- Niche: hash_utils, string_diff_utils, checksum_utils, natural_sort_utils, uuid_v4_utils, niche_more_utils (plus color_utils, name_utils, pad_format_utils, random_string_utils).
- URL/Path: path_more_utils (plus path_extension, path_join, url_absolute, url_build, url_encode, url_extensions, url_query).
- Caching: lru_cache, memoize_sync_utils, size_limit_cache, ttl_cache.
- Regex: regex_common_utils, regex_match_utils.
- Testing: debug_utils (exported from barrel).
- Scanner tool (
tool/suggest_saropa_utils.dart): CLI to suggest saropa_dart_utils replacements (e.g.x == null || x.isEmpty→x.isNullOrEmpty). Options:[path],--help,--version. Core intool/suggest_saropa_utils_lib.dart; tests intest/tool/suggest_saropa_utils_test.dart.
Fixed
- avoid_nullable_interpolation in
string_regex_extensions.dart:escapeForRegex()now usesm.group(0) ?? ''so the result never contains\null.
1.0.8
In this release we introduce typed result classes for common operations, split JSON utilities into focused modules, and bring the code in line with lints (named parameters, narrower exceptions, @useResult). We aimed for clearer structure and safer APIs.
Added
Occurrence<T>class (lib/iterable/occurrence.dart): typed result formostOccurrences()andleastOccurrences()methods, replacing record return typesBetweenResultclass (lib/string/between_result.dart): typed result forbetweenResult(),betweenResultLast(), and bracket-extraction methods, replacing record return typesGestureUtils(lib/gesture/gesture_utils.dart): extracted swipe speed/magnitude classification into standalone utility class with public thresholdsJsonEpochScaleenum (lib/json/json_epoch_scale.dart): epoch timestamp scale (seconds, milliseconds, microseconds) extracted fromjson_utils.dartJsonIterablesUtils(lib/json/json_iterables_utils.dart): generic JSON encoding for iterablesJsonTypeUtils(lib/json/json_type_utils.dart): 13 type-safe JSON conversion methods (lists, strings, ints, doubles, booleans, dates, epochs) extracted fromjson_utils.dart@useResultannotations: Added to 40+ public methods across string, datetime, gesture, json, list, map, num, and other extensions to prevent silent discard of return valuesKeyExtractor<T, E>typedef: fortoUniqueBy/toUniqueByInPlaceparameters (prefer_typedefs_for_callbacks)Swipe.toString(): Added string representation for debugging
Changed
Swipeconstructor: Changed from positional to required named parameters (prefer_all_named_parameters)- Boolean parameter renames (
prefer_boolean_prefixes):testDecode→shouldTestDecode,allowEmpty→shouldAllowEmpty,cleanInput→shouldCleanInput,inclusive→isInclusive,startOfDay→isStartOfDay,roundUp→shouldRoundUp - Exception narrowing (
avoid_catch_all): Replaced barecatch (e)with specific exception types (on FormatException) dynamic→Object?: Replaceddynamicreturn types in JSON decode methods (avoid_dynamic_type)- Added
T extends Objectconstraint toGeneralIterableExtensionsgeneric parameter
1.0.7
We split the large string and date-time extension files into smaller modules (everything stays backward compatible), fixed a bunch of lints, and switched to proper test matchers. The codebase is easier to work in and the linter is quieter.
Fixed
- Performance: cached
toLowerCase()call intoBoolNullable, extracted inline RegExp to top-level finals inlowerCaseLettersOnlyandremoveSingleCharacterWords
1.0.6
We ran a full bug audit and fixed 32 issues—date/time and string logic, emoji handling, and JSON/HTML edge cases. Behavior should be more reliable everywhere.
Fixed (32 bugs resolved — full audit)
Critical / Logic Errors
getUtcTimeFromLocal: was adding offset instead of subtracting; usedfloor()instead oftruncate()for negative fractional offsets (e.g. UTC-5:30). Return type narrowed fromDateTime?toDateTime(never null).isDateAfterToday: was an instance method that ignoredthisentirely, only checking thedateToCheckparameter. Removed the parameter — now correctly checks the receiver against today. Added injectable{DateTime? now}for testability.randomElement: was usingDateTime.now().microsecondsSinceEpoch % length(deterministic, biased). Now uses a module-levelRandominstance withnextInt().isBetween: inclusive mode was using==instead ofisAtSameMomentAsfor boundary equality — boundary values were excluded.removeStart: case-insensitive path was callingnullIfEmpty()on the trimmed match, returningnullinstead of the original string on non-match.last(): was using rune-based indexing, splitting multi-codepoint emoji. Now usescharacterspackage grapheme clusters. Also optimized: replacestoList()+sublist()withchars.skip()to avoid full list allocation.toDateInYear: was crashing withArgumentErrorfor Feb 29 → non-leap year. Now returnsnull.cleanJsonResponse: was unescaping\"before detecting outer quotes, corrupting strings like"hello \"world\"". Now detects outer quotes first.
Medium
betweenResult:endOptionalparameter was declared but never consulted — end-not-found always returnednull. Now correctly returns the tail whenendOptional: trueis passed. Default changed tofalseto preserve backward compatibility.isSameDateOrAfter/isSameDateOrBefore: replaced fragile cascaded year/month/day if-chains with cleantoDateOnly()+!isBefore/!isAfter.isJson('[]'): empty array was returningtruewithoutallowEmpty: true, inconsistent with empty object{}behavior. Now requiresallowEmpty: truefor both.isJsoncolon check: was checkingvalue.contains(':')(untrimmed) instead oftrimmed.contains(':').formatDouble: no guard for negativedecimalPlaces—toStringAsFixedwould throwRangeError. Now clamps to 0–20.hasDecimals/formatDouble: did not guard againstNaN/Infinity—NaN % 1returnsNaN(not0). Now returnsfalse/'NaN'/'∞'respectively.unescape(HTML): was mapped to regular space (U+0020) instead of non-breaking space (U+00A0). Fixed.unescape(HTML): numeric entity handler allowed surrogate codepoints (U+D800–U+DFFF) which crashjsonEncode. Now rejected with named constants_surrogateMin/_surrogateMax.addHyphens: accepted any 32-char string without validating hex content. Now validates with_hexOnly32Regex.exclude/containsAny: O(n×m) — converted toSetfor O(n) lookup.toFlattenedList: returnednullfor empty outer but[]for all-empty inners. Now returnsnullconsistently for empty results.
Low / Documentation
isYearCurrent: hardcodedDateTime.now()made it untestable. Converted from getter to method with{DateTime? now}injectable parameter.isDateAfterToday/isTodayetc.: same injectablenowpattern applied for testability.weekOfYear: added warning in docs that value can be 0 or 53 at year boundaries; recommendweekNumber()for ISO 8601 compliance.isMidnight: now checks all time components including milliseconds and microseconds.leastOccurrences: corrected copy-paste doc comment that said "highest" instead of "lowest".formatPrecision: hardcodedtoStringAsFixed(2)whole-number check now uses the actualprecisionparameter.betweenResult: improved doc to explain intentionallastIndexOf("outermost match") design.between: documented special case where emptyendreturns the tail fromstart.takeSafe(0): documented thatcount == 0returns the original list (unliketake(0)).weekOfYear/weekNumber(): documented ISO 8601 edge cases at year boundaries.num.length(): documented scientific notation behavior for values ≥ 1e21.pluralize: removedlength == 1guard that incorrectly skipped single-character strings.forceBetween: corrected misleading dartdoc ("NOT greater than" → correctly describes clamping).truncateWithEllipsisPreserveWords: fixed grapheme-unsafe fallback that could split multi-codepoint emoji; now usescharacters.take()for the search window.toMapStringDynamic: documented silent key collision behavior whenensureUniqueKey: false.timeToEmoji: boundary was>instead of>=— 7:00am showed moon emoji instead of sun.
1.0.5
We rewrote the README with before/after examples and real-world use cases so it’s easier to see what the library does and whether it fits your project.
1.0.4
We fixed a flaky date/time test that sometimes failed in CI. Your test runs should be more reliable now.
1.0.3
We updated the GitHub Actions publish workflow to use OIDC authentication. Publishing to pub.dev works with the current GitHub setup again.
1.0.2
We added a banner to the README so the project is easier to spot at a glance.
1.0.0
First stable 1.0: we switched to the MIT license for broader use, turned on the full saropa_lints tier for quality, and added README badges so you can see pub points, method count, and coverage at a glance.
Changed
- Migrated from GPL v3 to MIT license for broader adoption