πŸ“‘ Dext Framework

July 23, 2026 Β· View on GitHub

Exhaustive master index of all implemented features in the Dext Framework. Each item directly references the implementation unit in Sources/.

Important

Generated via a technical audit ("X-Ray") directly from the source code. No features have been omitted or simplified.


πŸ“‹ 1. Core Framework & Language Foundation

Dext was designed to leverage modern Object Pascal features while maintaining a balance between innovation and compatibility.

1.0 Delphi Compatibility

  • Architectural Minimum: Delphi 2010 (Extended RTTI, Generics, and Attributes).
  • Validated Version: 10.3+ Rio (extensive use of var inline and Managed Records optimizations).
  • 10.1 - 10.2 Support: In community testing phase; requires minor refactoring of inline variables.
  • Web Stencils: Requires Delphi 12.2+.

🧩 1. Dext Core Foundation (Sources\Core + Sources\Core\Base)

1.1 Reflection Engine (Dext.Core.Reflection)

  • TReflection β€” High-performance static facade for Delphi's RTTI system. Maintains a globally shared TRttiContext.
  • Metadata Cache (TTypeMetadata) β€” Global cache of type metadata (properties, fields, attributes) with thread-safe initialization via TMREWSync (Multiple-Read Exclusive-Write). Hot-paths are lock-free.
  • Smart Properties (Prop<T>, Nullable<T>, Lazy<T>) β€” Automatic detection of generic wrappers via PTypeInfo.Name analysis. The metadata cache stores IsSmartProp, IsNullable, IsLazy, InnerType, and direct pointer to the FValue field.
  • Property Path Resolution β€” Recursive resolution of nested paths (e.g., User.Address.Street) via TReflection.GetPropertyValue with TRttiProperty caching per segment.
  • Custom Attribute Scanning β€” GetAttributes<T> and HasAttribute<T> with scanning on fields, properties, and methods. Used by DI, Validation, JSON, and ORM.
  • Property Handlers β€” TPropertyHandler for optimized property access with getter/setter caching.

1.2 Dependency Injection (Dext.DI.Core, Dext.DI.Interfaces, Dext.DI.Attributes)

  • TDextServices β€” Fluent facade for service registration. Methods: AddSingleton<T>, AddTransient<T>, AddScoped<T>, AddSingletonInstance<T>, AddSingletonFactory<T>.
  • Interface/Implementation Mapping β€” Complete decoupling between definitions and concrete logic.
  • TServiceCollection β€” Internal repository of TServiceDescriptor with reverse search (LIFO) to allow registration overrides.
  • TDextServiceProvider β€” IoC container with hybrid storage: FSingletonInstances (ARC/Interfaces) + FSingletonObjects (Non-ARC/Manual Classes) + FScopedInstances/FScopedObjects for scoping.
  • Lifecycles β€” Singleton (global single instance), Transient (new instance per resolution), Scoped (single instance per DI scope via CreateScope).
  • Scope Isolation β€” IServiceScope with TDextServiceScope creating an isolated child provider. Scope destruction releases all scoped objects.
  • Auto-Collections β€” Automatic resolution of IList<T>, IEnumerable<T>, IDictionary<K,V> via TActivator.IsListType/IsDictionaryType.
  • DI Attributes β€” [Inject] for property/field injection, [ServiceConstructor] for explicit constructor selection, overriding the Greedy strategy.

1.3 Object Activator (Dext.Core.Activator)

  • TActivator β€” Central RTTI-based dynamic instantiation engine with 4 CreateInstance overloads:
    1. Manual β€” Explicit positional arguments.
    2. Pure DI (Greedy Strategy) β€” Selects the constructor with the MOST resolvable parameters from the container. Prioritizes the most derived class in case of a tie.
    3. Hybrid β€” Initial positional arguments + DI resolution for the rest.
    4. PTypeInfo-based β€” Instantiation by PTypeInfo (supports classes and interfaces, including auto-instantiation of collections).
  • [ServiceConstructor] Attribute β€” First-pass priority over the Greedy strategy.
  • Constructor Cache β€” Thread-safe cache (TMREWSync) of TConstructorEntry (method + PTypeInfo array of parameters) to avoid redundant RTTI scanning.
  • Field/Property Injection β€” InjectFields processes [Inject] on fields and properties after construction, supporting custom TargetTypeInfo.
  • Default Implementation Registry β€” RegisterDefault(TBase, TImpl) and RegisterDefault<TService, TImpl> for baseβ†’implementation mapping (e.g., TStringsβ†’TStringList).

1.4 JSON Engine (Dext.Json, Dext.Json.Types)

  • TDextJson β€” Static facade for serialization/deserialization with Serialize<T> and Deserialize<T>.
  • Driver Architecture β€” Pluggable IDextJsonProvider (DextJsonDataObjects default, System.JSON alternative). Drivers implement CreateObject, CreateArray, Parse.
  • TJsonSettings (Fluent Record API) β€” Immutable configuration via chaining: .CamelCase, .SnakeCase, .PascalCase, .EnumAsString, .EnumAsNumber, .IgnoreNullValues, .CaseInsensitive, .ISODateFormat, .UnixTimestamp, .CustomDateFormat(fmt), .ServiceProvider(p).
  • Automatic Casing (TCaseStyle) β€” 5 modes: CaseInherit, Unchanged, CamelCase, PascalCase, SnakeCase. Automatically applied during serialization.
  • Enum Serialization (TEnumStyle) β€” AsNumber (ordinal) or AsString (RTTI enum name).
  • Date Formats (TDateFormat) β€” ISO8601, UnixTimestamp, CustomFormat. Default: yyyy-mm-dd"T"hh:nn:ss.zzz.
  • DOM Abstraction β€” IDextJsonNode, IDextJsonObject, IDextJsonArray with strong typing (6 node types: Null, String, Number, Boolean, Object, Array).
  • TJsonBuilder β€” Fluent builder for programmatic JSON construction without strings.
  • Attributes β€” [JsonName] (rename field), [JsonIgnore] (exclude field), [JsonCaseStyle] (class-level override).
  • Architectural Profiles:
    • Dext DOM (IDextJsonNode) β€” Optimized for 99% of use cases (REST APIs, Configs). High-speed random access and object manipulation via in-memory tree (DataObjects engine).
    • Dext UTF-8 (Low-Level Streaming) β€” Surgical tool for Big Data. Zero-allocation sequential processing of massive volumes (GBs) with constant memory footprint.
  • TUtf8JsonSerializer (Dext.Json.Utf8.Serializer) β€” Zero-allocation record serializer. Operates directly on TByteSpan (raw UTF-8) without intermediate string conversion. TJsonRecordInfo caching per PTypeInfo to eliminate RTTI overhead in hot-paths. ToUtf8JSON in the DextJsonDataObjects driver for native UTF-8 output.
  • S54 Direct Codecs β€” Dext.Core.TypeModel, Dext.Core.DirectAccess, Dext.Codecs.Registry, Dext.Serialization.Protobuf, TDextJson, ORM hydration, and the codecs CLI share field plans, enabling direct offset reads/writes, generated protobuf codec registration, static gRPC dispatch by invoker, nested object/list support with explicit ownership, SmartProp/Nullable edge cases, TGUID/TUUID, and .proto export from code-first DTOs. IDE Expert diagnostics are documented as deferred DX work.

1.4b AutoMapper Engine (Dext.Mapper)

  • TMapper β€” Static facade and central registry for object-to-object mapping using Delphi RTTI.
  • Fluent Mapping Configuration β€” TTypeMapConfig<TSource, TDest> record supporting custom mappings using fluent notation:
    • ForMember(DestName, MapFunc) β€” Define custom mapping functions mapping source to target values.
    • Ignore(DestName) β€” Prevent copying specific properties.
  • Instance Mapping β€” TMapper.Map<TSource, TDest>(Source) returns a newly instantiated mapped destination class.
  • In-Place Mapping β€” TMapper.Map<TSource, TDest>(Source, Dest) maps source properties onto an existing destination object reference.
  • Collection Mapping β€” TMapper.MapList<TSource, TDest>(SourceList) maps lists and generic collections automatically.
  • Record Mapping β€” Maps matching fields and properties between classes and records.
  • Default Value Optimization β€” Support for mapping only non-default values using the AOnlyNonDefault parameter to avoid overwriting initialized destination values.

1.5 Configuration System (Dext.Configuration.Core)

  • TDextConfiguration (Fluent Builder) β€” .AddJsonFile(path), .AddYamlFile(path), .AddEnvironmentVariables(prefix), .AddCommandLine, .AddInMemoryCollection.
  • TConfigurationRoot β€” Multi-provider aggregator with LIFO precedence (last registered wins). Implements IConfiguration.
  • Hierarchical Keys β€” Access via : separator (e.g., Database:ConnectionString). GetSection(key) returns sub-tree.
  • Options Pattern β€” IOptions<T>, IOptionsSnapshot<T>, IOptionsMonitor<T> for typed binding of configuration sections to records/classes.
  • Section Validators β€” AddSectionValidator(section, validator) for startup configuration validation.
  • Change Tracking β€” IChangeToken with OnReload callback for hot-reload configuration.

1.6 Type System (Dext.Types.*)

  • TUUID (Dext.Types.UUID) β€” RFC 9562 compliant type with Big-Endian storage (Network Byte Order). NewV4 (random), NewV7 (time-ordered, 48-bit Unix timestamp ms + random). Implicit bidirectional conversion with TGUID (automatic endianness swap) and string. Operators = and <> via CompareMem. Compatible with PostgreSQL uuid and Web APIs.
  • Nullable<T> (Dext.Types.Nullable) β€” Generic wrapper for nullable value types. HasValue, Value, GetValueOrDefault, Clear. Implicit operators: Tβ†’Nullable<T>, Nullable<T>β†’T, Variantβ†’Nullable<T>, Nullable<T>β†’Variant. Comparison via TEqualityComparer<T>.Default. TNullableHelper for low-level access via raw PTypeInfo without generics.
  • Lazy<T> (Dext.Types.Lazy) β€” Thread-safe lazy initialization via TCriticalSection (double-checked locking). ILazy and ILazy<T> interfaces. TLazy<T> (factory-based) and TValueLazy<T> (pre-computed). Implicit operators: Tβ†’Lazy<T>, Lazy<T>β†’T, TFunc<T>β†’Lazy<T>. Ownership management: AOwnsValue parameter controls if the value is destroyed with the lazy wrapper.

1.6b Smart Types & Expression Trees (Dext.Core.SmartTypes, Dext.Specifications.*)

  • TEntityType<T> (Dext.Entity.TypeSystem) β€” Separate definition classes for queries. Allows separating data from metadata by working with pure POCOs, generating the same expression trees without embedding Prop<T> in the entity itself. Ideal for legacy systems or strict separation.
  • Prop<T> (Dext.Core.SmartTypes) β€” Generic record operating in dual mode: (1) Runtime Mode β€” stores value T normally, (2) Query Mode β€” generates expression trees (IExpression / AST) automatically via operator overloading. The central pillar of Dext's LINQ-like fluent DSL.
  • BooleanExpression β€” Hybrid record that can contain a literal Boolean OR an IExpression node (AST). Operators and, or, not, xor automatically generate TLogicalExpression nodes in query mode.
  • Type Aliases β€” StringType, IntType, Int64Type, BoolType, FloatType, CurrencyType, DateTimeType, DateType, TimeType β€” semantic aliases for Prop<T> that make entities self-documenting.
  • Full Operator Overloading β€” =, <>, >, >=, <, <=, +, -, *, /, unary negation β€” all generate TBinaryExpression with boEqual, boGreaterThan, etc., in query mode.
  • String Methods β€” Like, StartsWith, EndsWith, Contains generate TFunctionExpression with the corresponding operation.
  • Collection Methods β€” In(values), NotIn(values), Between(lower, upper), IsNull, IsNotNull.
  • OrderBy β€” Prop.Asc / Prop.Desc return IOrderBy for sorting composition.
  • IPropInfo β€” Ported metadata carrying the physical column name, injected by TPrototype.
  • TQueryPredicate<T> β€” function(Arg: T): BooleanExpression delegate used by the ORM as a query predicate.
  • Expression Tree Nodes (Dext.Specifications.Types) β€” TPropertyExpression, TLiteralExpression, TConstantExpression, TBinaryExpression, TLogicalExpression, TUnaryExpression, TFunctionExpression, TFluentExpression.
  • Nullable<T> Interop β€” Implicit bidirectional conversion between Prop<T> and Nullable<T>.
  • Variant Interop β€” Implicit bidirectional conversion between Prop<T> and Variant.

1.6c Windows Processor Groups & CPU Topology (Dext.Threading.ProcessorGroups)

  • Windows Processor Groups β€” Native support for Windows machines with >64 logical cores. Automatically detects multiple processor groups and binds worker threads using SetThreadGroupAffinity to scale and balance workloads.
  • GetSystemLogicalProcessorCount β€” Helper that queries system-wide processor topology across all groups on Windows (falling back to standard CPUCount on other platforms) to prevent under-provisioning of server IO workers.
  • Round-Robin Group Affinity β€” Auto-allocator that distributes worker threads evenly across available NUMA nodes and processor groups.

1.7 Value Converter Engine (Dext.Core.ValueConverters)

  • TValueConverterRegistry β€” Global converter registry with 3-level lookup: (1) Exact Match by PTypeInfo pair, (2) Kind Match by TTypeKind pair, (3) Fallback for tkVariant source.
  • TValueConverter β€” Execution engine orchestrating conversions, with automatic handling of Smart Types (Prop<T>) and Nullable<T> (detected via TReflection.GetMetadata).
  • 20+ Built-in Converters β€” Variantβ†’Integer/String/Boolean/Float/DateTime/Date/Time/Enum/GUID/Class/TBytes/TUUID, Integerβ†’Enum/String, Stringβ†’GUID/TBytes/TUUID/Integer/Float/DateTime/Boolean, Floatβ†’String, Booleanβ†’String, Classβ†’Class.
  • ConvertAndSet / ConvertAndSetField β€” Conversion + assignment via RTTI in a single call (used by ORM and Model Binding).

1.8 Memory & Span (Dext.Core.Span, Dext.Core.Memory)

  • TSpan<T> β€” Zero-allocation reference to a contiguous memory region. Slice, ToArray, Clear, GetEnumerator (for-in). Bounds checking on all accesses.
  • TVector<T> β€” Efficient, growable stack-allocated vectors for high-speed buffer management.
  • TReadOnlySpan<T> β€” Immutable version of TSpan<T>. Implicit operator TSpan<T>β†’TReadOnlySpan<T> and TArray<T>β†’TReadOnlySpan<T>.
  • TByteSpan β€” Specialized span for bytes. Equals via TDextSimd.EqualsBytes (SIMD-accelerated). EqualsString compares with UTF-8 without allocation. IndexOf, ToString (UTF-8β†’string), ToBytes. Optimized for JSON/REST parsers and network protocols.
  • ILifetime<T> (Dext.Core.Memory) β€” ARC wrapper for Non-ARC object lifecycle management. TLifetime<T> encapsulates an object and automatically releases it when the interface goes out of scope.
  • IDeferred / TDeferredAction (Dext.Core.Memory) β€” Defer pattern (Go-inspired). Action executed automatically in the destructor when the interface goes out of scope. Useful for temporary resource cleanup.

1.9 Threading & Async (Dext.Threading.*)

  • TAsyncTask β€” Fluent Async/Await implementation for asynchronous operations.
  • Work-Stealing Scheduler β€” Efficient task distribution across CPU cores for maximum parallel performance.
  • ICancellationToken β€” Cooperative cancellation with WaitForCancellation(timeout) and IsCancellationRequested. Integrated with Event Bus Lifecycle and Background Services.

1.10 Logging Pipeline (Dext.Logging, Dext.Logging.Sinks.APM)

  • ILoggerFactory β€” Factory for loggers with multiple provider registration. CreateLogger(categoryName) returns a composite ILogger.
  • ILogger β€” Interface with methods per level: Trace, Debug, Information, Warning, Error, Critical. Structured template support with placeholders.
  • Aggregate Logger β€” Each ILogger created by the factory aggregates all registered providers, dispatching every log entry to all simultaneously.
  • TBatchingTelemetrySink β€” Base abstract asynchronous batching sink with queue buffering, thread-safe synchronization, and background thread execution.
  • TSeqLogSink β€” Compact Log Event Format (CLEF) structured logger sink sending batches to Seq servers over HTTP.
  • TOTLPTelemetrySink β€” OpenTelemetry (OTLP/HTTP JSON) telemetry sink for exporting Logs to OTel collectors (SigNoz, Datadog).
  • TTelemetrySinkRegistry β€” Pluggable sink creator registry decoupling circular dependencies between package layers.
  • Fluent Logging Builders β€” Startup extensions supporting AddSeq() and AddOpenTelemetry() with custom batching and service settings.

1.11 Event Bus & Messaging (Dext.Events, Dext.Events.Interfaces)

  • Dext.Events (In-Process) β€” MediatR-inspired Publish/Subscribe system. Enables total decoupling between event producers and handlers.
  • IEventPublisher / IEventHandler β€” Asynchronous event dispatch via DI. Supports multiple handlers for the same event or exclusive handlers.
  • Scoping Support β€” Handlers respect DI lifecycle (Scoped handlers receive the same context as the original request).

1.12 Observability & Telemetry (Dext.Core.Diagnostics)

  • TDiagnosticSource β€” Telemetry infrastructure based on observers. Allows intercepting HTTP request lifecycle and SQL execution without coupling monitoring code to business logic.
  • SQL Logging Hooks β€” Automatic interception of SQL commands, parameters, and execution time, integrated into the framework's logger.
  • Activity Tracking β€” Activity tracking support (CorrelationId) for debugging complex and distributed flows.

1.13 Collections & Concurrency (Dext.Collections.*)

  • Binary Code Folding (TRawList) β€” Invisible base engine consolidating hundreds of generic specializations into a single implementation manipulating raw memory slices, reducing compile times by up to 60% and eliminating Code Bloat from RTL Generics.
  • CPU-Friendly Dictionaries (TRawDictionary) β€” Uses Open Addressing with Linear Probing in contiguous memory (Hash Metadata), eliminating cache misses caused by traditional linked-lists. Up to 6.6x faster lookups than RTL.
  • SIMD Acceleration (Dext.Collections.Simd) β€” Vectorized scans and comparisons (AVX2/SSE2) processing 16 to 32 bytes per clock cycle. Extreme performance (up to 6.8x faster) in native lists.
  • Zero-Allocation Vectors (Dext.Collections.Vector) β€” Native Span<T> integration for slicing and massive buffer processing without allocation or copying in the Memory Manager.
  • TFrozenDictionary<K,V> / TFrozenSet<T> (Dext.Collections.Frozen) β€” Immutable collections ("Write Once, Freeze") designed for aggressive concurrency without contention (Lock-Free Read). Bypassing TCriticalSection instances radically optimizes scaling.
  • TChannel<T> (Dext.Collections.Channel) β€” Go-inspired async communication channels (Lock-Free), with native Backpressure (Bounded Channels) to avoid CPU/memory starvation.

1.14 I/O Writers (Dext.Core.Writers)

  • IDextWriter β€” Thread-safe abstraction for framework output. Implementations: TConsoleWriter (stdout), TWindowsDebugWriter (OutputDebugString with buffering), TStringsWriter (TStringList/TMemo), TNullWriter (silent).
  • SafeWrite / SafeWriteLn (Dext.Utils) β€” Global functions routing output via the active IDextWriter. Automatic console detection. Native Unicode writing via WriteConsoleW (Windows) with UTF-8 fallback for pipes.
  • SafeAttachConsole β€” Attach to parent process console (CMD/PowerShell) or AllocConsole for F5-executed GUI applications.

1.15 Text Escaping (Dext.Text.Escaping)

  • TDextEscaping β€” Centralized text escaping utilities: Html, Xml, Json (manual character-by-character with \uXXXX support), Url. Used by Reporters, Serializers, and RestClient.

1.16 Date Utilities (Dext.Core.DateUtils)

  • TryParseISODateTime β€” Robust ISO 8601 parser (YYYY-MM-DDTHH:NN:SS.ZZZ) with support for variations (separator T or space, optional milliseconds).
  • TryParseCommonDate β€” Multi-format parser: ISO 8601 β†’ dd/mm/yyyy β†’ mm/dd/yyyy β†’ yyyy/mm/dd with automatic format detection.

1.17 Resilience Pipeline (Dext.Resilience)

  • IResiliencePipeline / TResiliencePipeline β€” Fluent record wrapper and interface exposing Polly-style policies. Synchronous and asynchronous generic/non-generic execution support (Execute<T> and Execute).
  • Retry Policy (TRetryPolicy) β€” Handles transient failures with customizable retry count and backoff strategies (linear, exponential backoff with jitter).
  • Circuit Breaker Policy (TCircuitBreakerPolicy) β€” Implements Closed, Open, and Half-Open states, failing fast and throwing ECircuitBrokenException once failure thresholds are exceeded.
  • Fallback Policy (TFallbackPolicy) β€” Intercepts exceptions and returns fallback alternative values or executes fallback actions.
  • Timeout Policy (TTimeoutPolicy) β€” Throws ETimeoutException when operations exceed set duration limits using cooperative task cancellation and asynchronous futures.
  • RestClient Integration β€” TRestClient natively integrates with the resilience engine, enabling backwards-compatible .Retry() and .Timeout() methods, plus custom pipeline configuration.

1.18 Persistent Background Jobs (Dext.BackgroundJobs.*)

  • IJobStorage β€” Decoupled storage abstraction supporting multiple providers.
  • IJobClient / TDextJobs β€” Thread-safe enqueueing client and static utility facade (TDextJobs.Enqueue<T>, TDextJobs.Schedule<T>).
  • TInMemoryJobStorage β€” Memory-only job storage provider designed for rapid local testing.
  • TSqliteJobStorage β€” SQLite database job persistence provider using FireDAC, supporting automated schema creation and transactional safety.
  • TJobServer / TBackgroundJobsService β€” Robust multi-threaded background worker engine running as an IHostedService (TBackgroundService), polling, locking, executing, and monitoring jobs.
  • TJobSerializer β€” RTTI-based method parameter serializer using Dext JSON DOM to serialize and deserialize class method parameters (TValue arrays).

πŸ“š 2. Dext Collections Library (Sources\Core)

2.1 Core Collections (Dext.Collections, Dext.Collections.Base)

  • TRawList<T> β€” Backbone of all collections. Generic list based on dynamic arrays with Move-based insertion/deletion to minimize overhead. for-in support via custom enumerator.
  • TList<T> / IList<T> β€” High-performance generic list. Operations: Add, Insert, Remove, IndexOf, Sort, BinarySearch, Contains, ToArray.
  • TDictionary<K,V> / IDictionary<K,V> β€” Generic hash map supporting TryGetValue, AddOrSetValue, ContainsKey, Keys, Values.
  • THashSet<T> / IHashSet<T> β€” Set of unique values with set theory operations: UnionWith, IntersectWith, ExceptWith.
  • TCollections (Factory) β€” Static factory: CreateList<T>, CreateDictionary<K,V>, CreateHashSet<T>, CreateSortedList<T>, etc.
  • TSmartEnumerator<T> β€” Extensible base enumerator for custom iteration in derived collections.

2.2 LINQ Extensions (Dext.Collections.Extensions)

  • Fluent Operations β€” Where, Select, OrderBy, OrderByDescending, First, FirstOrDefault, Last, Any, All, Count, Sum, Min, Max, Average, Distinct, Take, Skip, GroupBy, SelectMany, Aggregate, Contains, ToList, ToDictionary, ForEach.

2.3 Concurrent Collections (Dext.Collections.Concurrent)

  • TConcurrentDictionary<K,V> β€” Thread-safe dictionary with Lock Striping via TSpinLock array (multiple independent lock buckets to reduce contention).
  • TConcurrentQueue<T> / TConcurrentStack<T> β€” Thread-safe queue and stack for producer/consumer scenarios.

2.4 Frozen Collections (Dext.Collections.Frozen)

  • TFrozenDictionary<K,V> / TFrozenSet<T> β€” Immutable structures optimized for high-read scenarios (.NET 8 FrozenDictionary style). Once constructed, no modifications are allowed, enabling memory layout optimizations.

2.5 Channels (Dext.Collections.Channels)

  • TChannel<T> β€” Go-style async communication primitive for Producer/Consumer pipelines.
  • Bounded Channel β€” Fixed capacity with back-pressure (writer blocks when full).
  • Unbounded Channel β€” Unlimited capacity (writer never blocks).
  • ChannelReader / ChannelWriter β€” Segregated interfaces for reading and writing.

2.6 SIMD & Hardware Acceleration (Dext.Collections.Simd)

  • TDextSimd β€” Vectorized operations with automatic instruction set detection:
    • EqualsBytes β€” Byte array comparison via AVX2 (32 bytes/cycle), SSE2 (16 bytes/cycle), or Pascal fallback.
    • IndexOfByte β€” Linear search accelerated via vector instructions.
    • FillByte / MoveMem β€” Optimized memory fill and copy.
  • Runtime Detection β€” CPUID detection at startup. Automatic selection of the best available path.

2.7 Comparers & Algorithms (Dext.Collections.Comparers, Dext.Collections.Algorithms)

  • TEqualityComparer<T> / TComparer<T> β€” Standard generic comparers supporting primitives, records, and classes.
  • Algorithms β€” Sort (IntroSort), BinarySearch, Reverse, Shuffle.

🌐 3. Dext Web Framework (Sources\Web)

3.1 Bootstrapping & Minimal API

  • TWebApplication β€” Fluent facade for initialization: automatically loads appsettings.json, appsettings.yaml, Environment Variables, registers services, and builds the pipeline in a single chain.
  • Minimal API β€” Direct handler registration via delegates without controllers (app.MapGet, app.MapPost, app.MapQuery).
  • HTTP QUERY Mapping β€” Safe, idempotent data retrieval endpoints utilizing structured request bodies.

3.2 Middleware Pipeline

  • Chain of Responsibility β€” Functional (anonymous delegates) and class-based middlewares with DI constructor injection.
  • Built-in Middlewares β€” Logger, Compression (GZip/Brotli), Exception Handling (ProblemDetails RFC 9457), DeveloperExceptionPage, CORS, StartupLock.

3.3 Routing Engine

  • Dynamic Parameters β€” Routes with {id}, {slug}, and type constraints.
  • API Versioning β€” THeaderApiVersionReader, TQueryStringApiVersionReader, TPathApiVersionReader, TCompositeApiVersionReader (composite strategy).
  • HTTP QUERY Discovery β€” Automatic OPTIONS routing generating standard Allow and Accept-Query headers carrying configured query media types (e.g. application/jsonpath).

3.4 Model Binding

  • Hybrid Binding β€” [FromBody], [FromQuery], [FromRoute], [FromHeader], [FromServices] attributes.
  • Zero-Allocation β€” Direct UTF-8 deserialization to records and classes via TByteSpan.
  • Multipart/Form-Data β€” Upload processing via IFormFile abstraction.
  • Object Lifecycle Management β€” Tracking of objects created by Model Binding with integration to ORM ChangeTracker for automatic ownership transfer.

3.5 Hosting

  • IWebHost / IWebHostBuilder β€” Hosting abstractions. Support for Dynamic Ports (Port 0) with automatic OS assignment.
  • Server Adapters β€” Indy (default, OpenSSL/Taurus SSL), WebBroker Adapter (ISAPI/CGI for IIS/Apache), DCS Adapter (Delphi-Cross-Socket, non-blocking), and Native Server Engine (kernel-mode http.sys on Windows and non-blocking epoll sockets on Linux).
  • Zero-Allocation HTTP Parser (TDextIocpHttpParser) β€” Incremental parsing of HTTP/1.1 request headers directly from network buffers without intermediate heap allocations.
  • IHostedService β€” Background tasks with StartAsync/StopAsync. TBackgroundService with Execute(ICancellationToken).
  • IHostApplicationLifetime β€” Tokens for ApplicationStarted, ApplicationStopping, ApplicationStopped.

3.6 Security & Identity

  • IClaimsPrincipal β€” JWT, Basic Auth (RFC 7617), and Cookie authentication.
  • Rate Limiting β€” Fixed Window, Sliding Window, Token Bucket, Concurrency Limiter.

3.7 Real-time & Caching

  • SSE (Server-Sent Events) β€” Unidirectional event streaming fallback.
  • WebSockets & SignalR Hubs β€” Full RFC 6455 native WebSocket transport with client-to-server masking, handshake handling, and complete integration with Dext.Web.Hubs for real-time bi-directional messaging, group dispatching, and ping/pong keepalives. Natively upgrades HTTP connections using opaque mode (HTTP_SEND_RESPONSE_FLAG_OPAQUE) on HTTP.sys.
  • Delphi Hub Client (SignalR-compatible) β€” Native, high-performance Delphi client library (Dext.Web.Hubs.Client) supporting WebSocket and SSE transports, automated negotiate/handshake protocols, ping heartbeats, and thread-safe callbacks with optional main UI thread marshaling.
  • Caching β€” In-Memory caching engine, and native Redis cache engine (TRedisCacheStore). Generates unique cache keys for HTTP QUERY requests by computing a THashSHA1 hash of the query request body stream. Support for native response cache registration via .UseRedisCache in TAppBuilder. Detailed Health Checks (expandable roadmap under development).

3.8 API Documentation & Scaffolding

  • OpenAPI / Swagger β€” Automatic specification generation.
  • Auto-Migrations (S11) β€” Automatic schema synchronization during startup with table/column rename detection via attributes.
  • View Engine & WebStencils (S09) β€” AST-based template engine (Razor-style), zero-dependency.

3.9 Database as API (Dext.Web.DataApi)

One of Dext's most powerful features: automatic generation of full REST APIs from ORM entities β€” with a single line of code. Not a scaffold that generates code β€” it's a runtime handler mapping entities to endpoints dynamically.

Registration (3 coexisting modes)

  • Automatic by Attribute β€” [DataApi] on the entity + App.MapDataApis at startup. TDataApi.MapAll scans RTTI and registers all decorated entities automatically.
  • Typed Manual β€” TDataApiHandler<TProduct>.Map(App, '/api/products').
  • Fluent Manual β€” App.Builder.MapDataApi<T>(path, DataApiOptions.AllowRead.RequireAuth).

5 Generated CRUD Endpoints

MethodRouteHandler
GET/api/{entity}HandleGetList β€” List with pagination, sorting, and filters
GET/api/{entity}/{id}HandleGet β€” PK lookup (simple or composite)
POST/api/{entity}HandlePost β€” Creates new record, returns 201
PUT/api/{entity}/{id}HandlePut β€” Updates existing record
DELETE/api/{entity}/{id}HandleDelete β€” Removes record

Dynamic Specification Mapping (QueryString Filters)

  • 11 Operators automatically parsed from URL: _eq, _neq, _gt, _gte, _lt, _lte, _cont (LIKE %x%), _sw (LIKE x%), _ew (LIKE %x), _in (IN), _null (IS NULL).
  • Pagination β€” ?_limit=20&_offset=40.
  • Sorting β€” ?_orderby=price desc,name asc.
  • Name Resolution β€” ResolvePropertyName via TReflection.GetMetadata().GetHandlerBySnakeCase to convert URL snake_case to Delphi property PascalCase.
  • Each filter generates an IExpression via TStringExpressionParser.Parse and is injected into the ISpecification β€” the same AST used by Smart Properties.

TDataApiOptions β€” Fluent Configuration API

  • Security β€” RequireAuth, RequireRole(roles), RequireReadRole(roles), RequireWriteRole(roles) β€” Read/write permission separation with integrated JWT validation via IClaimsPrincipal.
  • Allowed Methods β€” Allow([amGet, amGetList]) restricts which endpoints are generated.
  • Multi-Tenancy β€” RequireTenant for tenant isolation.
  • Naming Strategy β€” UseSnakeCase, UseCamelCase for serialization casing control.
  • Enum Style β€” EnumsAsStrings, EnumsAsNumbers.
  • Explicit DbContext β€” DbContext<TMyContext> to select which context to use.
  • Custom SQL β€” UseSql('SELECT ...') for custom queries.
  • Swagger β€” UseSwagger, Tag('Products'), Description('...') for automatic documentation.

Naming Conventions (TDataApiNaming)

  • Auto-Discovery β€” T prefix automatically removed via TReflection.NormalizeFieldName.
  • Pluralization β€” English: yβ†’ies, ch/sh/x/sβ†’es, default β†’s (e.g., TCategory β†’ /api/category).
  • Custom Routes β€” [DataApi('/my/path')] overrides conventions.
  • Case Mapping β€” Delphi property PascalCase β†’ URL snake_case for filters.

Entity ID Resolver (TEntityIdResolver)

  • Automatic PK Type Resolution β€” Delegates to IModelBinder for transparent conversion: Integer, String, TUUID, TGUID.
  • Composite Keys β€” | separator for composite keys (e.g., /api/entity/1|ABC).

Ecosystem Integration

  • DI Scope β€” GetDbContext resolves TDbContext from the DI container (supports multiple contexts via ContextClass).
  • Telemetry β€” TDiagnosticSource.Write('DataApi.ModelBinding.Start/Complete') emits traceable events.
  • Logging β€” All handlers emit logs via Log.Debug/Log.Error with structured templates.
  • Serialization β€” TDextJson.Deserialize + TDextSerializer with per-endpoint configurable settings.
  • Swagger β€” Registered endpoints automatically appear in OpenAPI documentation.
  • [DataApiIgnore] β€” Attribute to exclude specific entities from automatic scanning.

πŸ“Š 4. Dext ORM & Entity Framework (Sources\Data)

4.1 Core Persistence

  • TDbContext β€” Unit of Work with automatic Change Tracking (states: Added, Modified, Deleted, Unchanged). Identity Map for instance uniqueness by primary key.
  • DbSet<T> β€” Generic repository. Operations: Add, Update, Remove, Find, FirstOrDefault, Where, Include, ToList.
  • SaveChanges β€” Persists all tracked changes in a transaction.
  • Fluent Connection Setup & Pooling Auto-Detection β€” Connection builders (UsePostgreSQL, UseFirebird, etc.) support automatic parameter extraction and synchronization with property setters, resolving empty-options/pooling bugs.
  • ConnectionDefName Support (FireDAC) β€” Direct support for FireDAC connection definition names (UseConnectionDef). Automatically queries FDManager.ConnectionDefs to resolve the database dialect, driver ID, and pooling configuration dynamically.
  • Shadow Properties Support β€” Declares columns (like TenantId, CreatedAt, IsDeleted) in database mappings that are tracked and saved without needing to be exposed as physical fields in class declarations.

4.2 Query Engine (LINQ-like)

  • Fluent queries with Projection (Select), Paging (Skip/Take), and Aggregates (Count, Sum, Max, Min, Average).
  • SQL Cache β€” Reuse of generated SQL commands for repeated queries.
  • Strongly-Typed Fluent Joins (JoinInner, JoinLeft, JoinRight, JoinFull, JoinCross) β€” Compiles directly into optimized database-level joins (INNER, LEFT, RIGHT, FULL, CROSS) using explicit condition expressions, implicit auto-resolution via relations metadata (TModelBuilder), or Cross Join Cartesian product execution.
  • Pessimistic Locking β€” FOR UPDATE for concurrency control.
  • Multi-Mapping (Dapper-style) β€” Recursive hydration via [Nested] attribute.
  • Fluent Validation Integration β€” Integrates with validation engine inside SaveChanges to run automatic object verification before executing commits.

4.3 Specification Pattern (Dext.Specifications)

  • Fluent Specification Builder β€” Where, OrderBy, Include, Take, Skip for decoupled and reusable business rules.
  • TExpressionEvaluator (Dext.Specifications.Evaluator) β€” In-memory evaluator for the same AST used by the SQL Compiler. Evaluates IExpression against objects (TObject) or dictionaries (TDictionary<string, Variant>). Supports: comparisons (=, <>, >, >=, <, <=), LIKE (case-insensitive with %), IN/NOT IN, IS NULL/IS NOT NULL, bitwise operations (AND/OR/XOR), arithmetic (+, -, *, /, mod, div), and AND/OR short-circuiting. Automatically unwraps Prop<T> (Smart Types) via RTTI.
  • TStringExpressionParser (Dext.Specifications.Parser) β€” Parser converting "Field Operator Value" strings into IExpression nodes. Automatic type conversion: Boolean, Float (invariant), Integer, String. Used internally by Database as API to transform QueryString filters into expression trees.
  • IExpressionVisitor β€” Visitor pattern for traversing the expression tree, used by both the SQL Compiler (generating SQL) and the Evaluator (in-memory filtering).

4.4 Relationships & Loading

  • One-to-One, One-to-Many, Many-to-Many.
  • Lazy Loading via Proxy Objects (transparent interception).
  • Eager Loading β€” Include/ThenInclude for graph pre-loading.
  • Split Queries Loading β€” Collection navigation properties loaded via dedicated SQL queries using IN bounds parameters to avoid cartesian join explosion.

4.5 Migrations System

  • Automated Code-First evolution with chronological database model snapshots.

4.6 Dialect Support (Polyglot)

  • PostgreSQL, SQL Server, MySQL, SQLite, Oracle, Firebird, InterBase.
  • Legacy Paging β€” Automatic wrapping for ROWNUM in older Oracle/SQL Server versions.

4.7 Soft Delete ([SoftDelete])

  • Declarative Attribute β€” [SoftDelete('IsDeleted')] transforms Remove() into an automatic UPDATE.
  • Custom Values β€” [SoftDelete('Status', 99, 0)] for integers/enums.
  • HardDelete β€” Db.Tasks.HardDelete(Task) for physical deletion.
  • Restore β€” Db.Tasks.Restore(Task) to restore soft-deleted records.
  • Automatic Query Filters β€” Deleted records are invisible by default. IgnoreQueryFilters to see everything, OnlyDeleted for the trash bin.
  • Timestamp Soft Delete ([DeletedAt]) β€” Automatically converts Remove() into an update setting the current timestamp, and generates IS NULL filters for active records (Issue #121).
  • IdentityMap Cleanup β€” Soft-deleted entities are removed from the memory cache after SaveChanges.

4.8 JSON/JSONB Column Queries ([JsonColumn])

  • [JsonColumn] Attribute β€” Marks string properties as JSON columns. [JsonColumn(True)] for JSONB in PostgreSQL.
  • Fluent Query β€” .Json('path') to query properties inside JSON columns: Prop('Settings').Json('role') = 'admin'.
  • Nested Properties β€” Prop('Settings').Json('profile.details.level') = 5 using dot notation.
  • IS NULL β€” Prop('Settings').Json('nonexistent').IsNull for missing keys.
  • Cross-Database β€” PostgreSQL (#>> / indexed JSONB), MySQL (JSON_EXTRACT / JSON_UNQUOTE), SQLite (json_extract + JSON1), SQL Server (JSON_VALUE).
  • INSERT with Cast β€” Automatic ::jsonb in PostgreSQL for [JsonColumn(True)].

4.8b Dialect-Aware Batch Operations (Dext.Entity.BatchStrategy) β€” Spec S59

  • TDextBatchStrategyFactory β€” Dynamic selection of batch UPDATE and DELETE strategies based on TDatabaseDialect.
  • PostgreSQL Strategy (TDextPostgresBatchStrategy) β€” Rewrites batch UPDATE into a single-statement UPDATE table AS t SET ... FROM (VALUES (...), (...)) AS v(...) WHERE t.pk = v.pk and batch deletes into WHERE (pk1, pk2) IN (...).
  • MySQL / MariaDB Strategy (TDextMySqlBatchStrategy) β€” Rewrites batch UPDATE into a single-statement UPDATE table SET col = CASE WHEN pk = x THEN y END WHERE pk IN (...).
  • Native Array DML Strategy (TDextNativeArrayDmlStrategy) β€” Preserves native protocol array binding for Oracle OCI and Firebird 4+.
  • Performance β€” Eliminates FireDAC sequential Array DML emulation bottleneck on PostgreSQL and MySQL, reducing per-record latency from ~650 Β΅s to ~118 Β΅s.

4.9 EntityDataSet (Dext.Data.EntityDataSet)

  • ORM ↔ VCL/FMX Bridge β€” Connects components (DBGrid, FastReport) to TList<T> POCO collections while preserving a clean architecture.
  • Zero-Allocation Memory β€” Access via TEntityMap mapped memory offsets eliminates RTTI or string copying on every record read.
  • LoadFromUtf8Json β€” Direct loading from JSON streams/buffers via TByteSpan without prior encoding conversion.
  • Automatic Setup (AST Parsing) β€” In design-time, "Sync Fields" and "Refresh Entity" Verbs directly parse .pas units and create TFields dynamically without needing to compile the project.
  • Live Data Preview (Hybrid) β€” IDE magic: by providing a TFDConnection and a DataProvider, Dext generates dynamic SQL and displays real data in the Grid during development. In runtime, this SQL is completely ignored, and the component consumes only the injected collections.
  • Expression Filtering β€” DataSet.Filter := 'Score > 100' supported using the same TExpressionEvaluator as the in-memory framework.
  • Auto-Stabilization β€” The Active property is never serialized as True in the DFM; prevents missing instance errors at runtime.
  • DML Memory Mode β€” Append, Edit, Post, and Delete operations natively manipulate the underlying in-memory list.

4.10 Inheritance Mapping

  • TPH (Table-Per-Hierarchy) β€” Automatic polymorphic hydration based on discriminators via attributes.

4.11 Advanced Features

  • Streaming Iterators (Flyweight pattern) β€” O(1) memory for rendering large volumes in SSR views. TStreamingViewIterator<T> iterates on demand during template @foreach.
  • Automatic converters for GUID, Enums, JSONB, and UUID v7.
  • Stored Procedures β€” Declarative execution via [StoredProcedure] and [DbParam].
  • Multi-Tenancy β€” Shared Database (TenantId), Schema Isolation (search_path), Tenant per Database.
  • Bulk / Batch Operations β€” High-performance batch APIs: AddRange, UpdateRange, and RemoveRange supporting raw generic collections (TArray<T>, IEnumerable<T>) for bulk database operations in a single context transaction, featuring configurable automatic chunking (defaulting to 100 records, customizable via WithBulkBatchSize in TDbContextOptions) to optimize network packets and satisfy parameter limit boundaries of DB drivers (e.g. FireDAC).
  • Database Sequence Generators & HiLo (Dext.Entity.Sequences) β€” Declarative mapping of sequences via [Sequence('name', allocationSize)] attribute or fluent UseSequence. Leverages a thread-safe TSequenceManager with a Pooled-lo range optimizer to pre-allocate key ranges in memory, enabling high-performance bulk inserts for entities with sequenced primary keys. SQLite support is emulated via a specialized table (dext_sequences).

4.12 Dynamic Query Filters (Dext.Entity.DbSet, Dext.Specifications.SQL.Generator)

  • IgnoreQueryFilters (Fluent API) β€” Db.Users.IgnoreQueryFilters.ToList β€” bypasses all registered global query filters (Soft Delete, Multi-Tenancy) for a single query. Does not affect subsequent calls.
  • Specification-Level Control β€” ISpecification<T>.IgnoreQueryFilters and ISpecification<T>.IsIgnoringFilters: enables specification classes to declare intent, keeping admin queries self-contained and reusable.
  • IsOnlyDeleted (Spec Integration) β€” ISpecification<T>.IsOnlyDeleted propagates the trash-bin query flag in the same mechanism, allowing OnlyDeleted to be declared in a spec.
  • Scoped Propagation β€” In TDbSet<T>.ToList(ASpec), spec flags are propagated to the internal FIgnoreQueryFilters / FOnlyDeleted state before SQL generation and reset via ResetQueryFlags in a finally block β€” ensuring isolation between calls.
  • SQL Generator Integration β€” TSQLGenerator<T>.GetSoftDeleteFilter returns empty string when FIgnoreQueryFilters is True. GetQueryFiltersSQL exits early for the same reason.
  • Admin Spec Pattern β€” Allows building dedicated specification classes (TAdminListSpec) that call IgnoreQueryFilters in their constructor, enabling declarative, zero-friction access to raw data.

πŸ”Œ 5. Dext Net β€” HTTP Client & Authentication (Sources\Net)

5.1 High-Performance REST Client (Dext.Net.RestClient)

  • Fluent API β€” Consume APIs without visual components. Methods: RestClient('url').BearerToken('...').Get<T>('/path').Await.
  • Fluent REST Request Factory β€” Grouping pattern using Client.Request.Get('/path') to isolate request building, avoiding root-level client scope bloat and return type limitations (Issue #119).
  • Unrestricted Body Payloads β€” Native support for serializing record and TArray<T> in request payloads (Body<T> and the array helper BodyArray<T>), bypassing generic compiler restrictions.
  • Record & Array Deserialization β€” Native deserialization of JSON arrays and objects directly into records and dynamic arrays (TArray<T>) during request execution.
  • Ergonomic Responses β€” Boolean helper IRestResponse.IsSuccess for immediate status code validation in the 200..299 range.
  • Connection Pooling β€” Intelligent TNetHttpClient instance reuse (thread-safe pooling), eliminating TCP/SSL handshake overhead and radically reducing OS resource usage.
  • Auto-Serialization β€” Native integration with Dext's JSON engine for hydrating objects and generic collections (IList<T>).
  • Async First β€” Fully integrated with Dext.Threading.Async with ICancellationToken support for cooperative cancellation and UI Access Violation protection.
  • Retry Logic β€” Automatic recovery with exponential backoff and Async/Await support.
  • Typed Responses β€” Client.Get<TUser>('/users/1') with automatic deserialization.
  • Async Chaining β€” Client.Get<TToken>('/auth').ThenBy<TUser>(...).OnComplete(...).Start.
  • Cancellation β€” ICancellationToken to abort ongoing requests.
  • Pluggable Auth β€” TBearerAuthProvider, TBasicAuthProvider, TApiKeyAuthProvider.
  • Thread Safety β€” Immutable configuration snapshot in Execute; isolated execution via pool.
  • Response Headers β€” Full access via GetHeader (case-insensitive) and GetHeaders (TNetHeaders array).
  • THttpRequestInfo β€” Integration with .http parsers for ad-hoc request execution.
  • Multipart Form Fields with Content-Type β€” Support for specifying custom MIME types (e.g. application/json) for individual form fields in multipart requests via AddFormField and AddMultipartField (Issue #125).
  • Conditional Query Parameters β€” Support for fluently adding query parameters conditionally (QueryParamIfNotEmpty, QueryParamIf, and overloads with default values) to simplify request building (Issue #123).
  • Legacy Compatibility and Indy Fallback β€” Complete abstraction of the HTTP engine (IDextHttpEngine) with automatic fallback using Indy (TIdHTTP) for older IDEs (Delphi XE2 to XE7), active in compilers below XE8 or under the DEXT_FORCE_INDY directive. OpenSSL DLLs required for legacy HTTPS requests.

5.2 Authentication Providers

  • Bearer Token (JWT) β€” Automatic Authorization: Bearer <token> header.
  • Basic Auth (RFC 7617) β€” Base64 encoding of user:password.
  • API Key β€” Customizable header or query string.
  • OAuth 2.0 Client Credentials (RFC 6749 Β§4.4) β€” Automatic token caching, thread-safe refresh with a 30s safety margin to prevent using expired tokens.

5.3 Native Redis Client (Dext.Net.Redis)

  • RESP2/RESP3 Protocols β€” Native high-performance socket execution supporting RESP2 and RESP3 specifications with zero-allocation RESP parsing.
  • Connection Pooling β€” Built-in TDextRedisConnectionPool for managed resource sharing across threads.
  • Reactive Pub/Sub β€” Messaging pipeline using concurrent channels (IChannel<TDextRedisMessage>).
  • RedisJSON & Dext.Json Integration β€” Direct type-safe serialization of Delphi classes to Redis JSON values using the core JSON engine.

πŸ“’ 6. Dext Event Bus (Sources\Events)

6.1 Core Architecture (Dext.Events.Interfaces, Dext.Events.Bus)

  • IEventBus β€” Central in-memory event bus for total decoupling between producers and consumers.
  • IEventHandler<T> β€” Typed interface for event handlers. Multiple handlers per event type, executed in registration order.
  • IEventPublisher<T> β€” ISP (Interface Segregation Principle) facade for components that only publish a specific event type.
  • Synchronous Dispatch β€” IEventBus.Dispatch invokes all handlers and returns TPublishResult with statistics (HandlersInvoked, HandlersFailed, HandlersSucceeded).
  • Asynchronous Dispatch β€” DispatchBackground executes handlers in a separate thread with an isolated DI scope (fire-and-forget).
  • TEventBusExtensions β€” Generic static helpers Publish<T> and PublishBackground<T> that box the event to TValue and delegate to IEventBus.

6.2 Behavior Pipeline (Dext.Events.Behaviors)

  • IEventBehavior β€” Cross-cutting middleware for the event pipeline. Intercept(AEventType, AEvent, ANext) method β€” calling ANext() continues the pipeline; omitting it short-circuits.
  • TEventLoggingBehavior β€” Structured logging via ILogger. Debug before/after handler with elapsed time. Error handling with failure re-raise.
  • TEventTimingBehavior β€” Debug-only, records dispatch time via OutputDebugString.
  • TEventExceptionBehavior β€” Structured exception wrapping in EEventDispatchException with event type name. Re-raise preserves original context.
  • Global vs Per-Event Behaviors β€” Global apply to all events; Per-event apply only to the specific type and execute INSIDE global ones.

6.3 DI Extensions (Dext.Events.Extensions)

  • Services.AddEventBus β€” Registers IEventBus as a Singleton (each Publish creates a child DI scope).
  • Services.AddScopedEventBus β€” Registers as Scoped (handlers share the same scope, ideal for web requests with a shared DbContext).
  • Services.AddEventHandler<TEvent, THandler> β€” Typed handler registration with automatic Transient registration.
  • Services.AddEventBehavior<T> β€” Global behavior. AddEventBehaviorFor<TEvent, T> β€” Per-event behavior.
  • Services.AddEventPublisher<T> β€” Registers IEventPublisher<T> as transient for ISP injection.
  • Services.AddEventBusLifecycle β€” Registers TEventBusLifecycleService as an IHostedService.

6.4 Lifecycle Events (Dext.Events.Lifecycle)

  • TEventBusLifecycleService β€” Background service listening to IHostApplicationLifetime and publishing TApplicationStartedEvent, TApplicationStoppingEvent, TApplicationStoppedEvent to the IEventBus.
  • Hosting Bridge (Dext.Hosting.Events.Bridge) β€” THostingLifecycleEventBridge for integration with the background services builder via AddLifecycleEvents.

6.5 Testing Support (Dext.Events.Testing)

  • Infrastructure for testing handlers and behaviors with pipeline mocking.

6.6 Aggregate Exception Handling

  • EEventDispatchAggregate β€” Aggregate exception containing Errors: TArray<string> with one entry per failed handler. All handlers are always invoked before raising.

πŸ§ͺ 7. Dext Testing Framework (Sources\Testing)

7.1 Test Runner & Dashboard

  • CLI Runner β€” High-performance command-line executor (dext test) with support for category and priority filtering.
  • Live Dashboard β€” Built-in visual host for real-time test monitoring with failure history and stack trace analysis.
  • Fluent Runner API (Dext.Testing.Fluent) β€” Programmatic configuration: TTest.Configure.Verbose.RegisterFixtures([...]).Run.

7.2 Attribute-Based Runner (Dext.Testing.Attributes)

Write tests without base class inheritance using RTTI metadata.

  • Core Attributes β€” [Fixture], [Test], [Fact], [TestClass].
  • Lifecycle Management β€” [Setup], [TearDown], [BeforeAll], [AfterAll], [AssemblyInitialize], [AssemblyCleanup].
  • Data-Driven Testing β€”
    • [TestCase(A, B, Expected)] β€” Inline parameterized tests.
    • [TestCaseSource('MethodName')] β€” Dynamic data providers via methods.
    • [Values(V1, V2)], [Range(Start, Stop, Step)], [Random(Min, Max, Count)] β€” Automatic case generation.
    • [Combinatorial] β€” Execute all possible parameter combinations.
  • Execution Filters & Control β€”
    • [Ignore('Reason')], [Skip('Reason')] β€” Skip tests.
    • [Explicit] β€” Tests run only when explicitly selected.
    • [Category('Tag')], [Trait('Name', 'Value')] β€” Categorization and filtering.
    • [Timeout(ms)], [MaxTime(ms)], [Repeat(n)], [Priority(n)] β€” Execution and performance control.
    • [Platform('Windows, Linux')] β€” OS-specific restrictions.

7.3 Fluent Assertions (Dext.Assertions)

Fluent API based on the Should(Value) pattern.

  • Typed Assertions β€” Specific methods for ShouldString, ShouldInteger, ShouldDouble (approximation), ShouldBoolean, ShouldDateTime, ShouldGuid, ShouldUUID, ShouldObject.
  • List/Collection Assertions β€” Should(List).HaveCount(5).Contain(X).OnlyContain(Predicate).AllSatisfy(Predicate).
  • Structural Comparison β€” BeEquivalentTo for deep object and collection comparison (order-independent).
  • Soft Asserts β€” Assert.Multiple(procedure ... end) to collect multiple failures in a block before failing the test.
  • Action Assertions β€” Should(Proc).Throw<EException>().WithMessageContaining('...').

7.4 Snapshot Testing

  • MatchSnapshot('name') β€” Verify complex objects and JSON payloads via disk-based baseline comparison.
  • Structural JSON Compare β€” Smart comparison that ignores formatting and property order in JSON.
  • Update Mode β€” SNAPSHOT_UPDATE=1 environment variable for automatic baseline updates.

7.5 Mocking & Interception (Dext.Mocks, Dext.Interception)

  • Dynamic Proxies β€” TProxy (Interfaces) and TClassProxy (Classes with virtual methods) via TVirtualInterface and TVirtualMethodInterceptor.
  • Fluent Mocking β€” Mock<T>.Setup.Returns(Val).When.Method(Args).
  • Argument Matchers β€” Arg.Any<T>, Arg.Is<T>, Arg.IsNotNull<T>.
  • Verification β€” Received(Times.Once), Received(Times.AtLeast(n)).
  • Auto-Mocking β€” TAutoMocker for automated mock injection into the DI container during unit tests.

7.6 Reporting & CI/CD (Dext.Testing.Report)

  • Multi-Format Export β€” JUnit XML, xUnit XML, TRX (Azure DevOps), HTML (Dark Theme), JSON.
  • SonarQube Integration β€” Generate code coverage and failure reports compatible with Quality Gates.
  • Decoupled TestInsight Integration (Dext.Testing.TestInsight) β€” Decoupled execution hook and listener for TestInsight plugin that automatically routes test runs and results to the IDE without framework compile-time coupling.
  • Decoupled Test Runner Integration & Registry (Dext.Testing.Integration) β€” Command-line registry and parameter processing system enabling decoupled executions from the IDE or CLI without intermediate BPL dependencies.
  • Native DUnitX Integration (Dext.Testing.DUnitX) β€” Decoupled runner adaptation for DUnitX that pipes real-time results, status streams, and filtering logic over local HTTP/SSE to the Dext Test Explorer IDE Expert.
  • Native DUnit Integration (Dext.Testing.DUnit) β€” Decoupled runner adaptation for DUnit that registers custom listeners to pipe results, duration metadata, and execution streams to the Dext Test Explorer.
  • Native DUnit2 Integration (Dext.Testing.DUnit2) β€” Decoupled runner adaptation using proxy interfaces to pipe real-time results and suite hierarchies from DUnit2 frameworks to the Dext Test Explorer.
  • Test Context Injection β€” ITestContext injectable via parameter for WriteLine, AttachFile (screenshots), and execution metadata.

🎨 8. Dext Template Engine (Sources\Core\Base\Dext.Templating)

8.1 Core Architecture

  • ITemplateEngine β€” Main interface: Render(template, context) and RenderTemplate(name, context).
  • TDextTemplateEngine β€” Complete implementation with AST (Abstract Syntax Tree) parser. Each directive is compiled into a node (TTemplateNode) with a Render method.
  • ITemplateContext β€” Hierarchical context with string values, objects, and lists. CreateChildScope for nested scoping.

8.2 Template Loader

  • ITemplateLoader β€” Pluggable interface for loading templates. Implementations: FileSystem and In-Memory.

8.3 Node Types (AST)

  • TTextNode (literal text), TExpressionNode (interpolation {{ var }}), TIfNode/TElseIfNode/TElseNode (conditionals), TForEachNode (iteration with @index, @first, @last), TBlockNode (named blocks), TExtendsNode (layout inheritance), TSectionNode (sections), TMacroNode (reusable macros), TBreakNode/TContinueNode (loop flow control).

8.4 Expression Engine

  • Expression parser with support for arithmetic, comparison, and logical operators (and, or, not).
  • Chained Filters β€” {{ value | upper | truncate(10) }} with filter pipeline.
  • Filter Registry (ITemplateFilterRegistry) β€” RegisterFilter(name, func) for custom filters.
  • Built-in Filters β€” upper, lower, capitalize, truncate, default, date, html_escape, etc.

8.5 Advanced Features

  • Layout Inheritance β€” {% extends "base.html" %} with block overrides.
  • Whitespace Control β€” {%- -%} for whitespace control in directives.
  • HTML Mode β€” IsHtmlMode for automatic output escaping.
  • Source Position Tracking β€” TSourcePos with line, column, and filename for precise error reporting.
  • ETemplateException β€” Exceptions with position and template snippet for debugging.

βœ… 9. Dext Validation Engine (Dext.Validation)

  • Attribute-Based Validation β€” RTTI decorators: [Required], [StringLength(min, max)], [Range(min, max)], [RegularExpression(pattern)], [EmailAddress], [Url].
  • Fluent Validation API β€” Strongly-typed validation base class TAbstractValidator<T> implementing IValidator<T> as a modern C# FluentValidation-like alternative.
  • Fluent Rule Builder β€” Memory-efficient record TValidationRuleBuilder<T> that avoids heap allocations while building chained validation rules (Required, Length, Range, EmailAddress, Matches, MatchesPattern, Must, When).
  • Smart Property Integration β€” Concrete RuleFor overloads for standard Prop<T> smart properties (e.g., Prop<string>, Prop<Integer>, Prop<Boolean>, etc.) to automatically extract property names from Prototype ghost entities without magic strings or compiler casting issues.
  • Pattern Registry β€” TValidationPatterns registry mapping keys to locale-specific regular expressions (e.g. Pt-BR or En-US phone numbers and zipcodes).
  • TValidator β€” Non-generic helper: Validate(obj) returns TValidationResult with a list of TValidationError (field + message).
  • TValidator<T> β€” Typed generic version.
  • Custom Validators β€” Inherit from ValidationAttribute for custom business rules.
  • Web Integration β€” Automatic resolution of registered validators (IValidator<T>) from the Dependency Injection (DI) container inside the web model binding pipeline (THandlerInvoker.Validate), raising TWebValidationException to yield structured error JSON/HTMX payloads.

πŸ”„ 10. Dext Mapper (Dext.Mapper)

  • TMapper β€” AutoMapper-like for DTO↔Entity transformation.
  • CreateMap<TSource, TDest> β€” Mapping registration with automatic property reflection by name.
  • ForMember β€” Mapping override for specific properties with custom lambda expressions.
  • Map<TSource, TDest> β€” Mapping execution with automatic destination instance creation.
  • Collection Mapping β€” Automatic mapping of lists and arrays.

🏒 11. Dext Multi-Tenancy (Dext.MultiTenancy)

  • ITenantProvider β€” Abstraction for current tenant identification.
  • ITenantConnectionStringProvider β€” Dynamic connection string resolution per tenant.
  • Strategies β€” Shared Database (TenantId discriminator), Schema Isolation (search_path in PostgreSQL), Database per Tenant.
  • DI Integration β€” Registered as a Scoped service for resolution per request.

πŸ–₯️ 12. Desktop UI & Design-Time (Sources\UI, Sources\Design)

12.1 Navigator Framework (Flutter-style)

  • ISimpleNavigator β€” Push/Pop/Replace/PopUntil navigation with TValue data passing.
  • 3 Adapters β€” TCustomContainerAdapter (embed frames in panel), TPageControlAdapter (tabs), TMDIAdapter (child windows).
  • Middleware Pipeline β€” TLoggingMiddleware, TAuthMiddleware, TRoleMiddleware β€” same architecture as the Web pipeline.
  • Lifecycle Hooks β€” INavigationAware with OnNavigatedTo(Context) and OnNavigatedFrom.
  • DI Integration β€” Navigator registered as a Singleton service in the container.

12.2 Magic Binding (Dext.UI.Binding)

  • Two-Way Attribute-Based Binding β€” [BindEdit('Name')], [BindCheckBox('Active')], [BindText('ErrorMessage')].
  • Nested Properties β€” [BindEdit('Customer.Address.City')] with dot notation.
  • Message Dispatch β€” [OnClickMsg(TSaveMsg)] eliminates manual OnClick handlers.
  • Custom Converters β€” IValueConverter with Convert/ConvertBack for complex types (e.g., TCurrencyConverter).
  • TBindingEngine β€” Central engine automatically synchronizing ViewModel ↔ UI.

12.3 MVVM Patterns

  • Clean architecture with ViewModel + Controller + DI.
  • Validation Integration β€” FViewModel.Validate with errors automatically reflected in the UI via binding.

12.4 Infrastructure

  • Interception Engine β€” Proxy engine for method interception, base for Mocks and AOP (Aspect-Oriented Programming) features.
  • Design-Time Experts β€” IDE Grid Data Preview and specialized metadata property editors.

12.5 Design-Time Scaffolding Experts (Dext.EF.Design.Scaffolding)

  • TSelectionEditor Integration β€” Non-invasive context menu integration for TFDConnection and TDataSet (FireDAC and Generic). Dext menus coexist with native IDE menus.
  • TTableSelectionForm β€” Advanced selection UI with real-time filtering, "Select All/None" shortcuts, and live table/selection counters.
  • Live Scaffolding Preview β€” High-fidelity preview window with real-time code generation, statistics (Entities/Metadata/Lines), and style switching (POCO vs. Smart).
  • Smart PascalCase Engine β€” Acronym-aware naming logic (EmployeeID β†’ EmployeeId, ReportsTo preserved) with support for snake_case and ALL_CAPS normalization.
  • Enhanced Meta-Inference β€” Precise AutoInc detection via RTTI and ftAutoInc, ensuring 1:1 parity with database schema.
  • IOTA Automation β€” Seamless creation of new units in memory and automatic association with the active Delphi project.

πŸ› οΈ 13. Dext CLI & Scaffolding (Tools\Dext.Tool.Scaffolding)

  • Dext CLI (S01) β€” Unified CLI engine (dext.exe) for project management.
  • Advanced Scaffolding β€” Project and file generation via smart templates: dext new (projects), dext add (controllers, entities, middlewares).
  • Template Logic β€” Direct integration with Dext.Templating for complex logic within scaffolding templates.
  • Dext Doc β€” Automated technical project documentation generation.
  • dext test β€” CLI-based test execution and coverage report generation.
  • dext ui β€” Web dashboard for real-time test monitoring.

πŸ” 14. Observability & Telemetry (Sources\Core\Base)

  • TDiagnosticSource (S03) β€” Centralized event publisher based on JSON payloads, ensuring decoupling between producers (ORM, Web) and consumers.
  • Telemetry Bridge (Dext.Logging.Telemetry) β€” Automatic ILogger integration, enabling HTTP and SQL telemetry visualization in console or log files.
  • SQL Capture β€” ORM native SQL instruction extraction and formatting for real-time auditing.
  • HTTP Lifecycle β€” Latency, status codes, and web framework route tracing.
  • Stack Trace Extraction (Dext.Core.Debug) β€” Precise and detailed stack trace extraction at the point of exception. Critical for debugging highly integrated frameworks with dynamic execution flows.

πŸ€– 15. AI Skills & Developer Experience (Docs\ai-agents)

  • Native AI Skills β€” Modular instruction files (dext-web.md, dext-orm.md, dext-auth.md) teaching AI assistants (Cursor, Antigravity, Copilot, Claude) to generate idiomatic Dext code.
  • 3 Integration Modes β€” Direct copy to .agents/skills/, global custom configuration, or symlinks.
  • Modular by Design β€” Atomic skills to save context tokens; load only relevant modules for the current feature.
  • Compatibility β€” Claude Code, Cursor, Antigravity, Cline, OpenCode, GitHub Copilot.

🌐 16. SSR & View Engines β€” Advanced Features

16.1 HTMX Integration

  • Auto-Detection β€” The pipeline automatically detects HX-Request headers and suppresses the global layout on compatible endpoints.
  • Partial Rendering β€” Results.View<T>('fragment', Query).WithLayout('') for partial fragment rendering without layout.
  • Full-Stack SPA Feel β€” Combines server-side SSR with dynamic HTMX swapping for highly responsive apps without heavy JavaScript.

16.2 Flyweight Iterators (Streaming SSR)

  • O(1) Memory β€” TStreamingViewIterator<T> iterates on demand during template @foreach. 10.000 records rendered using memory equivalent to a single object.
  • No ToList β€” Pass Db.Customers.QueryAll directly to Results.View<T>('customers', Query) and the framework automatically engages streaming.
  • Smart Properties in Templates β€” @(Prop(item.Name)) for automatic Prop<T> unwrapping inside HTML templates.

16.3 Web Stencils (Delphi 12.2+)

  • Native Provider β€” Services.AddWebStencils(...) with entity whitelisting via TWebStencilsProcessor.Whitelist.Configure.
  • Agnostic β€” Same IViewEngine interface for Dext Template Engine and Web Stencils; switch without changing code.

πŸ§ͺ 17. Quality & Testing (Scale and Rigor)

Dext is continuously validated by a massive testing infrastructure to ensure integrity across its subsystems:

  • Engineering Statistics β€” The project exceeds 200,000 lines of pure Pascal code (excluding templates and documentation), reflecting a massive investment in stability and high-level abstractions.
  • Massive Coverage β€” Hundreds of test suites with thousands of individual assertions validating everything from the Core (Memory, Collections) to complex Web and ORM integrations.
  • Multi-DB Matrix (ORM) β€” The persistence engine is exhaustively tested across a real matrix of 5 databases: PostgreSQL, SQL Server, MySQL, SQLite, and Firebird.
  • Stress & Concurrency Testing β€” Validation of concurrent collections, channels, and async tasks under high load to ensure no Race Conditions.
  • Anti-Leak Policies β€” Rigorous memory monitoring in every suite; test failures are triggered if object leaks are detected.
  • Field Evidence β€” Framework validated in real-world projects deployed on AWS and Azure, with fiscal management systems processing peaks of ~800,000 daily requests.
  • CI/CD Quality Gates β€” Native integration with Azure DevOps and GitHub Actions, enforcing coverage thresholds and snapshot approval.

πŸ€– 18. MCP Server (Model Context Protocol) (Sources\MCP)

The framework provides a native, zero-dependency implementation of the MCP 2025-03-26 specification, enabling Dext applications to expose tools, resources, and prompts to AI agents (like Claude Desktop and Claude Code).

  • Supported Transports β€” HTTP Streamable (Synchronous POST with Sessions), SSE (Legacy Server-Sent Events), and Stdio.
  • Declarative RTTI API β€” TMCPToolProvider with [MCPTool], [MCPParam], [MCPResource], and [MCPPrompt] attributes for frictionless endpoint registration.
  • Fluent Builder API β€” Chainable registration: Server.Tool('name').Description('...').OnCall(...).
  • Rich Content Types β€” Built-in support for TMCPContent (Text, Image, Audio, Embedded Resources) and TMCPToolResult returning multiple blocks and error states.
  • Integration β€” Runs natively on top of Dext's TWebHostBuilder allowing MCP and REST endpoints to coexist non-blocking in the same process.

πŸ“Š 19. Dext Observability Suite & Telemetry (S23 β€” S27) (Sources\Core\Base, Sources\Dashboard)

The framework embeds a premium, high-performance, asynchronous observability suite designed to gather, persist, and visualize structured logs, distributed spans, system health metrics, and detailed database query and external network profiling.

19.1 Distributed Tracing & Structured Logging (S24)

  • Asynchronous Ring Buffer β€” Log entries and spans are collected into a high-performance in-memory ring buffer (capped at 1000 items), eliminating disk I/O bottlenecks in critical request-handling threads.
  • Asynchronous Persistence β€” A dedicated background worker (TDashboardSaveTimer) periodically flushes traces to telemetry.json every 30 seconds in a non-blocking manner.
  • Hierarchical Gantt Tree β€” The Dashboard renders visual span nodes nested under their parent trace contexts (TraceId/SpanId) in real time, making latency and processing bottlenecks simple to analyze.

19.2 System Metrics & Throughput (S25)

  • RED Metrics Dashboard β€” Real-time visual graphs in the Dashboard tracking HTTP RPS (Requests per Second), SQL QPS (Queries per Second), HTTP Errors, and average latency.
  • System Health Monitor β€” Operating system resource sampling: CPU usage (%), physical memory (Working Set in MB), active thread count, and active DB connections.
  • Non-Blocking Persistence β€” Serialized metrics are appended to a ring buffer and written to metrics.json every 30s via the async background timer.

19.3 Database & Outbound HTTP Profiler (S27)

  • FireDAC Auto-Instrumentation β€” Zero-coupling interception inside the DB driver layers (Dext.Entity.Drivers.FireDAC.pas), automatically capturing raw SQL queries (db.statement), query parameters (db.params), query elapsed execution times, and routing database exceptions.
  • Outbound HTTP Auto-Instrumentation β€” Network call interception inside the Rest Client (Dext.Net.RestClient.pas), capturing target URLs, HTTP methods, response elapsed timings, HTTP status codes, and exceptions.
  • Context Inspector Drawer β€” A sliding overlay panel in the Dashboard triggered by clicking any span node in the tree. Displays pretty-printed SQL statements, structured query parameters, copied cURL commands, and generic metadata tags.

19.4 Streamable Sessions & HTMX (S23)

  • IStreamableSessionManager β€” SSE channel manager with automatic garbage collection (runs every 60s, evicting idle sessions after 30 minutes).
  • HTMX Fragment Swap β€” Endpoints serving dynamic HTML fragments (e.g. /sidecar/fragments/metrics), allowing live DOM updates via HTMX without writing any client-side JavaScript.

🌐 20. HTTP/2 Framing & HPACK Transport (S41) (Sources\Server)


🎨 8. Dext Template Engine (Sources\Core\Base\Dext.Templating)

8.1 Core Architecture

  • ITemplateEngine β€” Main interface: Render(template, context) and RenderTemplate(name, context).
  • TDextTemplateEngine β€” Complete implementation with AST (Abstract Syntax Tree) parser. Each directive is compiled into a node (TTemplateNode) with a Render method.
  • ITemplateContext β€” Hierarchical context with string values, objects, and lists. CreateChildScope for nested scoping.

8.2 Template Loader

  • ITemplateLoader β€” Pluggable interface for loading templates. Implementations: FileSystem and In-Memory.

8.3 Node Types (AST)

  • TTextNode (literal text), TExpressionNode (interpolation {{ var }}), TIfNode/TElseIfNode/TElseNode (conditionals), TForEachNode (iteration with @index, @first, @last), TBlockNode (named blocks), TExtendsNode (layout inheritance), TSectionNode (sections), TMacroNode (reusable macros), TBreakNode/TContinueNode (loop flow control).

8.4 Expression Engine

  • Expression parser with support for arithmetic, comparison, and logical operators (and, or, not).
  • Chained Filters β€” {{ value | upper | truncate(10) }} with filter pipeline.
  • Filter Registry (ITemplateFilterRegistry) β€” RegisterFilter(name, func) for custom filters.
  • Built-in Filters β€” upper, lower, capitalize, truncate, default, date, html_escape, etc.

8.5 Advanced Features

  • Layout Inheritance β€” {% extends "base.html" %} with block overrides.
  • Whitespace Control β€” {%- -%} for whitespace control in directives.
  • HTML Mode β€” IsHtmlMode for automatic output escaping.
  • Source Position Tracking β€” TSourcePos with line, column, and filename for precise error reporting.
  • ETemplateException β€” Exceptions with position and template snippet for debugging.

βœ… 9. Dext Validation Engine (Dext.Validation)

  • Attribute-Based Validation β€” RTTI decorators: [Required], [StringLength(min, max)], [Range(min, max)], [RegularExpression(pattern)], [EmailAddress], [Url].
  • Fluent Validation API β€” Strongly-typed validation base class TAbstractValidator<T> implementing IValidator<T> as a modern C# FluentValidation-like alternative.
  • Fluent Rule Builder β€” Memory-efficient record TValidationRuleBuilder<T> that avoids heap allocations while building chained validation rules (Required, Length, Range, EmailAddress, Matches, MatchesPattern, Must, When).
  • Smart Property Integration β€” Concrete RuleFor overloads for standard Prop<T> smart properties (e.g., Prop<string>, Prop<Integer>, Prop<Boolean>, etc.) to automatically extract property names from Prototype ghost entities without magic strings or compiler casting issues.
  • Pattern Registry β€” TValidationPatterns registry mapping keys to locale-specific regular expressions (e.g. Pt-BR or En-US phone numbers and zipcodes).
  • TValidator β€” Non-generic helper: Validate(obj) returns TValidationResult with a list of TValidationError (field + message).
  • TValidator<T> β€” Typed generic version.
  • Custom Validators β€” Inherit from ValidationAttribute for custom business rules.
  • Web Integration β€” Automatic resolution of registered validators (IValidator<T>) from the Dependency Injection (DI) container inside the web model binding pipeline (THandlerInvoker.Validate), raising TWebValidationException to yield structured error JSON/HTMX payloads.

πŸ”„ 10. Dext Mapper (Dext.Mapper)

  • TMapper β€” AutoMapper-like for DTO↔Entity transformation.
  • CreateMap<TSource, TDest> β€” Mapping registration with automatic property reflection by name.
  • ForMember β€” Mapping override for specific properties with custom lambda expressions.
  • Map<TSource, TDest> β€” Mapping execution with automatic destination instance creation.
  • Collection Mapping β€” Automatic mapping of lists and arrays.

🏒 11. Dext Multi-Tenancy (Dext.MultiTenancy)

  • ITenantProvider β€” Abstraction for current tenant identification.
  • ITenantConnectionStringProvider β€” Dynamic connection string resolution per tenant.
  • Strategies β€” Shared Database (TenantId discriminator), Schema Isolation (search_path in PostgreSQL), Database per Tenant.
  • DI Integration β€” Registered as a Scoped service for resolution per request.

πŸ–₯️ 12. Desktop UI & Design-Time (Sources\UI, Sources\Design)

12.1 Navigator Framework (Flutter-style)

  • ISimpleNavigator β€” Push/Pop/Replace/PopUntil navigation with TValue data passing.
  • 3 Adapters β€” TCustomContainerAdapter (embed frames in panel), TPageControlAdapter (tabs), TMDIAdapter (child windows).
  • Middleware Pipeline β€” TLoggingMiddleware, TAuthMiddleware, TRoleMiddleware β€” same architecture as the Web pipeline.
  • Lifecycle Hooks β€” INavigationAware with OnNavigatedTo(Context) and OnNavigatedFrom.
  • DI Integration β€” Navigator registered as a Singleton service in the container.

12.2 Magic Binding (Dext.UI.Binding)

  • Two-Way Attribute-Based Binding β€” [BindEdit('Name')], [BindCheckBox('Active')], [BindText('ErrorMessage')].
  • Nested Properties β€” [BindEdit('Customer.Address.City')] with dot notation.
  • Message Dispatch β€” [OnClickMsg(TSaveMsg)] eliminates manual OnClick handlers.
  • Custom Converters β€” IValueConverter with Convert/ConvertBack for complex types (e.g., TCurrencyConverter).
  • TBindingEngine β€” Central engine automatically synchronizing ViewModel ↔ UI.

12.3 MVVM Patterns

  • Clean architecture with ViewModel + Controller + DI.
  • Validation Integration β€” FViewModel.Validate with errors automatically reflected in the UI via binding.

12.4 Infrastructure

  • Interception Engine β€” Proxy engine for method interception, base for Mocks and AOP (Aspect-Oriented Programming) features.
  • Design-Time Experts β€” IDE Grid Data Preview and specialized metadata property editors.

12.5 Design-Time Scaffolding Experts (Dext.EF.Design.Scaffolding)

  • TSelectionEditor Integration β€” Non-invasive context menu integration for TFDConnection and TDataSet (FireDAC and Generic). Dext menus coexist with native IDE menus.
  • TTableSelectionForm β€” Advanced selection UI with real-time filtering, "Select All/None" shortcuts, and live table/selection counters.
  • Live Scaffolding Preview β€” High-fidelity preview window with real-time code generation, statistics (Entities/Metadata/Lines), and style switching (POCO vs. Smart).
  • Smart PascalCase Engine β€” Acronym-aware naming logic (EmployeeID β†’ EmployeeId, ReportsTo preserved) with support for snake_case and ALL_CAPS normalization.
  • Enhanced Meta-Inference β€” Precise AutoInc detection via RTTI and ftAutoInc, ensuring 1:1 parity with database schema.
  • IOTA Automation β€” Seamless creation of new units in memory and automatic association with the active Delphi project.

πŸ› οΈ 13. Dext CLI & Scaffolding (Tools\Dext.Tool.Scaffolding)

  • Dext CLI (S01) β€” Unified CLI engine (dext.exe) for project management.
  • Advanced Scaffolding β€” Project and file generation via smart templates: dext new (projects), dext add (controllers, entities, middlewares).
  • Template Logic β€” Direct integration with Dext.Templating for complex logic within scaffolding templates.
  • Dext Doc β€” Automated technical project documentation generation.
  • dext test β€” CLI-based test execution and coverage report generation.
  • dext ui β€” Web dashboard for real-time test monitoring.
  • dext index β€” Mapping and indexing of all public symbols (classes, records, interfaces, methods, etc.) with exact line numbers in Markdown, JSON, and CSV for AI agents and NotebookLM.

πŸ” 14. Observability & Telemetry (Sources\Core\Base)

  • TDiagnosticSource (S03) β€” Centralized event publisher based on JSON payloads, ensuring decoupling between producers (ORM, Web) and consumers.
  • Telemetry Bridge (Dext.Logging.Telemetry) β€” Automatic ILogger integration, enabling HTTP and SQL telemetry visualization in console or log files.
  • SQL Capture β€” ORM native SQL instruction extraction and formatting for real-time auditing.
  • HTTP Lifecycle β€” Latency, status codes, and web framework route tracing.
  • Stack Trace Extraction (Dext.Core.Debug) β€” Precise and detailed stack trace extraction at the point of exception. Critical for debugging highly integrated frameworks with dynamic execution flows.

πŸ€– 15. AI Skills & Developer Experience (Docs\ai-agents)

  • Native AI Skills β€” Modular instruction files (dext-web.md, dext-orm.md, dext-auth.md) teaching AI assistants (Cursor, Antigravity, Copilot, Claude) to generate idiomatic Dext code.
  • 3 Integration Modes β€” Direct copy to .agents/skills/, global custom configuration, or symlinks.
  • Modular by Design β€” Atomic skills to save context tokens; load only relevant modules for the current feature.
  • Compatibility β€” Claude Code, Cursor, Antigravity, Cline, OpenCode, GitHub Copilot.

🌐 16. SSR & View Engines β€” Advanced Features

16.1 HTMX Integration

  • Auto-Detection β€” The pipeline automatically detects HX-Request headers and suppresses the global layout on compatible endpoints.
  • Partial Rendering β€” Results.View<T>('fragment', Query).WithLayout('') for partial fragment rendering without layout.
  • Full-Stack SPA Feel β€” Combines server-side SSR with dynamic HTMX swapping for highly responsive apps without heavy JavaScript.

16.2 Flyweight Iterators (Streaming SSR)

  • O(1) Memory β€” TStreamingViewIterator<T> iterates on demand during template @foreach. 10.000 records rendered using memory equivalent to a single object.
  • No ToList β€” Pass Db.Customers.QueryAll directly to Results.View<T>('customers', Query) and the framework automatically engages streaming.
  • Smart Properties in Templates β€” @(Prop(item.Name)) for automatic Prop<T> unwrapping inside HTML templates.

16.3 Web Stencils (Delphi 12.2+)

  • Native Provider β€” Services.AddWebStencils(...) with entity whitelisting via TWebStencilsProcessor.Whitelist.Configure.
  • Agnostic β€” Same IViewEngine interface for Dext Template Engine and Web Stencils; switch without changing code.

πŸ§ͺ 17. Quality & Testing (Scale and Rigor)

Dext is continuously validated by a massive testing infrastructure to ensure integrity across its subsystems:

  • Engineering Statistics β€” The project exceeds 200,000 lines of pure Pascal code (excluding templates and documentation), reflecting a massive investment in stability and high-level abstractions.
  • Massive Coverage β€” Hundreds of test suites with thousands of individual assertions validating everything from the Core (Memory, Collections) to complex Web and ORM integrations.
  • Multi-DB Matrix (ORM) β€” The persistence engine is exhaustively tested across a real matrix of 5 databases: PostgreSQL, SQL Server, MySQL, SQLite, and Firebird.
  • Stress & Concurrency Testing β€” Validation of concurrent collections, channels, and async tasks under high load to ensure no Race Conditions.
  • Anti-Leak Policies β€” Rigorous memory monitoring in every suite; test failures are triggered if object leaks are detected.
  • Field Evidence β€” Framework validated in real-world projects deployed on AWS and Azure, with fiscal management systems processing peaks of ~800,000 daily requests.
  • CI/CD Quality Gates β€” Native integration with Azure DevOps and GitHub Actions, enforcing coverage thresholds and snapshot approval.

πŸ€– 18. MCP Server (Model Context Protocol) (Sources\MCP)

The framework provides a native, zero-dependency implementation of the MCP 2025-03-26 specification, enabling Dext applications to expose tools, resources, and prompts to AI agents (like Claude Desktop and Claude Code).

  • Supported Transports β€” HTTP Streamable (Synchronous POST with Sessions), SSE (Legacy Server-Sent Events), and Stdio.
  • Declarative RTTI API β€” TMCPToolProvider with [MCPTool], [MCPParam], [MCPResource], and [MCPPrompt] attributes for frictionless endpoint registration.
  • Fluent Builder API β€” Chainable registration: Server.Tool('name').Description('...').OnCall(...).
  • Rich Content Types β€” Built-in support for TMCPContent (Text, Image, Audio, Embedded Resources) and TMCPToolResult returning multiple blocks and error states.
  • Integration β€” Runs natively on top of Dext's TWebHostBuilder allowing MCP and REST endpoints to coexist non-blocking in the same process.

πŸ“Š 19. Dext Observability Suite & Telemetry (S23 β€” S27) (Sources\Core\Base, Sources\Dashboard)

The framework embeds a premium, high-performance, asynchronous observability suite designed to gather, persist, and visualize structured logs, distributed spans, system health metrics, and detailed database query and external network profiling.

19.1 Distributed Tracing & Structured Logging (S24)

  • Asynchronous Ring Buffer β€” Log entries and spans are collected into a high-performance in-memory ring buffer (capped at 1000 items), eliminating disk I/O bottlenecks in critical request-handling threads.
  • Asynchronous Persistence β€” A dedicated background worker (TDashboardSaveTimer) periodically flushes traces to telemetry.json every 30 seconds in a non-blocking manner.
  • Hierarchical Gantt Tree β€” The Dashboard renders visual span nodes nested under their parent trace contexts (TraceId/SpanId) in real time, making latency and processing bottlenecks simple to analyze.

19.2 System Metrics & Throughput (S25)

  • RED Metrics Dashboard β€” Real-time visual graphs in the Dashboard tracking HTTP RPS (Requests per Second), SQL QPS (Queries per Second), HTTP Errors, and average latency.
  • System Health Monitor β€” Operating system resource sampling: CPU usage (%), physical memory (Working Set in MB), active thread count, and active DB connections.
  • Non-Blocking Persistence β€” Serialized metrics are appended to a ring buffer and written to metrics.json every 30s via the async background timer.

19.3 Database & Outbound HTTP Profiler (S27)

  • FireDAC Auto-Instrumentation β€” Zero-coupling interception inside the DB driver layers (Dext.Entity.Drivers.FireDAC.pas), automatically capturing raw SQL queries (db.statement), query parameters (db.params), query elapsed execution times, and routing database exceptions.
  • Outbound HTTP Auto-Instrumentation β€” Network call interception inside the Rest Client (Dext.Net.RestClient.pas), capturing target URLs, HTTP methods, response elapsed timings, HTTP status codes, and exceptions.
  • Context Inspector Drawer β€” A sliding overlay panel in the Dashboard triggered by clicking any span node in the tree. Displays pretty-printed SQL statements, structured query parameters, copied cURL commands, and generic metadata tags.

19.4 Streamable Sessions & HTMX (S23)

  • IStreamableSessionManager β€” SSE channel manager with automatic garbage collection (runs every 60s, evicting idle sessions after 30 minutes).
  • HTMX Fragment Swap β€” Endpoints serving dynamic HTML fragments (e.g. /sidecar/fragments/metrics), allowing live DOM updates via HTMX without writing any client-side JavaScript.

🌐 20. HTTP/2 Framing & HPACK Transport (S41) (Sources\Server)

  • THpackDecoder & THpackEncoder β€” HPACK header compressor (RFC 7541). Includes support for the 61-entry static table, dynamic table ring-buffer with FIFO size-bound eviction, and client Huffman decoding via FSM.
  • TDextHttp2FrameCodec β€” Complete parser and serializer for all 10 HTTP/2 frame types. Zero-allocation parsing via TByteSpan and direct buffer writers.
  • TDextHttp2StreamMap β€” Sorted active streams map using binary search for O(log⁑n)O(\log n) lookup performance. Handles stream-level state machine transitions and flow-control.
  • TDextHttp2Connection β€” HTTP/2 connection state machine coordinating preface validation, SETTINGS exchange, and frame demultiplexing.
  • gRPC Compatibility Layer β€” Length-prefixed message unpacking/packing and trailers support to serve as the transport layer for gRPC (S02).

πŸ“‘ 21. Sockets Exposing & Native MQTT Protocol (S47) (Sources\Net, Tests\Net)

The framework includes support for network transport decoupling inside the IOCP/Epoll server to expose raw TCP/UDP sockets, alongside a native implementation of the MQTT v3.1.1 protocol (client and broker) for asynchronous pub/sub messaging.

21.1 Transport Layer Decoupling (IConnectionHandler)

  • Engine Decoupling β€” Abstraction of physical connections (IDextTransportConnection) and custom handlers (IConnectionHandler) allowing raw TCP/UDP streams to bypass the HTTP parser layer completely directly at the IOCP/Epoll worker threads.

21.2 TCP & UDP Sockets

  • TDextTcpServer & TDextTcpClient β€” Concurrent, asynchronous TCP server and lightweight TCP client supporting configurable read/write timeouts.
  • TDextUdpServer & TDextUdpClient β€” Low-level UDP communication components supporting raw byte spans and non-blocking receive callbacks.

21.3 Native MQTT v3.1.1 Protocol Stack

  • Binary Frame Encoder/Decoder β€” High-performance packet encoder and decoder supporting variable-byte Remaining Length representation and all standard MQTT control frames (CONNECT, CONNACK, PUBLISH, PUBACK, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNECT).
  • Trie Tree Route Router β€” Highly optimized Trie tree data structure for wildcards and topic subscription matching, with full support for single-level (+) and multi-level (#) wildcards.
  • Broker Server & Client β€” Multi-session concurrent MQTT broker supporting subscription states and clean sessions, alongside a non-blocking MQTT client with background keep-alive ping loop.

πŸ” 22. Security, Identity & Authorization (S06) (Sources\Web, Tests\Web)

Dext features a native, high-performance security and identity engine based on industry standards (JWT, OAuth2, and OpenID Connect) to guarantee enterprise-level compliance and safety.

22.1 Cryptographic Engine and JWT Validation (Dext.Auth.JWT)

  • TJwtTokenHandler β€” Full-featured JSON Web Token (JWT) manager with native support for HS256 signatures and RS256 asymmetric validation.
  • Windows CNG Integration β€” High-performance validation and signing dynamically leveraging Windows Native Cryptography APIs (bcrypt.dll), with a transparent fallback to System.Hash (Delphi XE8+) or Indy/OpenSSL for maximum compatibility across versions.
  • Optimized Parsing β€” Structured parsing of JWT tokens using fast string indexers (IndexOf) and memory spans (TByteSpan), avoiding heap allocations.
  • Claims Handling β€” Flexible claim records (TClaim) and a fluent identity builder (TClaimsBuilder).

22.2 JWT Authentication Middleware (Dext.Auth.Middleware)

  • TJwtAuthenticationMiddleware β€” HTTP pipeline middleware that extracts tokens from the Authorization: Bearer header, validates signatures, expiration times (exp), issuer (iss), and audience (aud), then injects the claims principal (IClaimsPrincipal) directly into the request context (IHttpContext.User).

22.3 Declarative and Policy-Based Authorization (Dext.Auth.Attributes, Dext.Auth.Identity)

  • Authorization Attributes β€” [Authorize] and [AllowAnonymous] attributes for declarative protection of controllers and actions.
  • Role Validation β€” Role-based access control evaluated dynamically inside the route execution and controller scanning dispatch flow.
  • Policy Engine β€” Runtime registration and evaluation of complex custom policies through the TAuthorizationPolicyRegistry (e.g., minimum age requirements or custom scope checks).

22.4 External Identity Providers (OIDC)

  • Plug-and-Play Methods β€” Middleware extensions for out-of-the-box configuration of third-party identity providers via OIDC: UseGoogleAuthentication, UseEntraIdAuthentication (Azure AD), and UseKeycloakAuthentication.

πŸš€ 23. Linux Epoll Server Engine Evolution (S50) (Sources\Server)

  • Thread Core Affinity (CPU Pinning): Auto-binding of I/O worker threads (TDextEpollWorker) to dedicated CPU cores via pthread_setaffinity_np to avoid scheduler migration overhead and maximize cache locality.
  • Kernel-level Pre-acceptance Optimization: Implements socket-level TCP_DEFER_ACCEPT to postpone worker wake-ups until incoming payload arrives, and TCP_FASTOPEN (TFO) to support payload transmission in the initial SYN packet.
  • Zero-Copy File Transmission (sendfile): Integrated support for direct file streaming using the non-blocking kernel sendfile system call, bypassing user-space copy buffers.
  • Context Allocation Pooling: Features a lock-free, thread-safe pre-allocated connection context pool (TDextEpollContext) to completely avoid heap fragmentation during highly concurrent connection spikes.
  • Active Keep-Alive Sweep: High-efficiency background sweep monitoring connection activity timestamps, automatically terminating idle descriptors (>15 seconds) under descriptor pressure, coupled with SO_LINGER socket teardown.

⚑ 24. Native Redis Client (S13) (Sources\Net, Tests\Net)

Dext features a native, high-performance Redis client library supporting RESP2/RESP3 serialization, connection pooling, reactive Pub/Sub channels, and RedisJSON.

24.1 High-Performance Serialization (RESP2/RESP3)

  • Zero-Allocation Parser β€” Highly optimized TDextRedisParser parsing incoming RESP byte streams using memory spans (TByteSpan), avoiding heap allocations.
  • RESP3 Additions β€” Native support for new RESP3 value types including Nulls (_), Booleans (#), and Double Floats (,).

24.2 Connection Pool & Thread Safety

  • TDextRedisConnectionPool β€” Safe, high-concurrency client pooling (IStack<TDextRedisConnection>) to minimize socket creation overhead and manage connections efficiently.
  • Thread-Safe Commands β€” Automatic acquisition and release of pooled connection handles during command executions.

24.3 Reactive Pub/Sub & Channels

  • TDextRedisPubSub β€” Asynchronous Pub/Sub engine using Dext's native concurrent channels (IChannel<TDextRedisMessage>) for thread-safe message dispatching.

24.4 RedisJSON & Dext.Json Integration

  • RedisJSON Module Support β€” Native integration with the Dext.Json serialization engine to store and retrieve structured Delphi objects directly as JSON values.

πŸ›£οΈ 25. High-Performance Radix Tree Routing Engine (Sources\Web)

  • Radix Tree (Trie) Routing Matching β€” Path segment route scanning replaced with an optimized TRouteNode tree structure, achieving O(L)O(L) path matching complexity (where LL is path segment depth) and deterministic route resolution.
  • Backtracking Segment Traversal β€” Fully supports literal matching, path parameters ({param}), and wildcard parameters with segment-by-segment backtracking to resolve overlaps.
  • Zero-Allocation Request Metadata Mapping β€” Bypasses RTTI-heavy dynamic wrapping (eliminating dictionary and TValue heap allocations) by directly exposing and assigning EndpointMetadata via IHttpContext properties on matched routes.

πŸ’Ύ 26. Remote TEntityDataSet Sync & Transparent Decompression (S51)

Exposes delta-tracking mechanisms and transport decompression.

26.1 Native Change-Log Tracking in TEntityDataSet

  • Row State Tracking β€” Native change tracking via TEntityRowState and change list property Changes (TEntityChange).
  • Tombstones for Deletion β€” Retains primary key maps (Key) of deleted entities during Delete, enabling synchronization of removals.
  • Transactional Consolidating β€” Native AcceptChanges API to clear accumulated change logs after successful updates.

26.2 Server-side agreed service mapping

  • Automated Routing Endpoints β€” Native MapEntityDataSet<T> exposing GET for fetching and POST /apply for persisting the change list.
  • Custom Persistence Engine β€” Pluggable IEntityDataSetStore interface defaulting to TDbContextEntityDataSetStore (DbContext.SaveChanges).

26.3 Transparent Network Transport Decompression

  • Transparent Inbound Decompression β€” TRestClient advertises Accept-Encoding and decompresses response streams dynamically.
  • Raw Stream Preservation β€” Preserves raw compressed bytes via RawContentStream property for audit or direct byte checking.

πŸ“‘ 27. Modernizer: gRPC & Protocol Buffers (S02)

High-performance binary transport protocol implementation.

27.1 Protobuf Serialization Engine (Dext.Serialization.Protobuf)

  • TProtobufSerializer β€” High-speed, zero-allocation binary serialization engine for Protocol Buffers (proto3).
  • Format Handlers β€” Supports Varint, Fixed32, Fixed64, and Length-Prefixed formatting types using high-performance TSpan memory representations.
  • Entity Binding via RTTI β€” Marshals Delphi objects directly to Protobuf binary format, evaluating attributes such as [ProtoMember] and field ordinals.

27.2 Length-Prefixed Message Codec (Dext.Grpc.Codec)

  • TGrpcCodec β€” Framing codec for gRPC Length-Prefixed Messages (LPM).
  • Compression Support β€” Compression flag handling (1-byte compressed flag, 4-byte big-endian message length) for HTTP/2 transmission.

27.3 gRPC Server Engine (Dext.Web.Grpc.Server)

  • TGrpcDispatcher β€” Decodes HTTP/2 frames and maps incoming application/grpc requests to the registered service handlers.
  • Service Mappings β€” Dynamic routing and method dispatch via reflection and interface lookup tables.

27.4 Client & DataSet Integration (Dext.Entity.GrpcProvider)

  • TEntitygRpcProvider β€” Pluggable gRPC sync provider for TEntityDataSet, enabling bi-directional remote synchronization.
  • TgRpcClient β€” Low-level client engine sending Protobuf streams and parsing gRPC binary responses.

πŸ“‘ 28. Model Context Protocol (MCP) Server (Sources\AI\MCP)

Provides native support for the Model Context Protocol (MCP) v2025-03-26.

28.1 TMCPServer & TMCPServerBuilder

  • TMCPServerBuilder β€” Fluent builder to configure MCP servers.
  • HTTP Stack Selection β€” Support for Indy and HTTP.sys (Native) stacks.
  • Provider Registration β€” Automated mapping of custom providers.

Dext Framework β€” Exhaustive Technical Map & Features Index. (Revision: Jul 2026).