# HomuraJS: The Directed Acyclic Graph (DAG) State & History Engine for JavaScript > Full Technical Specification, Architecture, Ecosystem Guides, WordPress & Zero-JS Integrations, and API Reference. > Engineered by Biagio Scaglia & the HomuraJS Core Team. > Version: 1.5.1 (production-hardened) > Documentation: https://biagio-scaglia.github.io/homura-js/ > Source Repository: https://github.com/biagio-scaglia/homura-js > Package Registry: https://www.npmjs.com/package/@biagioscaglia/homurajs --- ## 1. Executive Summary & Core Philosophy HomuraJS is an advanced, framework-agnostic state management and history engine designed to solve the fundamental flaw of traditional undo/redo implementations: **the destructive linear stack problem**. In conventional state libraries (e.g., Redux-Undo, simple undo arrays, browser history), history is modeled as a 1D linear array with a single active pointer. When a user steps back $N$ times and performs a new mutation, all future steps ahead of the pointer are permanently deleted. HomuraJS models application history as a **Directed Acyclic Graph (DAG)** of immutable state snapshots: - Every mutation creates a new node in the graph with parent and child links. - Rewinding to an earlier state and applying a change creates an **alternative timeline branch** without erasing any existing timeline. - Branches can be switched, compared, inspected, and merged via 3-way or fast-forward reconciliation. - Published snapshots are **deep-frozen**; accidental mutation of `getState()` throws instead of corrupting history. - `update(..., { silent: true })` applies in-place without a history node; `setStateAsync` awaits Promise middleware. - Memory usage is minimized using **Copy-On-Write structural sharing** via JavaScript Proxies. --- ## 2. Monorepo Package Anatomy HomuraJS is structured as a high-performance monorepo: ### `@homura-js/core` (< 5.2 kB gzipped) The zero-dependency core engine: - Graph node registry and DAG traversal algorithms (ancestors, descendants, branch heads). - Copy-On-Write draft proxy engine for intuitive mutable syntax (`update(draft => { draft.x = 1; })`). - Deep-frozen published snapshots (`deepFreeze`); draft creation is safe against frozen bases. - Silent updates (`silent: true`) and async middleware via `setStateAsync` / `MiddlewarePipeline.runAsync`. - Deep recursive structural diff engine (`diff(nodeA, nodeB)`); array removals apply high→low indexes. - Snapshot registry and milestone bookmarking. - Persistence adapters (LocalStorage, SessionStorage, IndexedDB, Custom); persistence errors rethrow (auto-save catches locally). - Event emitter (`state:change`, `node:add`, `branch:create`, `branch:switch`, `branch:merge`, `undo`, `redo`); cancelled transactions do not emit `transaction:commit`. - History compaction and topology-safe prune (`compact()`, `prune()`). - Step-by-step automated timeline playback (`replay()`). - Fast-forward and manual merge with required resolver when conflicts exist. ### `@homura-js/devtools` (< 9.4 kB gzipped) Standalone diagnostic UI and scrubber: - Interactive visual DAG timeline graph with zoom, pan, branch tags, and jump-to-node. - Real-time collapsible JSON state inspector. - Side-by-side recursive structural diff viewer with color-coded additions, deletions, and modifications. - Step-by-step timeline playback controls with speed multiplier (1x, 2x, 5x, 10x). - Floating and embedded mounting modes (`mountDevTools()`). ### `@homura-js/vanilla` (< 2.8 kB gzipped) Framework-free reactive DOM and form crash recovery: - `bindState(homura, targets)`: One-way reactive DOM binding without virtual DOM. - `bindForm(formElement, options)`: Form crash protection controller with undo/redo, smart recovery banner, and integrity verification. - `autoInitForms()`: Auto-discovers and initializes all declarative `[data-homura-form]` elements. - Utility functions: `extractFormData(form)`, `populateFormData(form, state)`, `isFieldSensitive(el)`, `maskPIIValue(key, val)`. - Smart Recovery: Visual state diff between DOM and saved drafts (`getDiffFromDom()`). - Sensitive Field Policy: Auto-filters passwords, CVVs, nonces, and `data-homura-sensitive="true"`. - AJAX Conflict Protection: `verifyIntegrityAndRestore()` detects and repairs fields wiped by asynchronous updates. - Handles multi-step form wizards (`data-homura-step`, `data-homura-next`, `data-homura-prev`). ### `@homura-js/react` (< 2.1 kB gzipped) React 18+ bindings: - `useHomura(store, selector?, equalityFn?)` hook powered by React 18's `useSyncExternalStore`. - Fine-grained selector optimization preventing unnecessary component re-renders. - Provides `state`, `update`, `undo`, `redo`, `canUndo`, `canRedo`, `createBranch`, `switchBranch`. ### `@homura-js/vue` (< 2.3 kB gzipped) Vue 3 Composition API bindings: - `useHomura(store)` hook returning shallow reactive state and time-travel controls. - Vue plugin wrapper for global store injection. ### `@biagioscaglia/homurajs` (Meta-Package & CDN) - Unified package exporting all modules. - CDN standalone browser bundle (`dist/index.global.js`) for static HTML, WordPress, Shopify, Squarespace, and Webflow. --- ## 3. WordPress & WooCommerce Integration (Deep Dive) HomuraJS provides an official WordPress plugin (`homura-time-travel-form-recovery`) designed for high-conversion sites, lead generation, and checkout crash protection. ### Key Capabilities in WordPress: 1. **Crash Recovery for Forms**: Automatically saves user input to browser LocalStorage as a local DAG state tree. If a customer accidentally closes a tab or experiences a page refresh, their data is instantly restored. 2. **Shortcodes for Page Builders & Themes**: - `[homura_form id="contact_quote" persist="localstorage"] ... [/homura_form]` - `[homura_undo form="contact_quote" label="Undo"]` - `[homura_redo form="contact_quote" label="Redo"]` - `[homura_status form="contact_quote"]` - `[homura_breadcrumbs form="contact_quote"]` 3. **Auto-Hooks for Popular WordPress Form & E-Commerce Plugins**: - **WooCommerce Checkout**: Auto-attaches to `.woocommerce-checkout` to protect customer shipping, billing, and order notes from accidental checkout abandonment. - **Contact Form 7**: Auto-attaches to `.wpcf7 form`. - **WPForms**: Auto-attaches to `.wpforms-form`. - **Gravity Forms**: Auto-attaches to `.gform_wrapper form`. - **Elementor Forms**: Auto-attaches to `.elementor-form`. 4. **Privacy & GDPR Compliance**: - 100% client-side operation. - Zero telemetry, zero external tracking, and zero remote script execution. - Data stored exclusively in the visitor's local browser sandbox. --- ## 4. Zero-JS Declarative HTML API (Static Sites & Headless CMS) Any static website (Webflow, Squarespace, Shopify, Astro, Hugo, 11ty, Plain HTML) can use HomuraJS without writing JavaScript: ### Single Form Crash Recovery & Time-Travel ```html
``` ### Multi-Step Questionnaire Wizard ```html ``` --- ## 5. WordPress & WooCommerce Plugin Integration (v1.5.1) Official WordPress.org Plugin: `homura-time-travel-form-recovery` (https://wordpress.org/plugins/homura-time-travel-form-recovery/) ### Capabilities & Architecture: - **Zero-Data-Loss Form Protection**: Real-time client-side DAG state tracking in LocalStorage / SessionStorage. - **Real QR Mobile Handoff**: Scannable QR via `uqr`; oversized tokens fall back to copy-link UX (`[homura_handoff]`). - **Ghost Assist & AES-GCM Vault**: Sensory mass-delete recovery and optional WebCrypto encryption. - **WooCommerce AJAX Conflict Recovery**: Restores fields wiped by `update_order_review` / cart recalculation; destroy cleans MutationObservers and jQuery hooks. - **State Diff Engine (`[homura_diff]`)**: Visual modal comparison between current form DOM values and saved drafts. - **Smart Recovery Banner (`[homura_recovery_banner]`)**: Interactive prompt allowing visitors to restore drafts, inspect differences, or dismiss previous sessions. - **Sensitive Field Policy**: Strict exclusion of passwords, CVVs, credit card numbers, payment nonces, and inputs tagged with `data-homura-sensitive="true"` or `data-homura-persist="false"` (GDPR and PCI-DSS compliant). - **Form Schema Versioning**: Prevents corruption when forms are updated or fields are modified by site administrators. - **PII-Masked Debug Export (`[homura_debug_export]`)**: Sanitized JSON diagnostic payload for troubleshooting. ### Complete Shortcodes: - `[homura_form id="form_id" persist="localstorage" debounce="200" smart_recovery="true"]...[/homura_form]` - `[homura_undo form="form_id" label="↩ Undo"]` - `[homura_redo form="form_id" label="↪ Redo"]` - `[homura_status form="form_id"]` - `[homura_breadcrumbs form="form_id"]` - `[homura_recovery_banner form="form_id"]` - `[homura_diff form="form_id" label="🔍 View Changes"]` - `[homura_handoff form="form_id"]` - `[homura_ghost_assist form="form_id"]` - `[homura_visual_diff form="form_id"]` - `[homura_clear form="form_id" label="🗑️ Clear Draft"]` - `[homura_reset form="form_id" label="🗑️ Reset"]` - `[homura_debug_export form="form_id" label="🛠️ Export Debug JSON"]` - `[homura_wizard id="wizard_id" persist="localstorage"]` ### Auto-Hooked Form Engines: WooCommerce Checkout (`.woocommerce-checkout`), Contact Form 7 (`.wpcf7 form`), WPForms (`.wpforms-form`), Gravity Forms (`.gform_wrapper`), Elementor Forms (`.elementor-form`), Fluent Forms (`.fluentform`), Ninja Forms (`.nf-form-content form`), Formidable Forms (`.frm-show-form`), and WS Form (`.wsf-form`). --- ## 6. TypeScript / JavaScript API Reference ### Core Type Definitions ```ts export interface HistoryEntry