Portable XFA runtime
Owned native FormCalc execution connects retained-funded events, fields, predicates and layout queries to owned producers, with explicit result-owner transport for nonvisual field evaluation
The native TXFAWidgetRuntime data, layout and event model executes with Delphi or FPC on Windows and with FPC on Linux x86-64; pageContent returns actual Form objects and page-span queries report physical or numbered-page coverage from the completed layout snapshot
Dynamic bookend, keep, margin and overflow properties support getElement creation, direct script setters, live intact defaults and saved per-instance Form state; subformSet exposes bookend only. Native bidirectional keep layout handles next/previous sibling adhesion, split-fragment endpoints and separate contentArea/pageArea scopes during Runtime reflow
Generated break, bookend and overflow presentations retain distinct interaction identities while sharing their original stored values
Script-created ordinary Form nodes keep presence/access properties and their attribute methods synchronised, including cloning, native event persistence, save/reload and transactional rollback
Explicit Form remerge rebuilds from the current Template and datasets through Pascal or synchronous JavaScript, with new Form identities and transactional rollback
Instance-manager defaults follow the current associated Template declaration across events, or a persisted first-manager snapshot for manual Form instances without that source; caller Form overlays retain supplied sibling order
Linux core execution does not require LCL, a desktop session or a Windows compatibility layer; the Windows FPC build retains its existing Lazarus UTF-8 RTL initialisation
Anonymous interactive fields
Fields without a name participate in widget enumeration, editing, focus and event dispatch. Their public Name remains empty; use Widgets[].ID to select a particular widget
Ordinary anonymous widgets receive layout-local IDs such as [0] and [1], separately from named-field counts. As with ordinary name[index] IDs, re-enumerate after structural or visibility changes instead of treating these ordinals as permanent node identities
Automatic instance identities and application-supplied ResolveWidgetIdentity callbacks also apply to anonymous fields. Physical master-page copies retain separate interaction IDs while sharing the model value; saved value overlays preserve unnamed page-model ancestors
Data-aware generated Form synchronisation
For supported ordinary named-subform binding in a library-generated Form, Runtime document updates reconcile automatic repeated instances with added or removed datasets groups while retaining the surviving Form instances and their script-set properties. Unmatched minimum instances remain real Form nodes rather than artificial datasets records
Explicit removal through the actual Form nodes collection remains authoritative: later automatic reconciliation does not recreate the removed instance merely because its data group survives or another row changes ordinal position. Saving the expanded document and creating a fresh Runtime preserves that deletion together with the remaining values and structure
Failed transactions restore the saved Form and datasets state, including prior explicit deletions, rather than repeating the initial merge. Width plans and internal terminal replay read the accepted structure without consuming new data instances
For this automatically generated Form model, default widget IDs combine a persisted instance token with the field's local path. Treat the result as opaque and obtain it from Widgets[].ID; a surviving instance retains its ID when an earlier data row is removed and after save and reload
Declarations whose occurrence limit allows repetition keep token-based IDs even when only one instance remains. Truly nonrepeating single instances retain the ordinary name[index] convention; changing occurrence limits or replacing declarations can change the identity policy
The optional ResolveWidgetIdentity callback remains authoritative for application-supplied widget identities. Caller Form overlays follow the preparation policy below; this does not establish every binding mode or infer business-key identity across replacement datasets documents
Data order in unordered subform sets
For a library-generated Form, subformSet relation="unordered" places directly named, automatically bound child subforms in the order of their matching datasets children. A set declaring B and C with data B, C, B therefore produces B, C, B in its actual Form and layout. The default ordered relation retains declaration order
Reconciliation reuses surviving instances and their Form-only state when data children move. Existing occurrence limits and explicit removal markers remain effective. Matching automatic instances appear first in data order; automatic minimum occurrences without a matching data child follow in template declaration order. Manually controlled instances and property nodes keep the existing instance-management rules and are excluded from data-order sorting
This ordering applies to ordinary direct name bindings. Nested sets retain their own relation, and explicit dataRef and global bindings retain their existing behaviour. Save and reload preserve the accepted instance tokens and data associations; a failed document transaction restores the preceding structure and layout
Data selection in choice subform sets
For a nonempty data merge, subformSet relation="choice" with ordinary named container bindings selects its member from the first available matching data child. Data C, B selects C even when the template declares B before C. The selected declaration can produce several instances within its occurrence limit. Unselected declarations do not create minimum-occurrence fillers, and unmatched data leaves the set without automatic members
Reordering unrelated data preserves the surviving winner's identity and Form-only values. Changing the first matching data child switches the selected branch and its actual layout. A failed document transaction restores the previously accepted structure, values, widget identities and geometry
A member may also be a nested ordered, unordered or choice set: its ordinary named descendants provide the indirect match, and the first available matching data child selects the containing outer member. The selected set inherits the original data scope instead of binding directly to the triggering data node, so its children retain their own bindings and ordering
Ordinary set members can repeat and competing declarations may use the same binding name. Data availability and template declaration order determine their assignments; max-zero subtrees do not participate. Explicit bindings, prototype references, ordinary subforms with transparent scope, bindings to the current data scope and master-page choice selection retain their existing handling
Outside choice competition, an optional set is also created when an ordinary named descendant matches available data. The same rule applies at every optional level beneath ordinary, ordered and unordered parents. Removing the matching data removes the automatic wrapper while the surrounding record remains; adding a match creates it again. Surviving wrappers retain their instance state, and failed transactions restore accepted structure and geometry
Without data records, initial loading and remerge materialise only the first template member of each choice set and apply that member's initial occurrence count. This includes an absent datasets packet, an empty datasets packet and an empty data element. A first member with initial two produces two instances; initial zero leaves the set empty without selecting a later member. Property nodes and page definitions remain available, and empty loading does not manufacture a data record
Library-created empty Form models retain their state while they remain empty. Adding the first data record or removing the last record rebuilds the automatic Form for the new merge mode, like an explicit remerge; Form-only state and instance identities are not retained across that boundary. Failed transactions restore the preceding document, bindings and widgets. An existing record, even an empty record element, uses nonempty merging and does not select a first-template fallback merely because no member matches. Caller-supplied Form overlays retain their existing handling
Repeated subform-set data allocation
The outer template subform selects the merge mode, with consumeData as the default. Ordinary named container bindings share a merge-local data allocation record, so a data group already assigned to one declaration is unavailable to a competing declaration in the same merge
Each repeated set allocates one complete occurrence before searching the remaining data for the next occurrence. With member maxima of one, choice data B, C, B creates three sets and ordered data B, C, B, C creates two sets containing B and C. Choice selects a declaration rather than limiting it to one instance: when B permits two instances, data B, C, B assigns both B groups to the first set and C to the next set
Transparent sets retain the original parent data scope. Their repetition identities are separate from their descendants' data bindings, so reordering data can preserve the associated Form instances and their values
In consumeData mode, two optional sibling sets whose descendants request the same B group cannot both consume that group. Repeated ordered sets can contain two separate B declarations: each declaration receives its own available data node, and their distinct declaration identities remain intact
Reordering data retains surviving choice instances, and ordered sets can move existing members between occurrences without losing their Form-only state or widget identities. Explicit set deletion follows its data anchor when data moves. Hand-maintained instances retain their data allocations and occupy their occurrence capacity. Unordered nested set members use their actual triggering data order
matchTemplate keeps declaration-specific container data assignments, allowing distinct sibling declarations to share the original data group. Complete matchTemplate instance-manager behaviour remains separate work. Scalar fields use the allocation rules below
Distinct scalar field bindings
In a library-generated Form, ordinary same-name fields consume separate matching data values in document order. Two fields named value with data A, B therefore display and edit A and B independently. Ordinary exclusion groups also retain separate group bindings instead of both resolving the first matching data node
consumeData shares scalar data availability across actual parent subforms. matchTemplate permits different actual parent subforms to reuse a data value, but same-name fields within one parent still receive separate values. When no value remains, consumeData preserves an unbound Form default; matchTemplate creates a separate default data value
Reconciliation updates these associations after data movement or replacement while preserving surviving Form and widget identities. Value reads, editing and Form value synchronisation use the same actual binding. Saving and reloading preserve the association, and failed document updates restore accepted data, Form values and widget state
Explicit dataRef targets may be shared by explicit bindings and are accounted for before later ordinary fields consume data. Short-format exclusion groups bind their shared scalar value; ordinary member fields do not consume additional values. Explicitly bound members retain their existing explicit binding behaviour. Multi-select choice lists retain their data-group binding path
This scalar allocation path applies to library-generated Form models. Caller-supplied Form overlays, all explicit-reference traversal combinations and broader dynamic XFA compatibility remain separate work
Transparent subform data scopes and repetition
An unnamed subform or a named subform with scope="none" inherits its parent data scope. The wrapper does not bind a same-name data group merely because that group exists. Its ordinary scalar fields and named child subforms retain their own data bindings
Matching descendant data can create an optional transparent subform. A wrapper with min zero and max one is present when its descendants match and absent when they do not; max zero disables it. Repeated wrappers allocate their descendant matches one occurrence at a time until data is exhausted or the occurrence limit is reached. Nested transparent wrappers can combine scalar fields and named child subforms
With a repeated wrapper containing one field named value and data values A, B, the generated Form contains two instances bound to A and B. This applies in both consumeData and matchTemplate modes. Distinct declarations may share data in matchTemplate mode, but one repeating declaration advances through its accepted data instead of repeatedly using the first value
Accepted descendant assignments determine both wrapper creation and final field bindings. Wrapper repetition anchors are separate from data bindings, so transparent wrappers preserve the inherited scope while surviving instances retain their Form-only state and widget identities after data movement. Reconciliation, save and reload, and failed transactions use these same accepted associations
JavaScript event contexts also use the accepted actual Form scope, including a root subform bound to a differently named record and named transparent wrappers that inherit that record
Changing a descendant field name in one repeated instance updates that instance's binding without applying the change to its siblings. The accepted instance identity and order remain stable on subsequent unchanged updates, including wrappers with unlimited repetition
These rules concern data merging in library-generated Forms. They do not redefine SOM name visibility or treat every bind-none object as a transparent subform. Complete global and explicit-reference combinations remain separate compatibility work
Global flags without record selection
Without an explicit record selector in the PDF application's configuration, bind.match="global" follows ordinary name binding in library-generated Forms. Two same-name fields consume separate matching values within one parent subform; editing the first preserves the second field's accepted data target
These fields also participate in ordinary optional and repeated transparent-subform allocation. The existing consumeData and matchTemplate policies continue to determine data consumption and missing-value creation, while stored binding metadata retains the original global flag
TXFADocument.RecordSelector reads and trims config.acrobat.common.data.record; an absent or empty value selects this ordinary path. PDF processing uses the Acrobat configuration branch and does not combine it with present or application-specific agent configuration. A nonempty selector, including 0, is kept distinct from the ordinary path
The native record context resolves configured boundaries, and batch flattening applies range selection with an independent Form and layout for each record. Configured records use the passive global rules below
Passive global bindings within configured records
With a nonempty record selector, a field or exclusion group using bind.match="global" binds only after its ancestors have been accepted. Its matching data cannot independently create an optional or repeated ancestor. Once the parent exists, ordinary local allocation has priority; an unavailable local target falls back to same-name elements outside every record subtree
Outside candidates are visited in data order at any depth. A unique matching candidate is shared across records, including later source records and inserted stream records. With several matching candidates, an attached stream supporting IXFARecordOrderProvider selects by the record's logical position after accepted insertions, moves and deletions. Original navigation ordinals stay unchanged. Without structural edits, selecting only source record 1 still selects the second candidate; range filtering does not renumber the source. Attributes and XML content inside scalar data values are not candidates. A missing candidate, or an out-of-range index into multiple candidates, leaves the field unbound with its Form default and creates no datasets value
Attached streams search only the global data already loaded into the resident DOM. Resolving a logical position can read source records needed for the count, but does not publish future globals or change the cursor. Local candidates retain priority, and a unique external candidate does not require an order query. Providers without the optional order interface retain their existing ordinal selection. The unique-value sharing rule follows the XFA 3.3 global-binding rules
Native merging synchronises pending stream structure before classifying records. Actual JavaScript binding refresh applies its action prefix at a transactional barrier, refreshes record membership, and requests a logical index only for multiple candidates. New record-local fields are excluded from external searches immediately. The accepted automatic Form keeps its record scope when the cursor moves elsewhere; explicit remerge changes that scope. Failed events restore structural edits, binding targets and Form state together
Bindings retain actual data identities for native and JavaScript reads and writes, including immediate sharing within one event, loadXML rebinding, remerge, save and reload, and transaction rollback. Shared long-format exclusion groups retain separate member allocation within each Form group while editing their common data children
A global multi-select choice list binds a data group. Its raw value joins the values of that group's element children with line-feed separators, without an extra trailing separator or filtering against the item list. Editing the selection updates the children and preserves the group; an empty selection retains an explicitly typed empty group. Alias fields and direct child edits read the same data
Flattening reads accepted group values and unbound Form defaults. Interactive navigation is described below; incremental loading and the remaining caller-overlay and master-scope combinations are separate compatibility work
Computed native dataRef predicates support JavaScript and FormCalc candidate filters, full repeated-group selection and stable accepted per-instance targets. Supported native Data edits preserve completed filter decisions across bounded merge replanning, while ordinary accepted-target reads and writes do not reevaluate user filters
Native record boundaries and record-relative reads
HPDFXFABuildRecordContext builds a bounded, read-only view of the current datasets DOM. Its TXFARecordContext result contains the data root, selected XML start node, selector kind, ordered record boundaries and the ordinal containing a supplied data node. Each boundary retains its actual node, original zero-based ordinal and XML depth
A numeric record selector selects data groups at that XML depth; level 0 is the actual XML root, not the synthetic datasets/data wrapper. A tag selector finds the first matching data group and then selects same-name groups at that depth, including groups under different parents. For an explicit selector, scalar values cannot define record boundaries. With no selector, the descriptor reports the existing direct-data-child scopes as xrskLegacy
config.acrobat.common.data.startNode can select a different starting element with a root-qualified xfasom(...) path. Omitted sibling indices mean [0]; explicit indices select the corresponding same-name sibling. Record depth starts at zero again at the selected element. An invalid or unmatched start path produces a diagnostic, and explicit record selection requires one XML root
Native $record binding and FormCalc aggregate reads use these boundaries to locate the supplied context's record. A missing value in the second record stays missing instead of reading from the first. An outside or foreign context has no containing record; native reads with no context or with the data pseudo-root explicitly default to the first selected record
Existing unconfigured datasets with multiple same-name top-level groups also retain their repeated root-subform instances. The single-container root-name fallback no longer prevents ordinary repeated-root name matching
The descriptor's ContainingOrdinal is -1 when no supplied node belongs to a record, including a nil context. Rebuild the view after editing or reloading the DOM; returned nodes belong to that document. Operation and deadline limits apply to inspection, which does not mutate the document
TXFADocument.ActiveRecordIdentity can supply an explicit current record for native processing; assigning zero restores context-derived defaults and clears cursor-only navigation state. HPDFXFAActiveRecord validates a nonzero identity against fresh boundaries and raises if a directly assigned identity is no longer present; a deleted record selected through the explicit dataWindow cursor instead becomes undefined. This transient identity is reset by LoadFromBytes and must not be copied between documents
Independent record batch flattening
When config.acrobat.common.data.record selects records, HPDFXFAFlatten processes the selected records in data order. Each iteration starts from the prepared complete XDP, replaces the input Form packet with a fresh Template-derived Form, and creates an independent layout. Ordinary binding and native FormCalc $record reads use the current record, while explicit $data paths retain access to the complete datasets
HPDFXFASelectRecordRange applies config.acrobat.common.data.range to a fresh TXFARecordContext. An empty range selects every record; comma-separated zero-based indices and inclusive intervals select existing records once in original order. Reversed interval endpoints are normalised. Selection preserves each boundary's original ordinal and XML depth, ignores out-of-range indices, and does not expand large intervals into individual indices. Malformed ranges and integer overflow produce diagnostics
All field, draw and page callback indices include the preceding records' physical page counts. Field names receive record[originalOrdinal]. before their per-record name, including the first record; radio members within one record retain a shared group name, and different records have different groups. Selecting only record 1 therefore starts output at page 0 while retaining record[1]. in field names. Result counters and physical page counts accumulate across the batch; no matching records or an empty selected range produces zero output
The prepared medium resource session is shared by the record documents. An unconfigured document retains its existing single-document flattening behaviour. This batch path supports noninteractive output; interactive navigation uses the runtime API below. For separately attached XML streams, use the document overload described below
Streamed record batch flattening
The HPDFXFAFlatten(TXFADocument, ...) overload borrows a document with an attached replay-capable record provider. It replays the journal through bounded resident windows without first saving or loading the complete dataset. Existing record edits are reapplied before each record becomes visible, deleted original ordinals are skipped, and range selection retains the same ordering, deduplication, field-name prefixes and cumulative page indices as the byte-input overload
Each selected record gets a private Form, layout and script lifecycle. Native FormCalc and enabled JavaScript run against the actual streamed provider, including supported cross-window navigation. Changes made by one record's scripts are rolled back before processing the next record, while accepted edits that preceded the batch remain available throughout
The batch uses a private resident document view and restores the caller's provider, cursor, known-count state and retained records on success or failure. The caller's original DOM objects remain intact, allowing an existing Runtime to continue after the call. Fetch the provider again from Document.RecordProvider after restoration instead of reusing a cached provider interface. Keep the document and its backing streams alive, and do not reenter the caller's document or Runtime from an output callback while the private view is active
Malformed ranges are rejected before output starts. Callback output is incremental and cannot be recalled after a later callback or script fails; buffer output or write to a temporary destination when atomic publication is required. Physical reads and cumulative parser, journal and operation budgets are not refunded by restoration. Use file-backed scratch streams to keep input history and edits out of application memory
The batch charges the memory it keeps alive against the same family budget the document's record branches share. The serialisation clone, both checkpoint journals, each captured snapshot and the per-record restored document and layout engine are charged before they are allocated and released with their owner, so a batch never retains unreserved state. Each per-record layout engine also charges its own instance, the registry of emitted field names, the reserved real-name set and the cache it fills whilst resolving final field values, taking every growth before the storage it needs and giving it back when the record completes; the attached-stream batch charges the same family budget, whilst the path that rebuilds records from prepared bytes has no family to inherit and carries a private batch budget. A batch that does not fit the family budget is refused before it emits any field or page callback, and the abandoned batch releases every charge it took. The 100000-operation budget, the 500 ms absolute deadline and the 4096-record limit are unchanged, and a budget that admits both the clone and its journals still refuses a record whose reservation does not fit
Interactive record navigation
For a document with a configured record selector, TXFAWidgetRuntime.RecordCount reports all current record boundaries and CurrentRecordOrdinal reports the current zero-based ordinal. The batch range does not restrict navigation. Without a selector, the native convenience API reports zero records and ordinal -1, and rejects selection
SelectRecord(ordinal) selects an existing record, creates a fresh Template-derived Form, rebuilds widgets and pages, and runs initialisation, calculation and the normal lifecycle. Committed dataset edits survive switching away and back; Form-only edits are replaced by fresh defaults. Selecting the already merged current record is a successful no-op. Invalid ordinals and pending uncommitted edits reject an actual switch without changing the accepted document
Selection uses one transaction and shared execution limits. A script failure restores the prior datasets, Form, cursor, widgets and layout, including the original caller-owned document object for a borrowed layout host. If the script cursor already points to the target but the existing Form belongs to another record, native selection still rebuilds that Form
With the built-in QuickJS engine, xfa.dataWindow and $dataWindow expose read-only currentRecordNumber, isDefined, recordsBefore and recordsAfter. gotoRecord(index) moves to an absolute zero-based index and moveCurrentRecord(offset) moves relatively; both return JavaScript undefined. record(offset) returns the actual relative record node or null, and isRecordGroup(node) checks membership in the current record boundaries
Script movement changes the data cursor without rebuilding the current Form. xfa.record, $record and relative SOM paths such as $record[-1] follow that cursor. Call xfa.form.remerge() to rebuild the Form for the selected record. Existing automatic Form bindings keep their accepted record until that explicit merge
Navigation methods require one signed 32-bit integer argument. An out-of-range cursor remains at its requested number with isDefined=false and no current record; counts before and after are bounded by the resident record count. A selected record that is removed also becomes undefined and does not silently select a replacement at the same ordinal. A subsequent navigation operation can select a live record again
HPDFXFASetRecordCursor supplies the bounded native cursor-only operation. RecordCursorExplicit and RecordCursorOrdinal distinguish it from context-derived defaults; ForceUndefined restores an undefined cursor without selecting a replacement node. Runtime snapshots retain this state across failed transactions
SaveToBytes preserves the accepted Form and datasets. A fresh runtime restores the record associated with that saved automatic Form from its validated data path, not from a previous process's node identity. Cursor-only movement without a merge is transient and is not separately persisted; an explicitly merged undefined Form reloads with an undefined cursor
This profile operates on fully resident datasets. It does not implement incrementalLoad=forwardOnly, streaming input or eviction according to a configured data window
Pull-based XML record source
HPDFXFAStreamRecords provides TXFAStreamRecordSource for reading separate XML data from a TStream, using the record and startNode settings from a supplied XDP configuration document. The source does not require the input stream to support seeking, position queries or size queries
Pass an empty, readable, writable and seekable journal stream together with TXFAStreamRecordLimits. Both streams remain caller-owned and must remain available without external repositioning until the source is freed. Use a file-backed journal to keep fetched XML bytes out of application memory. The source retains parser state and a bounded read buffer, rather than a complete data DOM or an array of every record
Next transfers ownership of one TXFAStreamDataItem to the caller. Items distinguish opened and closed containers, accepted records, other data elements, and XML content. Record items expose their original zero-based ordinal, selection-relative depth, original XML path, byte span and raw XML. Their Document owns the actual Node and its namespace-bearing ancestor wrappers; free the item after consuming it. An item remains valid after the source advances or restores a checkpoint
Numeric and tag selectors use the same record classification as the native DOM, including indexed startNode, different record parents, explicit dataGroup/dataValue overrides and opaque mixed-content subtrees. Inherited namespaces, local prefix rebinding, entity values, CDATA, comments and processing instructions remain available in each owning record DOM
Explicit dataGroup ancestors allow records to be returned before the remaining input is read, subject to a read-ahead buffer of at most 4096 bytes. An implicitly typed ancestor may contain trailing text that changes its classification, so the source first scans that unresolved subtree into the journal and then replays it. Such input can require reading to the end before returning its first record; that scan does not build a complete DOM
Capture and Restore preserve the logical parser position, container scopes and next original ordinal. Bytes fetched after a checkpoint remain in the journal and can be replayed without seeking or rereading the original stream. Restore does not reset cumulative operation or parsing budgets. Checkpoints belong to their original source instance
Limits cover individual tokens and elements, nesting, distinct sibling names, total journal bytes, token operations and cumulative parsed bytes. If the journal limit is reached before EOF has been observed, the next read fails rather than probing an unjournaled byte. EOF returns no item; truncated later elements fail without invalidating previously returned owning items
HPDFXFAReadStreamConfiguration reads incrementalLoad and single-value or comma-separated window settings from acrobat/common/data. Its product default for an omitted window is 0,0. Existing LoadFromBytes input remains fully resident; attach a separate XML stream explicitly with the document provider described below
Structural operation journal
HPDFXFAStreamStructure.TXFAStreamStructureJournal records ordered insert, replace, move and remove operations in a caller-owned, initially empty, readable, writable and seekable stream. Use a file stream to keep historical XML payloads on disk. The structured export API below applies the journal to XML output; the optional attached movement journal also persists movement of existing resident event roots
HPDFXFASourceReference identifies an element by its immutable source path, with an empty path identifying the source document boundary outside its XML root. Use the actual element path, such as /data[0], to address that element. Insert(ParentRef, BeforeRef, XML) returns a synthetic reference in a separate identity space. Move and Remove accept either source or synthetic references. An empty BeforeRef means the end of the parent's children at that operation's position in the log. Operations must be applied in order: a later movement of the anchor does not implicitly move a node inserted earlier
Replace(NodeRef, XML) updates a live synthetic node's own XML payload while preserving its i: identity, placement and independently journaled children. The new element name, attributes and opaque inner content replace the earlier payload; independently inserted or moved children keep their order after that content. This operation does not replace the complete assembled subtree or introduce positions inside opaque content. Use Remove to delete the node; an empty replacement is invalid. Source records continue to use their original-ordinal overlay
InsertContent(ParentRef, BeforeRef, XML) and ReplaceContent(NodeRef, XML) represent independent text, CDATA, comment or processing-instruction nodes in that same ordered history. Empty text is valid. Content references can move or be removed but cannot contain children or change into element references. To interleave content with independent elements, insert an empty container header and register each child in order; element payload interiors remain atomic
Capture and Restore preserve the logical log prefix and reject checkpoints from a discarded branch. Synthetic identities are not reused after rollback. BeginRead freezes a prefix and ReadNext reads it in order without loading all historical operations; later appends do not extend that cursor, and replacing its prefix invalidates it. Limits cover physical storage, cumulative operation usage, individual payload bytes and reference bytes; rollback does not refund cumulative usage or the physical high-water storage budget
The journal validates its storage and reference representation. The consuming document layer must resolve references, check parent and sibling membership, prevent structural cycles, classify inserted records and validate the XML in its destination namespace context before accepting an operation
Structured stream export
HPDFXFAStreamStructureExport.HPDFXFAWriteStructuredStreamData(Source, Overlay, Journal, Destination, Limits, ResolveNode) exports the accepted structural journal through a sparse projection. Insertions, replacements, moves and removals are applied in their original order, and a moved source element is emitted only at its final location. Moving a container carries its unread descendants; moving a child out before deleting its former ancestor preserves that child
The projection stores descriptors for referenced nodes and ranges between them, rather than an index of every source record. Inserted and replacement XML remain in the journal; each synthetic node keeps a cursor to its latest payload, which is read on demand. An inserted parent retains the children supplied in its original XML and can receive further inserted or moved event roots. TXFAStreamProjectionLimits bounds edit count, final depth and cumulative descriptor accounting; MaxPlanBytes also separately limits the encoded XML retained during export. These are accounting budgets rather than exact measurements of allocator overhead
Source references address record, global and open-container event roots. Complete record and global payloads remain atomic at this boundary: edit their interiors through the existing bounded payload mechanisms. Existing record overlays remain keyed by original ordinals, and the optional node resolver supplies global or container replacements. Export restores the source's logical position while retaining cumulative read and parse charges
Inserted and replacement payloads must be self-contained single-element XML, including any required namespace declarations, without a document-type declaration. Their own namespace meanings are retained at the destination. Structural references, every inserted and replacement payload including overwritten or later removed versions, and the final output tree are checked before the destination receives bytes. By default, final output must have one XML root and fit the configured depth. The optional final AllowFragment argument permits zero or multiple top-level elements when writing inside an existing wrapper; the attached provider enables it for XDP data content. A later I/O failure can still leave partial destination output, so use a temporary destination when publication must be atomic
A resolver deletion follows the final projected subtree: a child moved out before its former container is suppressed remains live at its new location, unless that child's own overlay or resolver result deletes it. Keep resolver results and all borrowed streams stable throughout validation and writing, and supply distinct streams for source replay, overlays, structural journal storage and output
HPDFXFAResolveStructuredStreamPaths uses the same output traversal to resolve requested identities to final local-name sibling paths. Requests accept original source-relative paths, explicit s: source references, and synthetic i: references. A synthetic reference may include a descendant path within its current effective payload. Complete record or global descendant suffixes address the current effective payload, including overlay edits. Missing or deleted targets return an empty string, duplicates retain their input positions, and source position is restored
Typed content is validated even when a later operation replaces or removes it. Text entities, CDATA, comments and processing instructions keep their XML meaning; serialiser-split CDATA reconstructs one logical content node. Content does not consume element sibling indexes or resolve to element paths. At the source document boundary, only whitespace, comments and processing instructions are accepted as content, including when AllowFragment is enabled
The standalone exporter supports inserted XML independently of the attached provider. The attached provider supports complete new records, new containers and ordered mixed content as described below. Original record ordinal APIs retain their existing meanings
Resident windows and disk-backed record edits
HPDFXFAStreamWindow.TXFAStreamRecordWindow borrows a fresh record source and retains a bounded set of owning record DOMs. Set BeforeCount and AfterCount in TXFAStreamWindowLimits from the configuration values before constructing the window. AdvanceTo loads enough records for the requested original ordinal and its lookahead, then evicts old records, including excess history when lookahead reaches EOF
RecordAt reads an offset from the current cursor using resident records only and never reads the input. ResidentItem enumerates the current array; its index is distinct from each item's OriginalOrdinal. Backward movement is allowed within retained records, without reloading evicted history or discarding already loaded lookahead. TryGetRecordCount returns false and a count of -1 until logical EOF, then reports the complete original record count
Previously consumed globals remain available through GlobalItem, while OpenContainerItem exposes only the active ancestor stack. Physical read-ahead does not publish future globals. XML whitespace and completed container events do not accumulate in the window; their exact bytes remain in the journal
The optional OnAcceptItem predicate filters records, globals and opening containers before payload retention. It must not mutate the borrowed item or reenter the window. Rejected records and globals are discarded; rejected opening containers retain only their path and position metadata for matching closing events, with Node and Document set to nil. PruneFilteredItems applies the predicate to existing retained items, preserving leased record DOMs until their final owner releases them
Pin returns a caller-owned TXFAStreamRecordLease that keeps its exact record DOM alive after eviction or window destruction. The borrowed Item must not be freed separately. Free the lease or call Unpin after its consumer releases all node references. Each concrete item supports one lease, and MaxPinnedRecords limits simultaneous leases, including old and restored DOM epochs
Capture creates a caller-owned snapshot and supports nested snapshots within one aggregate MaxSnapshotBytes budget. It deep-copies resident records, retained globals, open containers and pinned records, and captures the source's logical state. Only the newest active snapshot can be restored; freeing a snapshot releases its budget. Restore creates fresh node identities and restores record contents without rereading the physical source. Existing leases continue to own their old nodes, so a Form consumer must rebuild its references and acquire replacement leases after rollback. Restored copies of evicted pinned records remain available for reacquisition until the next advance
Rewind restores the initial logical source position and clears window visibility without seeking the original input or refunding cumulative budgets. Existing leases retain their exact old objects. OnRecordLoaded runs before a replayed record enters the window, allowing the document provider to apply its persisted replacement; a callback failure restores the source position for a later retry
MaxGlobalItems bounds retained non-record data. MaxRetainedBytes and MaxSnapshotBytes account for raw XML, paths and serialised DOM size; they are XML budgets, not exact process heap measurements. Source parsing limits remain independently applicable. A failed or out-of-range advance can have consumed events and evicted records before returning, so callers needing transaction rollback must capture and restore the window and their overlay state together
BeforeEvict runs while the old item is still alive and must succeed before it is released. An integration layer can serialise a changed record there and pass it to HPDFXFAStreamOverlay.TXFAStreamOverlayStore.Put, using the item's original ordinal and half-open byte span. The replacement must be one complete record element valid in its original XML context; an empty replacement deletes that element
The overlay store borrows three distinct, initially empty, readable, writable and seekable streams for its ordinal index, replacement payloads and undo log. Use files for all three to avoid retaining historical edits in memory. Capture and Restore use disk undo entries and reject checkpoints from discarded transaction branches. MaxBytes bounds the combined physical high-water marks; rollback reuses logical tails without requiring stream truncation or refunding the storage budget
SaveTo(Source, Destination) merges recorded replacements with the complete original XML, including records never loaded into the window. It copies unchanged intervals directly from the journal, preserving the BOM, declaration, DOCTYPE, whitespace, comments and processing instructions. Before writing, it completes token framing and EOF validation of the unread tail without constructing future record DOMs, then restores the source's logical checkpoint. This is not complete namespace, entity or DTD semantic validation
CopyOriginalSpan copies a fetched byte interval, CompleteJournalValidated completes token framing validation while preserving logical visibility, and OriginalLength returns -1 until EOF has been observed. Output and overlay storage must not alias the source or journal; distinct wrappers over the same underlying storage also remain the caller's responsibility. A destination write failure can leave partial output
The integration layer must flush dirty resident and leased records before final export; window destruction does not invoke persistence callbacks. The document provider below performs this synchronisation for native Runtime transactions
Document-owned streams and native Runtime navigation
HPDFXFAStreamDocument.HPDFXFAAttachStream attaches separate XML data to a configuration/template document, using an input stream, replay journal, ordinal index, replacement payload stream and undo stream. Pass source limits, window limits and the overlay storage limit explicitly. The document owns the provider; all five streams remain caller-owned and must outlive the document and its transaction checkpoints. Use distinct file-backed scratch streams to keep input history and accepted record edits on disk
TXFAWidgetRuntime.CreateForDocument(Document, Width, Height, Options) creates a Runtime that borrows this document. The caller must keep the document alive until the Runtime is freed. Native SelectRecord loads the requested original ordinal and its lookahead, retains the previously merged Form record while remerging, and releases retired native Form state after successful navigation. A pending edit must be committed or cancelled before navigation
TryGetRecordCount reports whether logical EOF has established the total. RecordCount returns -1 while the total remains unknown. Queries do not pull additional records, and physical read-ahead or a complete save does not make future globals visible in the current window
Runtime transaction snapshots serialise the resident document and capture the window plus disk overlay checkpoint. Rollback maps restored DOM nodes to their original source paths and record ordinals before rebuilding widgets, then restores the backend state. Physical reads and cumulative parsing budgets are not refunded
After checkpoint restoration, saved automatic Form bindings track their original data-node identities within each retained record. Reordering same-name data siblings updates the saved path to the original target; deleting that target leaves the binding undefined even when another same-name sibling occupies its former position. Repeated checkpoints preserve this distinction
Document.SaveToStream and Runtime.SaveToStream write a complete XDP, including evicted edited records and unread records. Resident record edits and retained global/container changes are synchronised before export. XML entities are decoded with the original input context and escaped by the native writer, so the embedded data does not depend on an omitted input DOCTYPE. Export replays one bounded data item at a time and consumes the cumulative source parsing budget; it restores the logical input position afterward
SaveToBytes provides the same complete output in memory, while SaveResidentToBytes is an internal snapshot-oriented view that deliberately omits evicted and unread data. Complete output can fail after writing a prefix; use a temporary destination when the application requires atomic file replacement
This integration covers native and JavaScript record navigation, record-internal edits, removal of record roots, globals and ancestor containers, root-element renaming, existing global content and container attributes, and streamed batch flattening. The extended attachment overload below adds movement of existing event roots and insertion of records, containers and ordered mixed content. Total live JavaScript heap accounting remains separate work
Querying accepted logical record order
The optional IXFARecordOrderProvider interface exposes GetBindingIndex(Document, NodeIdentity, BindingIndex, Remaining, Deadline, DeadlineCheck) for attached streams. It returns a zero-based Int64 position in the accepted structural record order, counting live source and inserted records together. A resident record root or descendant identity selects its containing record; an unknown, deleted or non-record identity returns false and an index of -1
Synchronise pending native DOM edits through IXFAScriptRecordReferenceRetentionProvider.SynchronizeRecordReferences before querying. The query uses the accepted journal and overlay state, preserves the current cursor and Form, and does not synchronise edits or select another record. A prepared checkpoint provider cannot answer until its restoration is committed. Original ordinals, source counts, batch ranges and existing navigation APIs retain their original meanings
Insertions, moves and deletions change logical positions; containers contribute their surviving record descendants, while text, comments, processing instructions and scalar values contribute no records. The sparse order graph replays journal operations in sequence and resolves only the source ranges needed to count records before the target. It retains edited descriptors and one parsed payload at a time rather than materialising the full source
Queries restore the logical parser position and never publish newly encountered globals to the resident DOM. Physical reads and cumulative parse charges remain consumed. A target appended after an unresolved tail can require EOF, and a moved source container can require reading its descendants. Existing source classification may also inspect an entire container without an explicit dataNode type. Operation, depth and allocation limits apply; a failed query returns no partial index, and a later query rebuilds its plan against the current accepted state
Native merging and actual JavaScript global-binding refresh use this order-query API automatically when several external candidates match. The logical navigation extensions below use neighbouring addresses to move across source and inserted records
Finding logical neighbouring records
The optional IXFARecordAdjacencyProvider.QueryAdjacent(Document, NodeIdentity, Direction, AllowSourceRead, Address, Remaining, Deadline, DeadlineCheck) finds the immediately preceding or following live record in accepted structural order. Use -1 or 1 for Direction, and synchronise pending DOM edits before querying, as for logical binding indices
A xrasFound result supplies a TXFARecordAddress: source records have Kind=xrakSource, their immutable original ordinal and an attachment-local source reference; inserted records have Kind=xrakInserted, their stable inserted reference and ordinal -1. The query follows source ranges and inserted nodes together, skips deleted records and traverses moved containers according to their accepted placement
xrasEnd means the direction has been fully checked and no neighbour exists. xrasUnknownCoverage means the answer requires source bytes that a query with AllowSourceRead=false is forbidden to fetch. xrasUnavailable means the starting identity has no live containing record. Non-found results clear the address and set its ordinal to -1; malformed input, invalid directions and exhausted budgets raise errors instead of reporting an endpoint
With source reads disabled, parsing is restricted to bytes already in the replay journal, including when a token or an untyped container spans the fetched boundary. Allowing reads can inspect the necessary source range; reverse lookup keeps only the last matching address rather than an array of all records. Both modes restore the logical parser position and preserve the cursor, Form and resident globals. Physical reads and parse charges are not refunded
This API locates addresses, including records outside the resident window. Use the address-loading API below to load such a target, or the logical navigation extensions to query and select a neighbour in one transaction
Loading and selecting record addresses
The optional IXFARecordAddressProvider.AdvanceAddress(Document, Address, Remaining, Deadline, DeadlineCheck) loads a source or inserted address returned by the neighbouring-record query. Source addresses must match both their immutable source reference and original ordinal. The operation can reload an evicted source record into a bounded window without clearing previously loaded globals or replacing current retained record identities
This low-level operation does not select the document cursor or rebuild the Form. Synchronization preserves edits before replay, restores overlay payloads for reloaded records and retains caller, script and accepted Form ownership. As with provider advancement, capture a document or runtime transaction before loading: an unavailable target or exception can follow partial source advancement and requires caller rollback
TXFAWidgetRuntime.SelectRecordAddress(Address) supplies that transaction, selects the loaded source or inserted cursor and merges the Form for its record. Selecting the already accepted Form record preserves the existing no-op selection behaviour. Active edits must first be committed or cancelled. Unavailable or mismatched addresses fail with a diagnostic and restore the previous document, cursor and Form; lifecycle changes that leave another cursor or Form scope also fail the selection
Already loaded globals retain their identities when returning to an earlier source position, and later forward replay does not publish them twice. A known source record count remains known after recentring. Old leases from before snapshot restoration keep their own readable nodes until released, but those old nodes cannot be pinned or revived as records of the current restored state
Addresses are scoped to the same attached source. Source movement, renaming and eviction preserve the original source coordinate; deletion makes it unavailable until restored. An inserted address removed by rollback is not reused by a later insertion. The address has no cross-document owner token and must not be reused after attaching a different source, even if its path and ordinal happen to match
Moving through logical record order
TXFAWidgetRuntime.MoveLogicalRecord(Direction) moves one live record backward or forward in an attached stream's accepted structural order. Direction must be -1 or 1. Pending structural edits, neighbouring-address lookup, loading, cursor selection and Form merging share one runtime snapshot and operation/deadline budget. Inserted records participate in the same order as source records; deleted records are skipped and moved containers retain their accepted placement
A successful native move returns true and rebuilds the Form for the selected record. Reaching an endpoint returns false with a boundary diagnostic, preserving the current cursor and Form without publishing layout notifications. An unavailable current record, invalid direction, pending edit or execution failure returns false with a diagnostic; failures inside the transaction restore its prior state
The HotPDF extension xfa.dataWindow.queryLogicalRecord(direction, allowSourceRead=false) returns an object with status and address. Status is "found", "end", "unknownCoverage" or "unavailable". A found address contains kind ("source" or "inserted"), reference and originalOrdinal; other statuses have a null address. The default query uses only already fetched source bytes. Passing true permits the source reads needed to establish the neighbour, without publishing its payload or changing the cursor and accepted Form
xfa.dataWindow.moveLogicalRecord(direction) allows source reads and loads the exact neighbouring record, including an evicted source record. It returns true after moving and false at an endpoint. An unavailable starting record or loading failure is an event error. Like other JavaScript navigation methods, it changes the data cursor without implicitly rebuilding the Form; call xfa.form.remerge() when the Form should follow the new record
Both script methods apply preceding event edits before querying the accepted structure. Query responses refresh record metadata; successful movement refreshes the resident script model while preserving retained handles and the accepted Form's record scope. Later event failure restores the edits and cursor together. Explicit logical moves share the existing 64-operation window-navigation limit; query responses remain subject to operation, time and response-byte budgets
After restoration, the stream provider resolves the accepted Form scope through its checkpoint target identity even if later structural edits change the record's XML path. Resolution preserves the restored Form bytes and still verifies that the target belongs to the current record context; unknown or invalid saved scopes remain errors
These methods extend logical navigation without changing original-ordinal APIs: gotoRecord, moveCurrentRecord, record(offset) and native SelectRecord retain their existing coordinates. Address queries require an attached provider with logical adjacency support, and native logical movement additionally requires address loading support. For an ordinary in-memory document, JavaScript movement follows its current record boundaries; its address query returns "unavailable" because no stable stream address exists
Inserting and selecting attached stream records
With structural storage attached, native callers can insert complete records beneath existing or newly inserted containers. A new record must satisfy the captured selection scope and depth as well as data-group classification; an explicitly marked empty dataGroup is valid, while a dataValue does not become a group merely by containing an element. The inserted record is an atomic payload at the streaming boundary, with its own stable identity and bounded serialised size
Obtain the optional IXFARecordReferenceProvider interface from the document provider and call GetRecordReference(Document, NodeIdentity, Reference) to synchronise native edits and obtain the inserted record's i: reference. A descendant identity resolves to its containing inserted record. Original source records return false and continue to use original-ordinal navigation
Runtime.SelectRecordReference(Reference) selects an inserted record transactionally and rebuilds its Form and layout. CurrentRecordReference exposes that selection, while CurrentRecordOrdinal is -1. Insertions do not renumber original source records or change the original source count. References belong to this stream attachment and its surviving checkpoint history; after complete saving and loading as a new document, records are classified from the saved XML rather than addressed by the former attachment's references
Accepted payload edits retain the same reference through eviction and replay. The selected record and the record supplying the automatic Form remain available within the existing retention budgets. Complete saving includes inserted records and resolves their Form bindings to ordinary output paths. Runtime transaction snapshots restore insertion, replacement, movement, deletion and reference selection together; source-range batch output preserves the caller's inserted-record selection. Direct provider-checkpoint callers must also save and restore the document's cursor reference and undefined-selection state alongside its resident DOM
Record-context queries remain read-only, so callers can inspect and repair native edits after a rejected synchronisation. Reference lookup, navigation, capture and saving synchronise pending edits. Failed structural synchronisation restores its journal prefix and mapping metadata, but does not undo the caller's native DOM edits; direct callers needing complete rollback must retain their document checkpoint. Active snapshots share the same MaxSnapshotBytes budget for source-window copies and inserted-record XML and metadata accounting
For a registered and selected inserted record, the built-in JavaScript runtime recognises $record, xfa.record, record(0), local global-binding values, shared unique external globals and multiple external candidates selected by logical position. Its original ordinal is -1, resident before/after counts are zero, other original-ordinal relative record queries return null, and moveCurrentRecord raises an error. Use queryLogicalRecord and moveLogicalRecord to navigate its live source or inserted neighbours
The HotPDF extensions xfa.dataWindow.currentRecordReference and gotoRecordReference(reference) expose stable-reference navigation to scripts. Save the current inserted record's reference, use gotoRecord to visit original source records, then pass the saved reference to gotoRecordReference to return. The read-only property is an empty string for source selection; an explicit inserted cursor keeps its reference when the selected record becomes undefined, so use isDefined to check availability
Reference navigation requires an attached stream with a registered inserted record. References are opaque attachment-local strings obtained from the native provider or the current-reference property. A malformed argument is a script error; an unknown, removed or discarded-branch reference fails the event and rolls back its edits and cursor. The window request applies preceding script edits and retained ownership before selecting the record, preserving saved record and descendant handles. Like gotoRecord, it changes the data cursor without automatically rebuilding the Form; call xfa.form.remerge() when the Form should use the new record
Scripts can create a dataGroup with xfa.datasets.createNode, populate its bounded payload and append or insert it beneath an established record parent. At a navigation or remerge boundary, and after successful event execution, the host applies the action prefix and registers its new records before resolving script ownership. A saved record handle or descendant handle therefore keeps the complete inserted record available across subsequent source navigation, including navigation later in the same event
Inserting containers and mixed content
New non-record elements are stored as container headers with independently ordered children. Native callers can interleave elements and moved source roots with AddText, CDATA text, AddComment and AddProcessingInstruction. Subsequent header and content edits, source-window replay, nested checkpoints and complete saving preserve that order. Scripts can also create containers, move source records into them and retain newly created child records across navigation and failed-event rollback
Record classification follows the source selection lineage: named selectors retain their established target depth, numeric selectors use depth relative to the configured startNode, and insertion outside that scope does not create a record. Scalar containers and non-record containers at the target depth block deeper record candidates. Ordinary containers and content do not receive record references; descendants of a complete new record resolve to that containing record. Moving an original record retains its original ordinal
Mixed text follows the native DOM's aggregate-value contract. When editing ordinary text children directly, keep the parent's Value equal to their concatenated values, including CDATA. Assigning a different parent Value overrides those text children while preserving comments, processing instructions and elements. Synchronisation restores any normalisation it performed if its structural update fails. Checkpoints preserve adjacent and empty content-node boundaries even when ordinary XML loading would merge or omit those nodes
New container and content descriptors use the existing global-item, retained-byte, edit and snapshot budgets. Complete saving resolves inserted-record Form bindings against their final element paths. A source child moved out before its new container is removed survives that removal. Original complete record and global payloads remain atomic; moving an independently mapped stream root inside one still requires further integration
Moving existing attached stream nodes
The extended HPDFXFAAttachStream overload appends StructureStorage, TXFAStreamStructureLimits and TXFAStreamProjectionLimits to the original argument list. Supply a separate, initially empty, readable, writable and seekable structure stream that outlives the document and its checkpoints. The original overload retains its existing behaviour
With structural storage attached, native ownership changes can move or reorder mapped record, global and ancestor-container roots beneath mapped containers. Synchronisation journals the accepted order. It keeps lightweight references for affected nodes and anchors while record payloads remain subject to window eviction. Replaying newly read or previously evicted records reconstructs the accepted placement without reading the complete source merely to synchronise a move
Movement keeps original record ordinals and the original source record count. Window navigation continues to use those source coordinates, while the resident DOM and complete saved XML use the changed parent and sibling order. Moving a child out before deleting its original ancestor preserves it during replay and saving. Complete saving resolves existing Form bindings against final output paths, including siblings that were absent from the resident window
Document checkpoints restore structural history together with the record window and overlay state. Synchronisation checks the active structural operation count before accepting further moves, and failed structural synchronisation restores its journal prefix and mapping metadata. Direct DOM callers should capture a checkpoint before a group of edits when they need atomic rollback. Moving an event root inside an opaque record or global payload requires further integration; ordinary edits inside an existing complete payload retain their existing support
Removing streamed globals and containers
Removing a global or ancestor-container node through native child ownership or JavaScript nodes.remove removes that element from complete output. A container removal also hides all its descendants, including records and globals that have not yet been read. Navigation retains original source ordinals: deleted positions are undefined, surviving records keep their original numbers, and the known record count continues to describe the original source extent
The provider keeps bounded deletion markers in original source coordinates. Replaying the source cannot restore a removed subtree, and deleted records and globals are filtered before entering the retained window. Container opening and closing metadata remain balanced while input parsing and cumulative budgets continue normally. Deleting a container does not require loading its complete contents first
Complete export omits the deleted subtree and rebases surviving Form bindings to output sibling positions. Document checkpoints and Runtime event rollback restore deletion state and window ownership together; physical reads and cumulative parsing budgets are not refunded
Deleting the record that supplied the current automatic Form does not delete that Form or invalidate its live script handles. Ordinary navigation and layout updates retain its existing values until an explicit selection or remerge replaces it; stale references to the deleted data are cleared
Renaming streamed elements
Record, global and ancestor-container elements can change their local names through native nodes or JavaScript data-node name assignment. Native node edits can also change the prefix and namespace URI. Accepted record replacements survive eviction and journal replay; global payloads and container headers preserve their changes through complete export, including matching container opening and closing tags
Original record ordinals and source paths remain stable while the stream is attached. Renaming a record away from a configured name selector does not remove its current streamed identity. A saved document loaded as a new document runs selection against the new XML names and can therefore select a different set of records
Complete export computes Form binding paths from the actual output names, including renamed ancestors and collisions with same-name siblings. Root-name changes do not reuse stale source sibling indices. The path resolver applies MaxSiblingNames to distinct output names under each open parent, and replay continues to consume the source's cumulative parsing budget. Runtime transactions restore names, bindings and replacement state after a failed event; direct DOM/provider users must retain their own document checkpoint
Provider replay retains records still owned by the current Form, caller or script. A Form restored from a checkpoint keeps its captured source-coordinate provenance even when the resident window changes sibling positions. Namespace serialisation isolates standalone fragments from the destination's default namespace and preserves attribute namespace URIs when an edited element requires a different prefix binding
Deleting streamed records
Remove an attached record root through its native parent node or the JavaScript data-node collection. Synchronization stores an empty replacement in the disk overlay, excludes the record from subsequent window assembly and releases its caller, script and automatic Form leases. Retained references do not restore the deleted source record, and explicitly requesting a native lease for it raises an error
Original record ordinals remain stable and may contain gaps. Deleting record zero leaves record one at ordinal one; record(offset) uses those original coordinates. Selecting a deleted ordinal leaves an undefined JavaScript cursor, while native SelectRecord fails transactionally. Deleting the current record makes its cursor undefined; an explicit remerge rebuilds the Form without that record's data. Once EOF is known, TryGetRecordCount still reports the original source extent, including deleted positions
Complete saving omits deleted records and rebases automatic Form binding paths to their surviving XML sibling indexes. Path resolution replays the source journal once for the current bindings, preserves the logical source position and does not publish EOF or seek the physical input. Replay consumes the existing cumulative parsing budget. Failed Runtime transactions restore deletion state, data, Form and retained ownership together; direct DOM/provider callers still need their own document checkpoint for atomic rollback
JavaScript navigation through streamed records
With the built-in QuickJS engine enabled, xfa.dataWindow.gotoRecord and moveCurrentRecord load the requested original record ordinal through the document provider before subsequent script statements execute. Moving the cursor preserves the currently merged Form and its widgets until an explicit xfa.form.remerge(). A request beyond EOF leaves an undefined cursor and establishes the total record count
record(offset) queries only resident records relative to the original cursor ordinal; it does not read the source or move the cursor. recordsBefore and recordsAfter describe the available resident window. A record retained for the old Form is excluded from ordinary resident enumeration and global-binding fallback
Window changes and remerge operations can occur within the same event. The host applies the completed action prefix, loads the window and replays the event with a saved response so earlier actions are not applied twice. A failed event restores record contents, the logical window, Form bindings and widget state; physical source reads and cumulative budgets remain consumed
After a successful outer event, obsolete native Form roots and identities are retired. Script ownership preserves referenced data records through eviction; it does not revive retired Form objects or establish a bound on the complete live JavaScript heap
Native retained-record ownership
The stream document provider exposes the optional IXFARecordRetentionProvider interface. SetRetainedRecords(Document, OriginalOrdinals) replaces the caller's retained set using original source ordinals; duplicates share a single lease, and the automatically bound Form record shares that same lease when requested explicitly
Retained records remain in the document after leaving the navigation window. TXFARecordContext.Records continues to contain only resident navigation records, while RetainedRecords identifies additional retained boundaries with their original ordinals. Retention does not read new source records, select a different current record or make an evicted record navigable
The requested set and automatic binding share MaxPinnedRecords. Replacing a full set checks the final set rather than requiring spare temporary slots, and invalid requests preserve the existing leases. Retained data edits participate in complete stream export and document checkpoint restoration; restored DOM nodes belong to a new epoch and must be resolved again
Lease validation and replacement do not provide a complete document transaction. Like provider advancement, synchronisation and DOM rebuilding can fail after work has begun; use the document's record checkpoint and resident DOM snapshot when the entire operation must roll back. TXFAStreamRecordWindow.ReplaceLeases requires an owning lease list without notification callbacks so publication cannot invoke caller code
Automatic script record retention
The built-in QuickJS runtime tracks public node handles, independently saved methods, query and live-child collections, paused iterators, event and module scopes, and saved layout methods. Their data records remain available when the navigation window moves and after native SelectRecord. Data child collections support Symbol.iterator; iteration resolves the retained owner against the current model
Ownership is captured before a window or remerge suspension and after a successful event. The host applies pending actions and aliases before resolving identities to original records. Retained edits participate in complete export, and failed Runtime transactions restore prior contents and ownership. Ownership metadata travels separately from replay actions and results so collection timing cannot change their comparison
The optional IXFAScriptRecordRetentionProvider.SetScriptRetainedRecords channel is independent of IXFARecordRetentionProvider.SetRetainedRecords. Script, caller and automatic Form sets share deduplicated leases and the same MaxPinnedRecords budget; clearing one set does not clear the others. Custom record providers must implement the script channel to participate in automatic retention
The attached provider also implements IXFAScriptRecordReferenceRetentionProvider for inserted records. SynchronizeRecordReferences registers applied native actions without pruning nodes before ownership is collected. SetScriptRetainedRecordReferences publishes the original-ordinal and inserted-reference script sets together, avoiding an intermediate eviction. Source owners, inserted owners, the selected inserted record and automatic Form records share a deduplicated MaxPinnedRecords limit; reference metadata also counts toward retained and snapshot byte budgets
Live inserted-record handles survive native source selection, explicit remerge, transaction rollback and source-range batch output. Dropping acyclic owners permits their payloads to leave the resident DOM at later collection boundaries, while accepted edits remain in the structural journal for complete output. The original ordinal-only script-retention interface preserves the separate inserted-reference set; providers without the new optional interface retain their existing source-record behaviour
With a bridge exposing HPDFQJS_CollectGarbage, successful outer script events collect unreachable ordinary cycles, refresh weak ownership and release records whose final script owner disappeared. Pending navigation and remerge boundaries preserve stack-captured ownership, and nested lifecycle events defer collection until the outer script finishes. Recovery replays collection positions separately from action results; rollback discards positions belonging to abandoned events
Older bridges keep their previous collection behaviour. Without WeakRef, the fallback retains owners strongly until session teardown or a resource-limit error. Collection does not guarantee reclamation of every weak-container graph, including the bundled engine's WeakMap value-to-key cycles. The registry caps owners at 262144, scanned identity references at 1048576 and scanned UTF-16 identity metadata at 64 MiB. Host transfer also obeys MaxValueBytes and a 16 MiB ceiling, and native record budgets still apply
JavaScript heap statistics and explicit collection
THPDFQuickJS.TryGetMemoryUsage returns THPDFQuickJSMemoryUsage with allocator bytes and limit, estimated used bytes, allocation count, and object, string and atom counts and bytes. Check SupportsMemoryUsage and SupportsGarbageCollection before using optional bridge capabilities. CollectGarbage runs at a host safe point between evaluations and does not execute pending JavaScript jobs; reading statistics does not implicitly collect
TXFAWidgetRuntime.TryGetJavaScriptMemoryUsage, JavaScriptMemoryUsageAvailable and JavaScriptGarbageCollectionAvailable expose the active built-in session's capabilities. Before an engine exists or while failed-event recovery is pending, statistics return false and clear the output record. Rebuild the dynamic bridge to enable the new optional exports; ABI 1 bridges without them still evaluate scripts normally
Statistics cover the entire QuickJS runtime, including builtins and internal objects; uncollected cycles contribute to object counts. JavaScriptMemoryBytes limits engine allocator memory, not bridge output buffers, Pascal strings, native DOMs, replay storage or process RSS. Garbage collection itself is not interruptible by the JavaScript instruction callback, so the event checks elapsed time after collection rather than guaranteeing a hard collection deadline. This API does not add a separate live-object count limit or update the prebuilt static bridge
Disk-backed JavaScript replay history
Script history and expected results use TXFAReplayJournal with disk-backed payloads and fixed-size index entries. Its owned temporary files are created lazily on the first append and removed when the journal is destroyed. Applications using the journal directly may instead supply two distinct, empty, readable, writable and seekable streams
Checkpoints retain logical entry counts. Rollback truncates abandoned journal tails, and an unrecoverable storage rollback makes the journal unusable. Session recovery reconstructs the engine by replaying accepted scripts and checking their results, preserving user functions and closure state. It reads history one entry at a time; recovery time still grows with accepted history, and current-transaction replay may materialise that transaction's entries
MaxJournalBytes and MaxJournalEvents remain total storage and event limits, not live-heap measurements. Moving replay history to disk does not discard accepted events, create a virtual-machine heap checkpoint or bound application-retained JavaScript objects
Persistent event and script-object handles
Explicit Form remerge or permanent instance removal retires the affected script modules and removes their cached exports, including alias entries for the same canonical identity. Temporary record-window eviction and reusable detached nodes do not retire modules. A caller-held ordinary closure can still retain module variables and data records; those records remain pinned until the caller releases the closure. Existing module-bound methods keep their retired-target errors
With a garbage-collection-capable bridge, native Remerge also refreshes retained ownership after successful lifecycle processing, even when no initialisation script runs. This maintenance uses the existing transaction and resource budget and skips nested script execution, whose outer event retains responsibility for pending owners. Failed transactions restore module state and record ownership through session replay
In-memory documents also release replaced active Form trees when the outer transaction succeeds, including remerge initiated by focus events. The Runtime tracks these retired roots explicitly and preserves unrelated detached native nodes. Failed transactions restore the accepted document and identity state. This cleanup does not change the existing retirement behaviour of JavaScript Form handles across remerge
Script objects retain node handles by identity. Saved built-in node, global lookup, data-child collection and instance-manager methods resolve their receiver against the current event model when called, so a saved method observes later accepted data and instance changes. Removed or retired targets retain their existing error behaviour
Handle factories and script-object scopes are installed outside the event builder. User functions retain their lexical state and saved function values, while built-in method wrappers keep identity or property-path descriptors instead of an old event receiver. Engines with WeakRef use weak proxy-cache values and remove expired entries at the next event; a still-held proxy keeps its object identity. Engines without WeakRef retain the strong-cache fallback
Ordinary event scripts also receive persistent handles through this, aliases, event.target and global XFA accessors. Event closures retain their local variables while node access resolves the current model; this === event.target and event === xfa.event preserve their event identity relationships. FormCalc built-ins resolve the current implementation and event context when invoked
Retained query lists preserve their selected membership, while live child collections resolve the owner's current children. Index access, property descriptors, list methods, array callbacks and iterators expose persistent node handles. Paused live iterators do not retain a raw children array from an earlier event. List mutation keeps the existing query-versus-DOM semantics, budgets and transaction rollback
Saved xfa.layout methods preserve completed-query coordinates, page counts, numbering and membership through independent primitive and identity snapshots. They resolve node arguments and returned members against the current model and charge the current event's execution and collection budgets. Automatic script ownership retains referenced streamed data records; these handle boundaries do not establish a bounded total JavaScript heap
Dynamic FormCalc Eval executes in an independent scope. Returned functions preserve their local variables and resolve implicit SOM lookups against their defining node's current identity, even when called by another event; an explicit node receiver or lookup context still takes precedence. Saved references and methods use the same persistent boundaries as ordinary scripts. Catching a recursive depth-limit error restores the evaluation depth so later valid calls can continue, while compilation retries and transaction rollback retain their existing limits
FormCalc Mod returns a signed floating-point remainder. For finite operands with a nonzero divisor, the result keeps the dividend sign and does not depend on the quotient fitting in an integer or floating-point value
FormCalc Round rounds halfway values away from zero and preserves large finite values when the requested decimal precision cannot change the result
FormCalc Choose uses one-based indexes, rounds fractional indexes down, and returns an empty string for an out-of-range selection. Native and compiled events preserve the selected value type and return null for a null index
FormCalc HasValue returns zero for null, empty text, or text containing only ASCII whitespace and Unicode space separators. It reads a field reference through its current value and returns one for numeric zero or text containing a nonblank character
FormCalc Space returns null for a null count and an empty string for zero. Native and compiled events check the configured value-size limit before building the result
FormCalc accepts both the null literal and the zero-argument Null() function in native and compiled events. Both spellings are case-insensitive
FormCalc Len, Upper, Lower, trimming, slicing, At, Replace and Stuff propagate null required inputs in native and compiled events. A null optional replacement or insertion is treated as empty text. Omitting the Substr length selects the remaining text, whilst a null length returns null
FormCalc Oneof compares the current values of ordinary field arguments. When both operands are explicit Ref handles, it compares their node identities, so separate fields with equal values remain distinct
JavaScript current-record synchronisation
xfa.record and $record use fresh configured record boundaries and the explicit active identity, or the current event's containing data context when no active identity is set. Explicit $data paths retain the complete datasets. With fully resident datasets, inserting or removing an earlier record changes the selected record's ordinal without changing its identity; streamed records keep their original source ordinals after deletion
Replacing a record's children with loadXML preserves the record itself. Replacing an event-context ancestor relocates an implicit context by its data path, including across xfa.form.remerge(); replacing an explicit active record does not silently select a different record. Retained live record references and global SOM lookup methods resolve against the current model after remerge
JavaScript record enumeration follows the native rules for mixed content, qualified dataNode overrides and root-qualified startNode paths. A data group with a child named value retains its child accessor during XML hydration
When the built-in QuickJS engine is enabled and the document contains JavaScript lifecycle scripts, flattening uses the complete runtime model for initialisation, calculation, validation and ready processing. Each selected record gets its own model and script session, so calculations can read both the current record and explicit full-dataset paths. A custom JavaScriptEvaluator retains its existing callback contract
Borrowed document rollback and implicit pages
A layout script host created with TXFAWidgetRuntime.CreateLayoutScriptHost borrows its document. Failed full document transactions restore the accepted contents inside that same caller-owned document object, including the selected record, and rebuilding the Form retains that object as its owner. The caller may continue using the host, then free it and continue using the document. Reloaded DOM nodes have new identities, so resolve node references again after rollback
TXFADocument.ExchangeContents exchanges the DOM, packet references, medium session and transient merge/record state of two documents without replacing either document object. It does not exchange subclass-specific state. Passing the same document is a no-op; passing nil raises a diagnostic
Runtime layout without an authored pageSet uses an implicit page model. That model has no fixed master-content source until one is explicitly assigned, so body content is placed once and its captured fragments have one parent. Authored page sets retain their fixed content and content-area placement
Long-format exclusion-group values
In a library-generated Form, when an exclusion group binds a datasets group and its members bind separate child values, the group rawValue reports the selected member's on value. Reading this aggregate does not replace the group's data binding with one member's binding or assign scalar text to the data group
Assigning the group's rawValue selects the matching member and assigns every other member its own configured off value. Clearing the group clears the selection. Assigning a member its on value deselects its siblings. The first and second scalar entries in each member's items provide its on and off values; an omitted off value is empty
JavaScript reads reflect these changes within the same event. Native editing applies the same member-selection rules, and the synchronised Form values and datasets survive save and reload. Failed events restore the preceding accepted state. Flattening preserves the resulting radio selection and identifies a generated Form group within its actual packet
Pascal callers can use HPDFXFAResolveExclusionValue to read the aggregate without treating a data group as a scalar. HPDFXFAResolveLongExclusionGroup identifies the actual group and member data scope, and HPDFXFAExclusionMemberValues reads the member values; these helpers accept operation and deadline limits
Initial data containing several selected members is read deterministically from the first matching member without rewriting that input. This support does not establish every global-binding combination or complete dynamic XFA compatibility
Instance-manager identity and new-instance state
Supported instance-manager remove, move, add and insert operations keep the selected Form instance associated with its data group. Surviving Form-only field state follows that instance, including nested repeated groups after a failed event, save and reload
A retained instance manager can create a new instance after removing its original instance. Retained removed fields cannot write through to a same-name replacement; scripts can catch that error before a native mutation is emitted
For an instance associated with a Template declaration, add and insert use that declaration's current child structure, values, property attributes, presence and access. The association survives insertion or reordering of same-name declarations, save and reload; a missing or ambiguous associated declaration produces a diagnostic rather than selecting a different declaration by its current ordinal
JavaScript and native construction use the same event-start declaration defaults. Editing an existing Form instance does not redefine later instances' Template defaults, while changes to the corresponding current Template through the public document DOM are read at the next event. This does not add a general Template scripting API
A manual Form instance without a trustworthy Template source captures its event-start declaration snapshot on the first successful access to its instance manager. Earlier construction and earlier-event initialisation edits are included; edits made earlier in that same event do not redefine the snapshot. The accepted snapshot persists through save, reload and rollback and supplies later add and insert defaults
Current manager occurrence limits remain separate from declaration defaults. A script can change its live occur limits before adding an instance in the same event; an absent max uses the effective min. A field or subform with bind.match = "none" remains Form-only rather than creating a datasets value merely because it is added
A caller Form packet without library-authoritative structure metadata is prepared as an overlay. Supplied ordinary siblings retain their relative order; matched declarations supply missing properties and defaults, and omitted Template siblings are inserted at stable Template-relative positions. Already-authoritative Form structure is retained. An omitted node is not interpreted as an explicit deletion, and this policy does not claim universal complete-Form serialisation support
Prepared caller Form subforms with bind match="none" inherit their parent data context. Transparent scope="none" subforms also inherit it unless they use explicit dataRef binding. Ordinary and master-page layout preserve the resolved context instead of selecting a same-name child group again. Accepted automatic Form scope metadata remains authoritative
HPDFXFAResolveActualFormScope accepts an optional final ScopeResolved argument, which defaults to False. Pass True after applying a scope callback or resolving an explicit binding. An explicit nil then remains empty instead of being restored from automatic binding metadata. A resolved dataRef target is not searched again by the subform name; unresolved references are resolved from their parent scope within the operation budget. Existing nonempty automatic scope metadata retains its precedence
Layout carries resolved scope state through measurement and placement so relative references are not consumed repeatedly. Runtime event bindings, Form SOM lookup, lifecycle traversal and value synchronisation use the same distinction between a parent context, an explicit target and an empty callback result
TXFAInstancePresentation uses a final-target resolver for explicit container references while its instance-editing operations retain their parent-group resolver. Caller Form widgets therefore read and update the selected target rather than its parent. Raw Template layout, including documents with an empty Form packet, expands terminal [*] references consistently in tables and ordinary flow, applies occurrence limits, and reserves the combined height before following fields
Master-page fields share their actual owning Form record across initial scalar synchronisation, layout, native widgets and event reads. Broader binding, lifecycle and dynamic XFA semantics remain separate work
Master-page binding context
Supported named-subform and dataRef bindings below pageSet and pageArea use the actual owning Form record. Nested repeated subforms are materialised once for their bound data groups; repeating a page master on another physical page copies the presentation while retaining the same actual Form and data associations
Master content participates in initialize, ready with ref="$form", and ready with ref="$layout". Lifecycle traversal follows the Form tree through page sets, page areas and content areas, using the master owner's accepted data scope. Physical copies on additional pages do not create additional initialisation events for the same actual Form instance. An uncaught master handler exception restores the lifecycle transaction, including earlier body changes, and a retry can run the rolled-back initialiser again
Fresh scalar fields initialise from their bound data after actual instance associations are established. Existing Form values, explicit bind-none defaults and caller property overrides are retained. Saving, reloading and transactional remerge use the same binding policy, and a failed event restores the accepted Form, data and widget state together
Explicit dataRef selectors retain their selected target. A manual or partial Form without automatic binding metadata keeps the existing top-level current-record rule, independently of the authored root subform name
Explicit Form remerge
function Remerge: Boolean;
TXFAWidgetRuntime.Remerge explicitly rebuilds Form from the current Template and datasets, including supported repeated-instance binding, then rebuilds native widgets and layout. It returns False and sets LastDiagnostic when the transaction fails
Reconstruction removes Form-only inserted nodes, property changes and explicit deletion state from the previous model, restoring the authored model from the current Template. Current datasets remain the binding source, and lifecycle scripts retain their normal ability to update values
In an enabled native JavaScript event, xfa.form.remerge() completes reconstruction and its lifecycle at the call position and returns undefined. Following statements in that event can resolve the fresh Form and observe its current values and geometry
Initialisation, calculation, validation, form-ready and layout-ready processing use the existing lifecycle and resource limits. An uncaught reconstruction, lifecycle or script failure restores the pre-transaction document, datasets, Form, retained script state, focus and edit state
The snapshot taken before such a transaction now carries its own retained-memory charge: the focus state, the layout and widget snapshot arrays, the input-source proof and the recovery graphs are each charged against the family budget before they are allocated, and every charge is released when the snapshot is discarded or the restore completes
Fresh Form nodes have independent identities. A retained reference to an old Form node remains detached or becomes stale; it never redirects to a same-name replacement or writes through to that replacement's bound data. Resolve nodes again after the call before editing the rebuilt model
Retained script identity aliases collapse to their final target when a binding is rebound across remerges, so a saved identity string resolves within one alias hop no matter how many remerge generations separate it from the current model. Repeatedly remerging inside one event accumulates responses quadratically; exceeding the engine memory budget fails the transaction with a diagnostic that names the opaque engine failure instead of a bare error
Version 2.1143.0 adds optional compact native alias Map backing for consecutive hexadecimal identities sharing string targets. Native Map behaviour and general key/value support remain intact through atomic promotion, with no increase to the existing VM or journal budgets. This reduces retained alias storage without removing live-history execution or retained public payloads
Each successful remerge transaction releases the retired generation's script node objects, so the JavaScript node arrays stay bounded no matter how many remerges a session performs. A handle retained across that release keeps the remerge diagnostic through the identity tombstones; since 2.1135.0, a bridge with the optional registry export stores canonical membership in an exact session-owned disk index charged to the existing journal limit, while other values retain the original Set
SaveToBytes persists the accepted Form and datasets for a fresh Runtime or the existing native PDF consumer. Ordinary UpdateDocument and automatic reconciliation retain their incremental behaviour, including surviving manual Form edits, rather than implicitly requesting this reset
This operation does not introduce a general Template scripting API or establish complete dynamic XFA support
Dynamic bookend, keep, margin and overflow properties
In an enabled Runtime JavaScript event, owner.getElement("bookend", 0) creates the missing optional bookend under a subform or subformSet and returns the existing node on later access. A subform also admits one optional keep, one optional margin and one optional overflow; subformSet does not admit keep, margin or overflow, and requesting a duplicate property occurrence remains subject to the schema limit
const owner = this.parent;
const opening = owner.getElement("bookend", 0);
opening.leader = "#Open_ID";
opening.trailer = "";
const adhesion = owner.getElement("keep", 0);
adhesion.intact = "none";
This example requires a subform owner and a valid positioned source named by #Open_ID. Ordinary access through owner.bookend or owner.keep and direct attribute setters reach the same native property state; later events update the existing node rather than adding another occurrence
Bookend leader and trailer references default to empty, while keep next and previous default to none; id, use and usehref retain their empty defaults. An unassigned intact is read from the owner's current class and layout: positioned or row subforms and draws use contentArea, while flowing or table subforms and fields use none
A scripted margin supplies the four content insets: absent attributes default to zero as in templates, and the effective insets shift the flow origin and shrink the inheritable content width of tb, lr-tb and row containers during native reflow, including row replay. A scripted overflow exposes target, leader and trailer with empty defaults: the target routes overflowing flowed rows into the named contentArea or pageArea during native reflow and reservation, leader and trailer admit the same decoration lists as templates, an explicitly empty attribute masks the value inherited from an ancestor, and resolution keeps the declaring owner's own data context
Changing a subform's layout during the same event changes its unassigned intact getter without asserting that attribute. An explicitly assigned intact remains authoritative after later layout changes
For a partial Form keep whose owner has no layout attribute, the native default reader inherits the template owner's layout only when structural matching identifies that owner unambiguously. Materialized Form state and an explicitly present layout, including an empty value, remain authoritative. If multiple repeated same-name declarations prevent a unique match, the Form owner's own default remains in effect; this is not a general reverse mapping from Form nodes to template definitions
A set-owned bookend remains attached to that actual subformSet instance with its logical children and data context. Transparent sets share their parent's TB or lr-tb flow cursor, so their child subforms contribute their real occupied extents and can share lines with surrounding siblings; ordinary subforms retain their own layout and positional boundaries
Addressing one repeated instance does not change another instance's properties. Successful assignments persist through SaveToBytes and a fresh Runtime reload, and a bookend saved in a partial Form produces real presentations even when its template owner has no bookend property
Creation, assignment and subsequent layout participate in the existing event transaction. A failed event restores the prior saved properties and values together with the addressed focus and edit state. Runtime reflow applies the shared keep and intact layout contract to the actual addressed instances, including transparent-set siblings and adjoining split fragments; mandatory movement and impossible-chain overflow retain that contract's explicit compatibility policy. Broader property and dynamic XFA support remains outside this profile
Minimum height for growable content
When a text measurement callback returns zero height for empty content, growable TB, LR-TB and table-cell layout applies minH and maxH before deciding whether the final height is usable. An empty field with a positive minimum therefore retains its allocated height and moves following content accordingly. Empty content without a positive final height consumes no tile width or line height and does not split neighbouring LR-TB tiles onto separate lines
Native JavaScript bridge
bash tools/Build-HotPDFQuickJSLinux.sh /var/tmp/hotpdf-native
export HOTPDF_QUICKJS_DLL=/var/tmp/hotpdf-native/libhpdfquickjs.so
export HOTPDF_SUPPRESS_AUTO_LAUNCH=1
The Linux bridge builds from the bundled QuickJS sources with GCC-compatible compilation and uses the same versioned HPDFQJS ABI as the Windows DLL
QuickJSDLLPath and HOTPDF_QUICKJS_DLL accept an explicit shared-library path on Linux; the existing API names are preserved for source compatibility
Default discovery checks libhpdfquickjs.so next to the executable and Lib/thirdparty/QuickJS/bin/Linux64 in executable ancestor directories
Each session owns a reference to its exact loaded module until its native engine, contexts and callbacks have been released; sessions retain independent script state and journals
Native monotonic clocks enforce the existing event, XML and layout budgets; deterministic epoch values, random responses and external transport responses remain recorded and replayed transactionally
Conditional layout scripts
Runtime layout and native flattening evaluate nonempty breakBefore and breakAfter scripts in the actual enclosing subform and repeated data instance, including initial target selection
Startup conditions on the root subform and the promoted first content subform use the same resolved Form data scope as the walk-level condition at that node, so an explicit bind match="dataRef" target reaches the script instead of a same-name decoy data node
An absent or empty script is unconditional; an omitted or empty contentType selects FormCalc. Raw JavaScript remains controlled by ScriptOptions.EnableJavaScript, while FormCalc retains native expression evaluation and can use the configured bridge for compiled event statements without enabling raw JavaScript
The script's language supplies its Boolean conversion and final expression value. False suppresses page movement without discarding otherwise successful effects, and auto or omitted targetType does not suppress execution
A real layout request begins a condition cycle; internal width planning, terminal replay and mutation restarts reuse stable instance decisions. Successful restart refreshes the structural trace used by snapshot restoration, so restoring an unsuccessful edit does not execute its conditions again
Script failures propagate through the existing edit transaction, preserving the previous saved values, script checkpoint and completed page snapshot. Successful later reflow evaluates a new cycle and publishes the resulting page associations, numbering and sizes together
Page queries inside a condition use the last completed layout snapshot, as they do in other runtime events; they do not force synchronous relayout. Native SOM pagination routing uses actual owner/data context and accepted predicate decisions across internal replay, while medium resolution retains its separate fixed-session contract; broader dynamic XFA remains active work
Generated break-decoration presentations
Modern break leaders and trailers use the asserting instance and the reference's resolved data policy, with condition, trailer, route and leader processing shared by runtime layout and native flattening
Bookend presentations use those same actual owner/data and virtual insertion contexts, with one leader at owner entry and one trailer at final body completion. Their interaction identities remain distinct from break and overflow presentations even when owner, target, data and phase otherwise coincide; source values stay shared, and the existing custom identity resolver, focus/edit and rollback contracts continue to apply
Repeated presentations of the same source field have distinct interaction identities, including more than one copy on a page, without inventing separate form or dataset values. The optional ResolveWidgetIdentity callback still supplies the source identity; generated-copy discrimination preserves the addressed presentation
For a surviving generated presentation, focus and uncommitted edit buffers belong to that addressed copy through successful reflow and transaction rollback. A committed value updates the original shared form value, and the other presentations and a fresh reload consume that same stored value; an edit buffer is not copied into another presentation merely because their source node and data instance match
absPage continues to identify the source object's first actual physical association, while the focused presentation has its own widget page and bounds. Generated queryable containers and leaves use real placements, and completed page associations, numbering and sizes retain the existing atomic publication and recovery contract
Native structural SOM and supported literal property filters resolve decoration references without a bridge; computed predicates retain the existing script configuration and transaction limits. Overflow decorations additionally share presentation maxima within each asserting-instance pool, preserve inherited pool consumption and select ordered fallback targets; unused reservations and rejected internal trials do not spend occurrences. These rules do not establish every SOM construct, event or dynamic XFA workflow
Layout completion state
xfa.layout.ready is a read-only Boolean available in JavaScript and compiled FormCalc events, with each read charged to the script operation budget
Ordinary runtime events observe a completed layout and return true; scripts evaluated while a conditional layout pass is in progress return false, including a nested remerge while the outer layout pass remains active
The property follows the current script context's snapshot boundary, like the existing page queries; it does not force synchronous layout after an assignment or infer completion from the event name or page count
Same-event xfa.form.remerge() installs fresh layout state with the context's completion state. A retained public xfa.layout facade follows the current layout when properties are read; a method saved before the change retains its completed-query snapshot
Assignments cannot change the value; JavaScript strict-mode assignment or attempts to redefine the non-configurable property fail through the existing event transaction
Direct HPDFXFAExecuteJavaScriptEvent callers can supply the optional LayoutReady argument, whose default is True
Physical page queries
xfa.layout.absPage(node) returns the zero-based first physical page containing a laid-out form object, and xfa.layout.absPageCount() returns the physical page count of the current layout
Both JavaScript and compiled FormCalc events use the runtime's actual pagination snapshot, with separate identities for repeated instances; layout:ready observes the rebuilt layout, and later successful reflow refreshes the queries
Supported form objects include fields, draws, subforms, areas, page areas and content areas; a hidden parent subform removes its descendants from layout, while a hidden field in a laid-out visible parent can retain a page association
A valid runtime node without a layout association returns -1; a value that is not a runtime node returns 0, and absPage requires exactly one argument
Page associations and page count participate in transaction rollback, so an unsuccessful event does not publish a partial layout; these queries report the current completed layout rather than forcing an immediate layout inside the calling script
Physical page queries are separate from logical page numbering and do not establish support for every page-master or dynamic XFA layout construction
Page content from the completed layout
xfa.layout.pageContent(page, type, onPageArea)
pageContent returns a NodeList with length and item(index) for a zero-based physical page. It reads the last completed layout, independently of logical page numbers and their initialNumber; an ordinary event does not force a new layout merely by calling this query
The optional type filter accepts field, draw, subform, area, pageArea or contentArea. An omitted or empty filter selects all eligible laid-out containers. The optional onPageArea flag defaults to true, selecting master-page content; false selects body content. Type and master/body filters apply together, with pageArea and contentArea on the master side
const fields = xfa.layout.pageContent(0, "field", false);
if (fields.length > 0) {
fields.item(0).access = "readOnly";
}
Results are actual Form objects that support the existing property and event operations, rather than copies of their geometry. Cross-page continuations remain associated with each page they occupy, repeated master content is queryable on every realised page, and generated break, bookend and overflow presentations retain their distinct script identities while sharing their source values
Page-model discovery follows current materialised Form containers, including unnamed pageSet, pageArea and contentArea ancestors and page sets cloned into a different Form parent. Following events query those current Form objects through the completed layout bindings
HotPDF returns a given script identity at most once within one page query; distinct generated-presentation identities remain separate results. Hidden and inactive content is excluded, while invisible content with a real layout placement remains eligible. The unfiltered result also includes laid-out exclGroup containers, and excludes form, pageSet, proto, transparent subformSet and property nodes
The following parameter rules are HotPDF behaviour where the Adobe method reference leaves details unspecified: calls require one to three arguments or throw TypeError; the page is converted with Number and must be a finite safe integer or throw TypeError. Negative and out-of-range integers return an empty NodeList. An omitted or undefined type becomes the empty string; other type values are converted with String, and an unknown filter returns an empty NodeList. An omitted or undefined flag becomes true; other flag values use Boolean conversion
Each call selects membership from the completed snapshot rather than exposing a live recalculation view. Previously committed members are omitted if their node, required data scope or generated-presentation path no longer resolves in the current document; a deleted member does not redirect to a same-name replacement
When a complete materialised Form replaces Template identities, old Template associations are omitted during reconstruction, including generated presentation owners and targets; they are not reassigned to the new Form before its layout completes. A sparse Form with only descendant materialisation markers retains its existing Template fallback
Successful reflow publishes page membership with the other completed layout queries, and transaction rollback restores the preceding snapshot. Synchronous Form remerge provides fresh Form objects and page membership when it returns; retained pre-remerge Form handles keep the existing detached-or-stale behaviour and do not redirect to replacement nodes
The documented parameter defaults and container filters follow the Adobe pageContent reference; HotPDF's validation, filtering and identity rules above do not claim an Adobe-defined collection order or invalid-input policy. Page-span queries use the related completed association snapshot; broader layout queries and general dynamic XFA remain separate work
Geometry from completed layout fragments
xfa.layout.x(node, unit, index)
xfa.layout.y(node, unit, index)
xfa.layout.w(node, unit, index)
xfa.layout.h(node, unit, index)
JavaScript and compiled FormCalc events read the accepted layout fragment for a field, draw, subform, area, pageArea or contentArea. X and Y are relative to the fragment's geometric parent; W and H describe the fragment's allocated dimensions, including explicit container space that contains no field or draw
The optional unit defaults to pt; in, cm, mm and pc are also supported, and an empty string selects points. The optional zero-based index defaults to zero and selects an object's accepted fragments in layout order, including distinct content-area fragments on the same physical page
Each call requires one to three arguments. HotPDF converts units with String and indices with Number; unsupported units, unrecognized objects, unsupported object classes, negative indices, fractions and non-finite or unsafe integer indices throw TypeError. A genuine supported object without a fragment, an out-of-range index or a retired object returns zero
A fragment index counts actual occurrences rather than deduplicated page membership. Generated presentations retain separate script identities, and fixed master content has an occurrence for each realised physical page
Queries use the completed snapshot and do not trigger layout inside an ordinary event. Successful reflow publishes all geometry together; synchronous Form remerge refreshes replacement Form objects before execution resumes, and failed event transactions restore the preceding geometry snapshot
A previously saved geometry method uses its captured coordinate snapshot, while a method read later from a retained public layout facade uses the current snapshot. Removed or retired nodes cannot borrow old geometry or redirect to same-name replacements. Page-index queries retain their existing combination of the node's current page association and the saved page-count and numbering vectors
Native callers can enable TXFALayoutEngine.CaptureFragments before layout and enumerate LayoutFragmentCount with TryGetLayoutFragment. Records contain absolute and parent-relative rectangles in PDF points, physical page and content-area identities, source provenance and a parent fragment index; parent records precede their children
A geometric parent belongs to the same physical page as its child. When a positioned child overflows onto a page where its explicit source parent has no allocated fragment, its geometry uses the nearest realised ancestor or the actual page/content-area context. Source ancestry remains available separately; an empty parent rectangle is not invented for the overflowing child
Fragment capture also enables placement capture and shares its bounded storage. Returned presentation arrays are copied, while node references remain owned by the source document; copy or resolve those identities before replacing or freeing that document
Physical and logical page spans
xfa.layout.absPageSpan(node)
xfa.layout.pageSpan(node)
JavaScript and compiled FormCalc events query accepted page associations for the addressed Form object. The supported classes are field, draw, subform, area, pageArea and contentArea; repeated data instances and distinct generated presentations retain their own identities
HotPDF defines absPageSpan as the inclusive physical interval from the object's first accepted page through its last accepted page. A blank page between those endpoints contributes to the span even when the object has no content on that intermediate page. An unrelated leading or trailing page does not extend the interval without an accepted association
pageSpan counts numbered pages within that same physical interval, including numbered intermediate pages and excluding unnumbered pages. An interval containing only unnumbered pages returns 0. The result does not depend on initialNumber or displayed page labels and is not computed by subtracting the first label from the last
The association snapshot includes actual split fragments, accepted empty-container positions and every realised occurrence of repeated master content. It is separate from pageContent's visibility-filtered membership, so a hidden field with an existing association in a visible parent can have a span without appearing in pageContent. A hidden parent does not create descendant associations
Each method requires exactly one argument or throws TypeError. A value that is not a genuine supported runtime node, a node without an accepted layout association, or an identity that no longer resolves in the current document returns 0; valid spans are never negative. A retired handle is not redirected to a same-name replacement
These methods read the completed layout rather than forcing synchronous layout during an ordinary event. Successful reflow publishes associations and numbered-page state together; failed transactions restore both. Synchronous Form remerge refreshes the fresh Form's queries before the calling script resumes
The Adobe pageSpan reference describes a covered interval rather than an occupied-page count. HotPDF's physical interval, numbered-page counting, validation and zero-result policies above make unspecified cases explicit; they do not claim to reproduce every Adobe behaviour for missing objects or page-numbering configurations. Broader dynamic XFA remains separate scope
Logical page numbering
xfa.layout.page(node) returns the logical number of the first physical page associated with the runtime node, using the selected page area's initialNumber, whose default is 1; it is not necessarily the physical index plus one
A node or value that cannot be associated with a laid-out page returns 0; a hidden field with an existing page association in a visible parent remains queryable, while a hidden parent subform removes its descendants' layout associations
xfa.layout.pageCount() counts numbered pages, whereas xfa.layout.absPageCount() counts physical pages including unnumbered pages; absPage retains its existing zero-based index and missing-layout return rules
Logical numbering follows the actual selected page master on each physical page; the first physical page supplies initialNumber, and later numbered pages advance the current number and contribute to pageCount
Missing numbered, numbered="1" and numbered="auto" include the page in numbering; numbered="0" and numbered="none" retain the current logical number and exclude the page from pageCount
JavaScript and compiled FormCalc use the same completed layout snapshot; successful reflow updates logical numbering together with physical page associations, and transaction rollback restores both the numbering vector and numbered-page count
These queries do not force synchronous layout inside the calling script; ordered page-master selection and qualified simplex/duplex selection supply their committed physical layout, including terminal replay and background-only pages. Duplex side qualification uses physical surfaces rather than logical numbering, and broader lifecycle and dynamic XFA behaviour remain separate capabilities
Physical page sizes
TXFAWidgetRuntime.TryGetPageSize(PageIndex, Width, Height) returns the completed layout's actual physical width and height in PDF points for a zero-based page index; it returns False with both outputs zero when the index is unavailable
The sizes follow the same selected-master sequence as widgets, page queries and logical numbering, including retained empty pages; successful reflow publishes the new size vector with that layout snapshot, and transaction rollback restores its previous values
Per-master media output consumes these physical dimensions separately from content-area origins and logical page numbers
Linux locales
The native Linux locale backend reads system ICU calendar names, decimal and grouping symbols, currency symbols and codes, AM/PM markers, and number/date/time patterns
Named locales use fully parsed BCP47 identifiers and known ICU language data; underscore separators are canonicalized, and unsupported languages or malformed identifiers return False
An empty name selects ICU's configured default locale; document localeSet definitions and explicit application locale providers retain their existing priority
Both libicuuc and libicui18n are required; the loader resolves matching ICU export versions, including versioned runtime libraries without development symlinks
ICU and Windows may provide different regional patterns and whitespace based on their installed locale data; explicit document locale definitions can select deterministic application formatting
Persistence and PDF consumers
SaveToBytes persists the native XDP, including Data DOM imports, per-instance values, namespace mappings, comments and processing instructions, with the same rollback behaviour on both platforms
A Linux saved-XDP consumer fixture reloads TXFAWidgetRuntime and applies its actual values through THPDFHeadlessDocument field setters and native appearance generation
That fixture uses an independently prepared PDF field template; automatic native XFA PDF creation also creates fresh pages, supported fields and appearances directly from XDP on Windows and Linux through HPDFXFAWriteHeadlessPDF, without prepared field slots
The automatic adapter has a bounded field and draw profile; complete dynamic XFA integration, additional consumers and interactive rendering remain active work