extensions 0.7.1 copy "extensions: ^0.7.1" to clipboard
extensions: ^0.7.1 copied to clipboard

A set of APIs for commonly used programming patterns and utilities, such as dependency injection, logging, and configuration.

0.7.1 #

  • Documentation examples are now compiled code. Public API dartdoc references runnable example regions with dartdoc's {@example} directive instead of restating snippets inline, so a sample cannot drift from code that builds. 36 regions across 18 example files are referenced from 38 places in the library docs; example/README.md indexes them.
  • New examples: example_ai.dart (chat client pipeline, custom client, function calling, streaming), example_vector_data.dart (collection definition, filter trees, filtered retrieval), and example_primitives.dart (cancellation and composite change tokens, ChangeToken.onChange). Those three subsystems previously had none.
  • Corrected library documentation that described APIs which do not exist: hosting.dart documented BackgroundService.executeAsync (the method is execute), and the dependency injection, logging, options, caching, HTTP, primitives, diagnostics, file providers, globbing, AI, and vector data barrels each had at least one hand-written snippet replaced by a reference to code that compiles. Some unconverted snippets remain in those barrels and are still unverified.
  • Three examples now import package:extensions/hosting_io.dart rather than reaching into package:extensions/src/.
  • No API or behavior changes.

0.7.0 #

  • AI — chat routing (new; upstream marks this family [Experimental]):
    • Added RoutingChatClient, a template base that selects and invokes another chat client per request, with a RoutingChatClient.fromSelector factory, plus RoutingContext.
    • Added FailoverChatClient and FailoverChatClientAttempt: after a failed invocation another client can be selected, but only while the failure is uncanceled, happened before any streaming output was exposed, and maximumAttemptsPerRequest permits it. Attempts carry an explicit stackTrace so policies can rethrow without losing the original stack.
    • Added OrderedFailoverChatClient (tries clients in order, rethrows the final failure when all fail) and SemanticRoutingChatClient (routes by cosine similarity between the last user message and example-utterance profiles, with SemanticRoutingScoreAggregation and a score-threshold fallback to a default client).
  • AI — new members on existing types:
    • UsageDetails gained inputAudioTokenCount, inputTextTokenCount, outputAudioTokenCount, and outputTextTokenCount, all merged by add().
    • AIFunction.asDeclarationOnly() returns a declaration-only view of a function that describes it but cannot be invoked.
    • List<ChatMessage> gained addMessagesFromResponse, addMessagesFromUpdates, addMessagesFromUpdate (with an optional content filter), and addMessagesFromStream for appending response messages to a conversation history.
  • AI — shared function-invocation engine:
    • FunctionInvokingChatClient and FunctionInvokingRealtimeClientSession now share one internal invocation processor (the upstream Common/ refactor). Function executions emit execute_tool spans through dart:developer's Timeline, and invocation log messages follow upstream wording and levels (unknown functions now log at warning; invocations log at debug, with arguments and results at trace).
    • Behavioral refinements from upstream: declaration-only tools are reported back to the model as not found instead of silently matching nothing, serial invocation stops after a result that requests termination, and cancellation now propagates instead of being captured as a function failure.

0.6.0 #

  • BREAKING — AI function invocation now matches upstream loop limits:

    • Reaching maximumIterationsPerRequest no longer returns a response with unanswered tool calls. Following upstream, the final request omits function declarations from ChatOptions.tools (non-function tools and, when any remain, toolMode are preserved) so the model produces a real answer. If it requests a call anyway, that response is returned without invoking anything. Note that this tool-free request is a real round trip, so a request that reaches the limit now makes one more provider call than before.
    • Exceeding maximumConsecutiveErrorsPerRequest now throws instead of silently returning a partial response. A single failure is rethrown as-is so callers can catch the tool's own error type; multiple failures are combined into an AggregateException, which is now also exported from package:extensions/ai.dart.
    • The limit comparison was >= and is now >, matching upstream: a limit of n tolerates n consecutive failing iterations. A limit of 0 therefore surfaces the first tool failure immediately.
  • AI — provider annotations:

    • AIContent gained an annotations field carrying provider-returned citations (AIAnnotation / CitationAnnotation).
  • AI — OpenTelemetry coverage completed:

    • Added OpenTelemetrySpeechToTextClient, OpenTelemetryHostedFileClient, and OpenTelemetryRealtimeClient (plus its session decorator), each with a matching builder extension.
    • Instrumentation is spans-only, emitted through dart:developer's Timeline. Because the port avoids dart:io, the upstream OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT environment variable has no counterpart — hosts set TelemetryHelpers.enableSensitiveDataDefault at bootstrap instead.
  • HTTP — handler lifetime management:

    • HttpMessageHandler instances are now disposed only after in-flight requests complete, tracked by active/expired handler entries and a timer-driven cleanup cycle. The implementation is web-safe and uses no finalizers.
    • HttpClientBuilder gained addAsKeyed, removeAsKeyed, and configureAdditionalHttpMessageHandlers.

0.5.0 #

  • VectorData — interfaces renamed to Dart conventions:
    • IVectorSearchableVectorSearchable and IKeywordHybridSearchableKeywordHybridSearchable. The old names remain as deprecated typedefs.
  • BREAKING — FileSystemGlobbing rewritten as a faithful upstream port:
    • Matcher now uses a full port of the upstream pattern engine (literal, linear, and ragged patterns with pattern contexts) instead of delegating to package:glob.
    • package:glob's Glob is no longer re-exported from package:extensions/file_system_globbing.dart. Code that relied on the re-export must import package:glob/glob.dart directly.
    • Pattern syntax now follows upstream semantics: exact names, * within a name segment, ** across directory levels, a leading .. for the parent directory, and a trailing / treated as dir/**. The glob-specific ?, [abc], and {a,b} forms are no longer supported.
    • New Matcher constructor parameters: comparisonType (StringComparison.ordinal or ordinalIgnoreCase, matching upstream case-insensitive default) and preserveFilterOrder (applies filters in the order added so a later include can re-admit an excluded file).
    • matchFile/matchFiles now run through the real matcher against an in-memory tree built by the new InMemoryDirectoryInfo.fromPaths, so in-memory results agree with disk-based matching. getResultsInFullPath now returns normalized paths.
    • Fixed the PatternMatchingResult.files setter, which previously assigned the field to itself.
  • AI — chat client structured output:
    • Added ChatClient.getStructuredResponse<T>() and StructuredChatResponse<T> for requesting JSON responses that deserialize into a typed result, with support for schema injection, wrapped-object envelopes, and native JSON response formats.
  • AI — distributed caching:
    • Added DistributedCachingChatClient and ChatClientBuilder.useDistributedCache().
    • Added CachingEmbeddingGenerator, DistributedCachingEmbeddingGenerator, and EmbeddingGeneratorBuilder.useDistributedCache().
  • AI — builder pipeline glue:
    • ChatClientBuilder gained useConfigureOptions, useChatReducer, and useImageGeneration extensions.
    • EmbeddingGeneratorBuilder, ImageGeneratorBuilder, TextToSpeechClientBuilder, SpeechToTextClientBuilder, and HostedFileClientBuilder gained useLogging and (where applicable) useConfigureOptions extensions, asBuilder() on the corresponding client/generator types, and ServiceCollection registration extensions (addEmbeddingGenerator, addImageGenerator, addTextToSpeechClient, addSpeechToTextClient).
  • AI — chat response accumulation:
    • Added public toChatResponse() extensions on Iterable<ChatResponseUpdate> and Stream<ChatResponseUpdate> plus a ChatResponseAccumulator, replacing the private accumulation logic in ChatClientBuilder.
  • AI — DataContent:
    • DataContent.fromUri now parses data: URIs so data and mediaType are populated from the URI contents, and throws FormatException on malformed data URIs.
    • The uri getter now synthesizes a data URI from data and mediaType when the content was created from raw bytes.

0.4.1 #

  • Web-compatible file configuration:
    • File-based JSON configuration is now available from package:extensions/configuration.dart and can read from an injected FileProvider, including memory-backed providers on web.
    • Added a web-safe FileSystemException stand-in for file configuration errors.
  • File providers and globbing:
    • PhysicalFileProvider now supports injected package:file filesystems, allowing in-memory filesystem use in browser and test environments.
    • Polling change tokens, wildcard watching, and Matcher globbing now work through filesystem abstractions instead of direct dart:io access.
    • Resolved a FileSystemException export ambiguity in the aggregate package:extensions/extensions.dart barrel.

0.4.0 #

  • Web compatibility:
    • package:extensions/configuration.dart, hosting.dart, and logging.dart are now web-safe and can be compiled to JavaScript. Console logging falls back to print and disables ANSI colors on web, and the default HostApplicationBuilder skips file-backed configuration and environment variables on web.
    • package:extensions_flutter/extensions_flutter.dart is now web-compatible as a result.
  • BREAKING — JSON file configuration moved to configuration_io.dart:
    • addJson is no longer exported from package:extensions/configuration.dart because it depends on dart:io. It now lives in package:extensions/configuration_io.dart (also re-exported from io.dart and the aggregate package:extensions/extensions.dart).
    • Migration: code that imports configuration.dart directly and calls addJson must add import 'package:extensions/configuration_io.dart';. Code importing package:extensions/extensions.dart is unaffected.
  • Dependencies:
    • Added universal_platform for web-safe platform detection in the console log formatter.

0.3.28 #

  • AI Realtime — Function invocation:

    • Added experimental FunctionInvokingRealtimeClient, FunctionInvokingRealtimeClientSession, and RealtimeClientBuilder.useFunctionInvocation() for automatically invoking AIFunction tools requested by realtime model responses.
    • Function results are sent back to the realtime session as conversation items and the model is prompted to continue the response.
    • Added controls for detailed errors, concurrent invocation, iteration/error limits, additional tools, and unknown-function handling.
  • AI — Bug fix:

    • EmptyServiceProvider now behaves as an empty provider instead of throwing UnimplementedError for optional service lookups.
  • HTTP — Cleanup:

    • Removed a duplicate @override annotation in DefaultHttpClientFactory.createClient.

0.3.27 #

  • Hosting — BackgroundService / Host lifecycle fixes:
    • Host.startAsync no longer awaits a BackgroundService's execute operation, so startup completes once start returns instead of blocking on long-running services (mirrors C# StartAsync semantics).
    • BackgroundService.stop now mirrors C# Task.WhenAny by waiting for the execute operation to complete without observing its error or cancellation, so stopping a faulted or cancelled service no longer rethrows.
    • Host treats an OperationCanceledException from a background service during shutdown as a normal stop rather than logging it as a fault.
    • BackgroundService.dispose is now null-safe when the service was never started.

0.3.26 #

  • AI — OpenAI provider:
    • OpenAIChatClient now honours ChatOptions.rawRepresentationFactory: if the factory returns a Map<String, dynamic>, its entries are merged into the HTTP request body before the request is sent, providing an escape hatch for provider-specific parameters not covered by ChatOptions.

0.3.25 #

  • AI — OpenAI provider:
    • Added OpenAIChatClient — a ChatClient implementation for the OpenAI chat completions API (POST /chat/completions). Supports streaming (SSE), tool calls, response format control (text, json_object, json_schema), and all ChatOptions fields. Configuring OpenAIClientOptions.endpoint to a local server (e.g. http://localhost:1234/v1) makes it compatible with LM Studio, Ollama, and other OpenAI-compatible servers.
    • Added OpenAIEmbeddingGenerator — an EmbeddingGenerator<String, float> for the OpenAI embeddings API, with optional dimensions and defaultModelDimensions support.
    • Added OpenAIImageGenerator — an ImageGenerator for DALL-E and gpt-image-1, returning DataContent (base-64) or UriContent (URL).
    • Added OpenAISpeechToTextClient — a SpeechToTextClient backed by the Whisper transcription and translation endpoints via multipart upload.
    • Added OpenAITextToSpeechClient — a TextToSpeechClient with both non-streaming and streaming audio delivery.
    • Added OpenAIClientOptions — holds endpoint URI (default: https://api.openai.com/v1) and an injectable http.Client for testing.
    • Added OpenAIServiceCollectionExtensions — DI convenience methods (addOpenAIChatClient, addOpenAIEmbeddingGenerator, etc.) on ServiceCollection.
    • Added LoggingChatClientBuilderExtensions.useLogging() — integrates LoggingChatClient into a ChatClientBuilder pipeline, skipping the logging step when the resolved factory is NullLoggerFactory.

0.3.24 #

  • VectorData — expanded abstractions:

    • Added annotation types: VectorStoreDataAttribute, VectorStoreKeyAttribute, VectorStoreVectorAttribute for decorating record classes (intended for code generators or explicit schema construction).
    • Added DistanceFunction and IndexKind string-constant classes for use in vector property configuration.
    • Added full VectorStoreCollectionDefinition record schema with VectorStoreProperty, VectorStoreKeyProperty, VectorStoreDataProperty, and VectorStoreVectorProperty.
    • Added VectorSearchOptions, VectorSearchResult<TRecord>, and RecordRetrievalOptions.
    • Added FilteredRecordRetrievalOptions<TRecord> for filtered, ordered, paginated record retrieval, with OrderByClause.ascending / OrderByClause.descending helpers.
    • Added HybridSearchOptions for keyword + vector hybrid search.
    • Added IVectorSearchable<TRecord> and IKeywordHybridSearchable<TRecord> interfaces.
    • Added deprecated legacy filter clause hierarchy (FilterClause, EqualToFilterClause, AnyTagEqualToFilterClause) for compatibility with code targeting the old C# API surface; prefer VectorStoreFilter and its sealed subclasses.
  • AI — Bug fix:

    • Added name field to FunctionResultContent; FunctionInvokingChatClient now populates it so providers can correlate results back to the originating function declaration.
  • Logging — Cleanup:

    • Renamed ILoggerProviderConfiguration<T> to LoggerProviderConfiguration<T> — the I-prefixed name and its typedef alias have been removed. Update any direct references to the abstract class.
  • Dependency Injection — Bug fix:

    • Fixed getRequiredService error message: was printing Type.runtimeType (always "Type") instead of the actual type name.
  • System — Bug fix:

    • ExceptionBase.toString() now returns "TypeName: message" instead of the default Instance of 'TypeName'.

0.3.23 #

  • Fixed missing export 'ai.dart' in the extensions.dart barrel file.

0.3.22 #

  • AI — Microsoft.Extensions.AI port (Phases 1–4):

    • Phase 1 — Core API gaps:

      • Added ReasoningOptions, ReasoningEffort, and ReasoningOutput types for model reasoning control
      • Added allowBackgroundResponses and rawRepresentationFactory to ChatOptions
      • Replaced merged content types with proper call/result pairs: CodeInterpreterToolCallContent / CodeInterpreterToolResultContent, ImageGenerationToolCallContent / ImageGenerationToolResultContent, McpServerToolCallContent / McpServerToolResultContent, InputRequestContent / InputResponseContent, WebSearchToolCallContent / WebSearchToolResultContent
      • Added abstract ToolCallContent and ToolResultContent base classes
      • Added ToolApprovalRequestContent / ToolApprovalResponseContent for user-in-the-loop approval flows
      • Added AIFunctionDeclaration, AIFunctionFactoryOptions, DelegatingAIFunctionDeclaration, ApprovalRequiredAIFunction
      • Added HostedToolSearchTool and HostedMcpServerTool approval mode hierarchy (AlwaysRequire, NeverRequire, RequireSpecific)
      • Added AIContentExtensions with firstOfType<T>() and allOfType<T>() helpers
      • Added AutoChatToolMode to the public API
    • Phase 2 — New client types:

      • Added TextToSpeechClient pipeline: TextToSpeechClient, TextToSpeechOptions, TextToSpeechResponse, TextToSpeechResponseUpdate, TextToSpeechClientMetadata, DelegatingTextToSpeechClient, ConfigureOptionsTextToSpeechClient, LoggingTextToSpeechClient, TextToSpeechClientBuilder
      • Added HostedFileClient pipeline: HostedFileClient, DelegatingHostedFileClient, LoggingHostedFileClient, HostedFileClientBuilder
    • Phase 3 — OpenTelemetry middleware:

      • Added OpenTelemetryChatClient, OpenTelemetryEmbeddingGenerator, OpenTelemetryImageGenerator, OpenTelemetryTextToSpeechClient decorators
      • Added useOpenTelemetry() builder extension for each client type
      • Added OpenTelemetryConsts with span and attribute name constants
    • Phase 4 — Evaluation framework:

      • NLP evaluators: BleuEvaluator, F1Evaluator, GleuEvaluator with supporting algorithms (BleuAlgorithm, F1Algorithm, GleuAlgorithm, NGram, SimpleWordTokenizer)
      • Quality evaluators: CoherenceEvaluator, CompletenessEvaluator, EquivalenceEvaluator, FluencyEvaluator, GroundednessEvaluator, IntentResolutionEvaluator, RelevanceTruthAndCompletenessEvaluator, RetrievalEvaluator, TaskAdherenceEvaluator, ToolCallAccuracyEvaluator
      • Safety evaluators: CodeVulnerabilityEvaluator, ContentHarmEvaluator, HateAndUnfairnessEvaluator, IndirectAttackEvaluator, ProtectedMaterialEvaluator, SelfHarmEvaluator, SexualEvaluator, ViolenceEvaluator, UngroundedAttributesEvaluator, GroundednessProEvaluator
      • Reporting: ScenarioRun, ReportingConfiguration, ResponseCachingChatClient, disk-based ResponseCache, ResultStore, and ReportingConfiguration factory
  • VectorData — Microsoft.Extensions.VectorData.Abstractions port:

    • Added VectorStore, VectorStoreCollection<TKey, TRecord>, and VectorStoreRecordCollection<TKey, TRecord> abstractions
    • Added VectorStoreFilter sealed hierarchy: EqualToVectorStoreFilter, AnyTagEqualToVectorStoreFilter, AndVectorStoreFilter, OrVectorStoreFilter
    • Added record definition types: VectorStoreRecordDefinition, VectorStoreRecordDataProperty, VectorStoreRecordKeyProperty, VectorStoreRecordVectorProperty
    • Added attribute annotations: VectorStoreRecordData, VectorStoreRecordKey, VectorStoreRecordVector
    • Added options types for all collection operations with distinct method names (getAsync/getBatchAsync/getFilteredAsync, upsertAsync/upsertBatchAsync, deleteAsync/deleteBatchAsync)
    • Added OrderByClause with ascending(field) / descending(field) factory methods
    • Exported from package:extensions/vector_data.dart and included in package:extensions/extensions.dart
  • Bug Fix — Dependency Injection:

    • Fixed getKeyedServices<T>(key) always returning empty or throwing a TypeError. The method now correctly requests Iterable<T> from the provider (mirroring the non-keyed getServices<T>() and the C# GetKeyedServices<T>() implementation), which routes through CallSiteFactory.tryCreateIterable() and aggregates all registrations under the given key.
    • getKeyedServicesFromType(Type, key) now throws UnsupportedError with a clear message (Dart cannot construct Iterable<T> from a runtime Type; use getKeyedServices<T>() instead).

0.3.21 #

  • Updates.

0.3.20 #

  • Updates.

0.3.19 #

  • Code Quality:
    • Improved export visibility in hosting libraries by hiding internal implementation functions (addCommandLineConfig, addDefaultServices, applyDefaultAppConfiguration, createDefaultServiceProviderOptions)
    • Code formatting improvements in AI logging clients (line length fixes)
    • Improved import naming conventions in HostApplicationBuilder to follow Dart style guidelines
    • Fixed documentation reference in FunctionInvocationContext

0.3.18 #

  • Bug Fixes:

    • Fixed PhysicalFileProvider.getFileInfo() and getDirectoryContents() incorrectly handling nested directory paths by removing the first path separator anywhere in the path instead of only at the beginning
    • Fixed LoggerFactory.addProvider() throwing RangeError when adding providers after loggers were already created due to incorrect list index assignment
    • Improved _isUnderneathRoot() validation to prevent false positive matches on paths with common prefixes
    • Fixed file polling tests to account for file system timestamp granularity (1-second precision)
  • Code Quality:

    • Fixed all analyzer issues (import ordering, naming conventions, line length, unused imports/variables)
    • Renamed ArgumentOutOfRangeException.ThrowNegative() and ThrowNegativeOrZero() to follow Dart naming conventions (lowerCamelCase)
    • Improved test reliability by ensuring proper timing for file system timestamp changes
    • Disabled cascade_invocations lint rule to reduce noise in test files
  • Test Improvements:

    • Fixed and re-enabled 3 previously skipped tests
    • All 508 tests now pass with improved timing reliability
    • Added better handling for platform-specific file system behavior

0.3.17 #

  • Bug fixes and improvements.

0.3.16 #

  • Major Feature Additions:

    • Added comprehensive Caching module with in-memory and distributed cache support
    • Added HTTP Client Logging with configurable formatters and redaction
    • Added high-performance LoggerMessage API for zero-allocation logging
    • Added Typed Logger support (Logger<T>)
    • Added advanced Console Formatters (Simple, JSON, Systemd)
    • Added File System Globbing with advanced pattern matching
    • Added Diagnostics module for activity tracking and metrics
  • Caching:

    • New MemoryCache with size limits, priorities, and eviction policies
    • DistributedCache abstraction with in-memory implementation
    • Post-eviction callbacks and cache statistics
    • Sliding and absolute expiration support
    • Examples: example_caching.dart
  • Logging:

    • High-performance LoggerMessage.define API for cached log delegates
    • BufferedLogRecord for structured logging scenarios
    • NullTypedLogger<T> for testing and no-op scenarios
    • Console formatters with customizable output (simple, JSON, systemd)
    • Color support and timestamp formatting
    • Examples: example_advanced_logging.dart, example_console_formatters.dart
  • HTTP:

    • HTTP client logging with request/response tracking
    • Header redaction for sensitive data
    • Configurable handler lifetime
    • Scoped logging integration
    • Example: example_http_client_logging.dart
  • File Providers:

    • Enhanced polling change tokens with debouncing
    • Physical file provider options
    • Improved file watching reliability
    • Example: example_file_providers.dart
  • File System Globbing:

  • Diagnostics:

  • Testing:

    • Added 1000+ new test cases across all modules
    • Comprehensive test coverage for caching, logging, and primitives
  • Code Quality:

    • Fixed all analyzer warnings and errors
    • Improved type inference in examples
    • Removed unused imports and variables
  • Breaking Changes:

    • None - all additions are backward compatible

0.3.15 #

  • Changed logging scope for lifetime messages and added additional tests.

0.3.14 #

  • Updates.

0.3.13 #

  • Bug fixes.

0.3.12 #

  • Updates.

0.3.11 #

  • Exported CancellationTokenRegistration.

0.3.10 #

  • Added const constructor to NullLoggerFactory.

0.3.9 #

  • Exported NullLogger, NullLoggerFactory, and CancellationTokenSource. Changed Logger.logError to not require and exception.

0.3.8 #

  • Bug fixes and updates.

0.3.7 #

  • Bug fixes and updates.

0.3.6 #

  • Downgrading async package.

0.3.5 #

  • Bug fixes and updates.

0.3.4 #

  • Bug fixes and updates.

0.3.3 #

  • Bug fixes and updates.

0.3.2 #

  • Bug fixes and updates.

0.3.1 #

  • Bug fixes and updates.

0.3.0 #

  • Initial version
1
likes
150
points
648
downloads

Documentation

API reference

Publisher

verified publisherjamiewest.dev

Weekly Downloads

A set of APIs for commonly used programming patterns and utilities, such as dependency injection, logging, and configuration.

Repository
View/report issues

License

MIT (license)

Dependencies

async, clock, collection, cross_file, file, glob, http, meta, path, stream_transform, universal_platform, watcher, xml

More

Packages that depend on extensions