TXFAJavaScriptSession
Unit: HPDFXFAEventScript
Declaration
TXFAJavaScriptSession= class
Behavior
Owns an independent QuickJS engine and a bounded journal of committed virtual evaluations
Preserves script-object lexical variables, functions, object values and nested closures across events; rollback reconstructs the engine by replaying committed evaluations
Records Date and Math.random inputs for reproducible replay; replay executes only virtual form operations and does not publish document mutations
Version 2.1148.1 keeps Date.prototype.constructor and ordinary Date instance constructor aliases on the recorded event clock, including after rollback and failed-event reconstruction. Standard constructor descriptors, Date.parse, Date.UTC, subclass construction and explicit date arguments are preserved
Version 2.1148.2 keeps internal clock assignments out of the evaluation result: empty, comment-only and declaration-only scripts return undefined as they do in the native engine. A leading hashbang is recorded as an equivalent line comment, with the engine handling its line terminators, and the caller's first line remains separate from the recording prefix
Scripts remain global evaluations with their original lexical declarations and a single execution of user code. The bridge already enforces strict mode; the source-format repair does not change that policy
Version 2.1148.3 captures the Session's runtime dependencies before user code runs. Standard names such as globalThis, Math, Reflect, String and Error can have caller-owned lexical bindings without redirecting internal clock, replay, maintenance or retention operations; user code still observes its own bindings normally
Date construction and text conversion use their captured native operations, and the deterministic random method retains the native name, length and nonconstructable function shape. The private __hpdfSessionIntrinsics property is immutable support state within each engine and does not retain a second engine or expand the existing memory and journal limits
Native Session history uses strict global-program evaluation, while published replay fragments retain their existing indirect-eval mode. Full equivalence of strict function behavior and program-level declaration lifetime between those modes remains a separate compatibility task
Event support code is compiled once for each owned engine; each evaluation supplies a fresh form and data context, script body, limits and recorded response vectors
Rollback reinstalls that support code and replays the committed dynamic evaluations, preserving independent lexical and closure state without reparsing the support library for every journal entry
RebuildPending performs that reconstruction up front and commits nothing, so a host can pay for it before arming a deadline for the event it is about to dispatch
Nested lifecycle replay uses immutable, session-local script/result references instead of recursively embedding and escaping recorded source; each reference preserves the recorded Date and Math.random inputs and checks the original evaluation result
ReplaySince(Position) returns code for evaluation through this same session; references remain valid after rollback and engine reconstruction, even when a discarded history position is reused, and expire when the session is destroyed
The shared support source, committed evaluations, returned results and immutable replay storage all count against the journal byte limit; rebuilding and replay remain inside the existing elapsed-time and engine limits
Default journal bounds are 64 MiB of combined logical storage and 8192 committed evaluations, including identity bindings; the reference pool has the same entry-count cap and retains published entries until session destruction
Engine memory, stack, operation, interrupt and elapsed-time limits still apply; reference sharing does not eliminate full form-context hydration or guarantee unlimited nested remerge depth
TXFAWidgetRuntime owns one session automatically when using the shipped general engine; session state is not serialized into XDP and a new runtime starts fresh
The class is single-threaded and must not be shared by concurrent callers
Shared immutable replay payloads
Version 2.1145.0 stores each accepted history script/result once in a Session-owned immutable payload arena. Publishing a replay fragment adds independent pool references instead of writing a second copy of equal payload bytes
History rollback releases history references while published fragments keep their original payloads alive, including after a history position is reused. Owned-pool cleanup retains the existing public-prefix and surviving-history protection before releasing references
Each logical journal retains its original payload and index byte charges, so the default 64 MiB journal admission and event limits are not enlarged by physical sharing. Physical payload, descriptor and index files have separate overhead, and shadow compaction can temporarily require both old and replacement storage
Zero-reference descriptor slots are reused. Dead payload space is collected in batches, with bounded-hole compaction, while a rollback that merely changes a pinned reference count from two to one skips a whole-catalog scan
Recoverable read-only cleanup or shadow-write failures leave committed references readable and defer cleanup; adding a payload or another shared reference retries the deferred work before writing. Destructive reference/truncation failures or failed write restoration make the shared arena unavailable rather than exposing partial state
The Unicode-string path can publish scalar-canonical UTF-8 without payload-sized decode/encode copies. Other string/codepage configurations retain the legacy roundtrip comparison before sharing, and differing normalized bytes retain their own stored copy; FPC physical sharing is verified without claiming removal of its temporary conversions
This does not expire public replay strings, change frozen entry-pair identity, reclaim process compiled-cache payloads or skip required history execution. See the focused shared-storage acceptance (Tests/XFA/ReplayReferences/SharedPayloadArena/Readme.en-us.md) for actual Windows/Linux source identities and physical storage measurements
Guarded alias binding
Version 2.1147.0 uses the optional native predecessor query to skip unnecessary full alias scans when the current compact Map and iterator path are proven safe. Ordinary tick order, chain rewrites, public identity resolution and customized iterator behavior retain the original fallback
Version 2.1147.1 also admits predecessor-free queries after that enabled Map promotes to general storage, using a fixed conservative value summary. Matching values, collisions and custom iteration keep the original fallback; the original journal and execution budgets remain unchanged
The Delphi Session caches only the UTF-8 byte count of its accepted prelude, invalidates that count after every assignment and computes it lazily at the original protected budget-check sites. Conversion failure remains retryable through the original exception handling. FPC performs its existing conversion at each read, preserving codepage behavior
Compiled-cache owner lifetime
Version 2.1146.0 automatically registers one optional native compiled-cache owner for the Session's pinned module. Dirty rebuilds detach the old engine and attach its replacement to the same owner, retaining reusable compiled history
Session destruction frees the engine, releases owner-only compiled entries and then releases the module lease. Exact source shared by another owner remains cached; an unscoped engine's successful use preserves the original module lifetime. Required JavaScript roots, published fragments and immutable journal references are unaffected
Older bridges keep the previous unscoped cache behavior. If owner support is present but setup fails, the Session reports the error and preserves a valid owner for retry or destruction instead of silently downgrading
Compiled replay lookup
The optional compiled-script cache uses indexed exact-source lookup during retained-history reconstruction, avoiding a full cache scan for each recorded wrapper
This does not skip committed history execution or expire public replay references; rebuilding still reconstructs lexical state and checks the recorded results. Compiled-cache owner bookkeeping and source/bytecode payload remain separate from the Session's VM and journal budgets
Direct event compilation
Version 2.1148.0 adds a native direct-eval compilation cache for the shipped fixed event wrapper, without changing the Session, Host or event JavaScript modules or adding a public API. Its complete static caller and source key is separate from the original global compiled-script namespace
Repeated admitted source restores fresh bytecode and fresh closures against the current event's frame and bindings. Events still execute, preserve independent lexical state and observe the current model; caching does not replace history reconstruction, recorded Date and Math.random handling or public replay lifetimes
Templates, large sources and unadmitted graphs keep the original compilation path. The 64 KiB input, 256 KiB combined key/bytecode, 512-atom and 1 MiB native writer-workspace bounds govern optimization admission only, with allocator overhead additional and no raised VM, journal or execution limits
Entries share the existing native payload and owner budgets, participate in the same owner release and unload lifecycle and retain no additional JS roots or executed closures. Cache statistics combine direct and global entries. The focused public-event acceptance (Tests/XFA/ReplayCompilationCache/DirectEvents/Readme.en-us.md) verifies alternating source, changing current bindings, owner cleanup and continuous cold/hit limits; arbitrary event-source caching and general retained-history growth are not declared complete
Native replay field residency
Version 2.1142.0 uses an optional native replay provider to fetch immutable script/result fields from the existing disk journals when a generated reference actually executes, instead of installing every published payload as a JS pair and quoted compiled-cache source
The generated code retains caller-level indirect eval, recorded Date and Math.random inputs and the exact result-divergence check. Public ReplaySince references remain valid after rollback, index reuse and engine reconstruction; this change does not expire published references, reuse logical IDs or drop unseen history
Before user code, metadata synchronization validates the first pending logical ID against the helper's current installed/manual highwater and advances to the actual last retained ID. Publication holes remain meaningful, and a conflicting manual add fails at the same pre-user-script boundary as eager installation
The Session selects native or legacy mode once for its module lease and keeps that mode across rebuilds. The bootstrap captures the raw native function and removes its temporary Session global before replaying history; older bridges continue to install the eager Map and use entry-based fragments
Generated native references use transient script(id) and result(id) fields. The compatible entry(id) method still materializes and strongly caches one frozen data-property pair on explicit access, preserving repeated array identity and WeakRef lifetime; cached manual pairs remain available to field access without creating a persistent pair for every ordinary generated replay
Host I/O, size, allocation, copy and fetch-deadline faults cannot be committed even when user JavaScript catches them, including inside completion-value toString. The Session becomes dirty, leaves the failed event out of its journal and reconstructs the accepted state on the next evaluation; ordinary unavailable-ID catches remain ordinary successful events
The finite 32-entry acceptance removes measured eager pool residency while retaining every saved public fragment. Durable published payload storage, explicit legacy pair caches, strong object roots and required live-history hydration still have their existing lifetimes and may grow; no hard cap is raised and general dirty-replay growth is not declared complete
See InstallReplayProvider, runtime deployment and targeted native-provider acceptance (Tests/XFA/ReplayReferences/NativeProvider/README.en-us.md)
Native retired identity storage
Version 2.1135.0 moves canonical retired identity membership to a session-owned exact disk index when the bridge exposes the optional registry callback. Saved identity strings, aliases, retirement diagnostics and replay identities retain their existing semantics
The full index and key payload count against MaxJournalBytes. Empty indexes do not create a file; rebuilding replays the accepted history into a fresh index, and teardown removes the owned temporary file. Version 2.1139.0 extends this index to every string identity, including empty keys, embedded NULs, unpaired UTF-16 surrogates and long noncanonical keys. Version 2.1140.0 adds typed native storage for primitive numbers, BigInts, booleans, null and undefined when the optional value-registry export is present
Version 2.1141.0 also routes objects, functions, boxed values, proxies and Symbols through the exact native index when the installed function exposes its own strongValues=true data capability. Both the capability and its descriptor value must be own data properties; accessors and inherited values cannot enable native routing. Earlier scalar-only V2 and V1 bridges keep references in the original strong JavaScript Set
TryGetIdentityStorageUsage reports index bytes and native member counts for the current engine, including scalar and reference categories admitted by that bridge. Values in the JavaScript fallback are excluded
Reference descriptors combine an object or Symbol tag with the engine and native JSValue identity pointers. Each index is private to one engine lifetime and append-only; rebuilding destroys the old engine, clears the index and reconstructs membership from replayed values, so stale pointer keys never cross engine namespaces
The bridge reserves native root-vector capacity before host insertion and owns one strong reference only after a new member is accepted. Engine teardown releases those roots without reading the provider. The vector and retained payload remain linear and count against the normal VM memory budget; the physical index and keys count against MaxJournalBytes
The Session uses the optional typed registry when available, the V1 registry for strings on older bridges, and the preceding JavaScript representation when neither registry is present. A supported typed registry that fails to install reports an error without a silent downgrade
This reduces resident membership-index overhead for admitted retirement values; no hard cap is raised, public strings are not expired, published replay payloads are not reclaimed, and constant process memory or total storage is not promised. See the typed registry deployment and ownership rules and targeted acceptance profiles (Tests/XFA/IdentityStorage/StrongDiskIndex/README.en-us.md)
Compact native identity aliases
Version 2.1143.0 enables compact backing for the initial native identity-alias Map when the loaded bridge provides the optional installer. Consecutive exact 16-code-unit hexadecimal keys sharing primitive-string targets can share runs instead of retaining one allocated native record and key per alias
The object remains a genuine native Map with the same identity, prototype, borrowed native methods, insertion order and live entries, keys and values iterators. Uppercase and lowercase spellings remain distinct where their actual characters differ, and full-width UInt64 keys never pass through floating-point conversion
Arbitrary key and value types, mixed hexadecimal spellings and fragmented histories remain supported through atomic promotion to the ordinary native representation. Compact state maintains a size-dependent run bound for sublinear key access, and ordinal iteration uses binary search. Promotion includes the triggering write or deletion and translates active iterator positions without exposing staged contents on allocation or interruption failure
The same-program Win64 acceptance measures net alias allocation at 1000 and 4000 consecutive public BindIdentity calls: the preceding provider uses 141041 and 552593 bytes, while the new provider uses 585 bytes at either size. This is a retained alias-storage profile, not a constant-memory claim for arbitrary histories or the whole process. The default 16 MiB Session VM, 64 MiB journal and 8192-event budgets remain unchanged
All backing and promotion storage is charged to the existing VM allocator. Required public payloads, retained roots, replay history and the cost of alias-collapse iteration keep their existing semantics and lifetimes. MallocBytes measures allocator usage; the inherited MemoryUsedBytes estimate does not fully account for Map internals
The bootstrap removes its reserved temporary native installer and only enables a newly created empty initial alias Map. Existing caller state and later replacement Maps or map-like objects retain their normal behavior. Older bridges without the export continue through the preceding ordinary Map path; a present installer that fails reports an initialization error
See SupportsAliasMapOptimization, InstallAliasMapOptimization and focused acceptance evidence (Tests/XFA/IdentityStorage/CompactAliasMap/Readme.en-us.md)
Related APIs
TXFAJavaScriptSession, HPDFXFAExecuteJavaScriptEvent and Interactive Dynamic XFA Widget Runtime