@jqhtml/core 2.3.70 → 2.3.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -214,12 +214,17 @@ class LifecycleManager {
214
214
  return LifecycleManager.instance;
215
215
  }
216
216
  constructor() {
217
- this.active_components = new Set();
218
- // No automatic cleanup on DOM removal - components stop explicitly via:
219
- // 1. Parent component re-render (calls .empty() which stops children)
220
- // 2. Manual .empty(), .html(), .text() calls (overridden to stop children)
217
+ // Components stop explicitly via:
218
+ // 1. Parent component re-render (stops descendants before clearing innerHTML)
219
+ // 2. Any jQuery removal that reaches jQuery.cleanData (.remove(), .empty(),
220
+ // .html(x), .text(x), .replaceWith(), .replaceAll()) - hooked in jquery-plugin.ts
221
221
  // 3. Explicit .stop() call
222
- // This allows components to be moved in DOM without lifecycle interruption
222
+ // Native DOM removal is NOT observed for stop; 'detach' (dom-attachment.ts) is the
223
+ // signal for that. Moving a component within the document never stops it.
224
+ //
225
+ // There is deliberately no registry of live components here. The DOM (via
226
+ // element.data('_component')) is the only owner; a registry would pin every
227
+ // component that left the document without being stopped.
223
228
  }
224
229
  /**
225
230
  * Boot a component - run its full lifecycle
@@ -230,7 +235,6 @@ class LifecycleManager {
230
235
  * - _load_render_only: on_create + render + on_load + re-render. No on_render, no on_loaded, no on_ready.
231
236
  */
232
237
  async boot_component(component) {
233
- this.active_components.add(component);
234
238
  try {
235
239
  // Create phase - SYNCHRONOUS, runs BEFORE first render
236
240
  component.create();
@@ -391,12 +395,6 @@ class LifecycleManager {
391
395
  }
392
396
  }
393
397
  }
394
- /**
395
- * Unregister a component (called on destroy)
396
- */
397
- unregister_component(component) {
398
- this.active_components.delete(component);
399
- }
400
398
  }
401
399
 
402
400
  /**
@@ -1506,760 +1504,509 @@ function serialize_for_cache_key(value) {
1506
1504
  }
1507
1505
 
1508
1506
  /**
1509
- * Load Coordinator - Request deduplication for component on_load() calls
1507
+ * Jqhtml_Local_Storage - Scoped local storage for JQHTML component caching
1510
1508
  *
1511
- * Coordinates parallel component loading to prevent duplicate requests.
1512
- * When multiple components with identical names and args load simultaneously,
1513
- * only the first (leader) executes on_load(). Others (followers) wait for
1514
- * the leader's result.
1509
+ * Provides safe, scoped access to localStorage with automatic handling of
1510
+ * unavailable storage, quota exceeded errors, and scope invalidation.
1515
1511
  *
1516
- * Key Concepts:
1517
- * - **INVOCATION_KEY**: Unique identifier for component name + args combination
1518
- * - **Leader**: First component to reach on_load() for a given INVOCATION_KEY
1519
- * - **Follower**: Subsequent components that wait for leader's result
1512
+ * Key Features:
1513
+ * - **Manual scoping**: Cache key must be set via set_cache_key() before use
1514
+ * - **Graceful degradation**: Returns null when storage unavailable or cache key not set
1515
+ * - **Quota management**: Auto-clears storage when full and retries operation
1516
+ * - **Scope validation**: Clears storage when cache key changes
1517
+ * - **Developer-friendly keys**: Scoped suffix allows easy inspection in dev tools
1518
+ * - **Class-aware serialization**: ES6 class instances serialize and restore properly
1520
1519
  *
1521
- * Lifecycle:
1522
- * 1. Leader reaches on_load() → create coordination entry
1523
- * 2. Followers reach on_load() → join waiting queue
1524
- * 3. Leader completes → distribute data to all followers
1525
- * 4. Clear coordination entry (no caching)
1520
+ * Class-Aware Serialization:
1521
+ * ES6 class instances can be serialized and deserialized if registered via
1522
+ * register_cache_class(). Classes are wrapped as {__jqhtml_class__: "Name", __jqhtml_props__: {...}}
1523
+ * and restored to proper instances on retrieval. Nested class instances in objects
1524
+ * and arrays are handled recursively. A class whose wire form is not its own
1525
+ * properties (one that defines toJSON(), or keeps state in private fields)
1526
+ * registers a {to_plain, from_plain} pair and is rebuilt through it. Date, Map and
1527
+ * Set are pre-registered the same way - there is no second mechanism.
1528
+ *
1529
+ * ONE SERIALIZER. Every copy of on_load() data the framework makes goes through
1530
+ * this file: the localStorage cache (set()/get()), the normalization of every
1531
+ * on_load() result into this.data (normalize_for_cache()), and the copy a
1532
+ * deduplicated follower takes of its leader's data (serialize()/deserialize(),
1533
+ * used by load-coordinator.ts). Anything that survives one of those survives all
1534
+ * of them, and anything dropped is dropped identically on all of them. A plain
1535
+ * JSON.stringify anywhere on those paths would consult toJSON() and hand out a
1536
+ * wire form nothing knows how to restore.
1537
+ *
1538
+ * Scoping Strategy:
1539
+ * Storage is scoped by a user-provided cache key (typically a session identifier,
1540
+ * user ID, or combination of relevant scope factors). This scope is stored in
1541
+ * `_jqhtml_cache_key`. If the cache key changes between page loads, all JQHTML
1542
+ * storage is cleared to prevent stale data from different sessions/users.
1543
+ *
1544
+ * Key Format:
1545
+ * Keys are stored as: `jqhtml::developer_key::cache_key`
1546
+ * Example: `jqhtml::User_Profile_data::user_123`
1547
+ *
1548
+ * The `jqhtml::` prefix identifies JQHTML keys, allowing safe clearing of only our keys
1549
+ * without affecting other JavaScript libraries. This enables transparent coexistence
1550
+ * with third-party libraries that also use browser storage.
1551
+ *
1552
+ * Quota Exceeded Handling:
1553
+ * When storage quota is exceeded during a set operation, only JQHTML keys (prefixed with
1554
+ * `jqhtml::`) are cleared, preserving other libraries' data. The operation is then retried
1555
+ * once. This ensures the application continues functioning even when storage is full.
1556
+ *
1557
+ * Usage:
1558
+ * // Register classes that need to be cached (call once at startup)
1559
+ * jqhtml.register_cache_class(Contact_Model);
1560
+ * jqhtml.register_cache_class(User_Profile);
1561
+ *
1562
+ * // Must set cache key first (typically done once on page load)
1563
+ * Jqhtml_Local_Storage.set_cache_key('user_123');
1564
+ *
1565
+ * // Then use storage normally - ES6 classes serialize automatically
1566
+ * Jqhtml_Local_Storage.set('cached_component', {
1567
+ * contact: new Contact_Model(),
1568
+ * timestamp: Date.now()
1569
+ * });
1570
+ * const cached = Jqhtml_Local_Storage.get('cached_component');
1571
+ * // cached.contact instanceof Contact_Model === true
1572
+ *
1573
+ * IMPORTANT - Volatile Storage:
1574
+ * Storage can be cleared at any time due to:
1575
+ * - User clearing browser data
1576
+ * - Private browsing mode restrictions
1577
+ * - Quota exceeded errors
1578
+ * - Cache key changes
1579
+ * - Browser storage unavailable
1580
+ *
1581
+ * Therefore, NEVER store critical data. Only use for:
1582
+ * - Cached component HTML (performance optimization)
1583
+ * - Transient UI state (convenience, not required)
1526
1584
  *
1527
1585
  * @internal This class is not exposed in the public API
1586
+ *
1587
+ * ---------------------------------------------------------------------------
1588
+ * REPORTING WHAT WAS DROPPED
1589
+ *
1590
+ * `this.data` is always the serialized copy this file produces - in EVERY cache
1591
+ * mode, including 'none' (see component.ts `_apply_load_result`). Whatever the
1592
+ * serializer cannot express is therefore not merely missing from the cache, it
1593
+ * is missing from `this.data`, and an author needs to be told once rather than
1594
+ * discover it on the next cache hit.
1595
+ *
1596
+ * Two small optional parameters carry that:
1597
+ *
1598
+ * process_for_serialization(value, verbose, seen, path, collector?)
1599
+ * `collector(path, kind)` is invoked for every value that is dropped or
1600
+ * degraded. `path` is a dotted/bracketed path from the root the caller
1601
+ * named; `kind` is one of Strip_Kind. Paths are only BUILT when a
1602
+ * collector is present, so the no-collector path costs nothing.
1603
+ *
1604
+ * Jqhtml_Local_Storage.normalize_for_cache(value, component_name?)
1605
+ * With a component name, and only in development mode, each dropped path
1606
+ * prints exactly ONE console.warn for the life of the page (keyed
1607
+ * `${component_name}:${path}`, the same once-only shape as
1608
+ * warn_uncacheable_args in component-cache.ts). Production converts
1609
+ * silently. Neither ever throws.
1610
+ * ---------------------------------------------------------------------------
1528
1611
  */
1529
- class Load_Coordinator {
1530
- /**
1531
- * Generate INVOCATION_KEY from component name and args
1532
- * Uses deterministic JSON serialization (sorted keys)
1533
- * Excludes internal properties (those starting with _)
1534
- *
1535
- * For functions/objects:
1536
- * - Checks for ._jqhtml_cache_id property (assigned by RSpade)
1537
- * - Falls back to .jqhtml_cache_id() method if property doesn't exist
1538
- * - If neither exists, marks property as uncacheable
1539
- *
1540
- * Returns object with:
1541
- * - key: Cache key string, or null if uncacheable
1542
- * - uncacheable_property: Name of first property that prevented caching (for debugging)
1543
- */
1544
- static generate_invocation_key(component_name, args, options = {}) {
1545
- let uncacheable_property;
1546
- let uncacheable_reason;
1547
- // Filter out internal properties (starting with _) and serialize args
1548
- const serializable_args = {};
1549
- for (const key of Object.keys(args).sort()) {
1550
- if (key.startsWith('_')) {
1551
- continue; // Skip internal properties
1552
- }
1553
- // Skip framework properties that shouldn't affect cache identity
1554
- // Note: _load_only and _load_render_only are already filtered by the _ prefix check above
1555
- if (key === 'use_cached_data') {
1556
- continue;
1557
- }
1558
- const value = args[key];
1559
- const value_type = typeof value;
1560
- // Handle primitives (string, number, boolean, null, undefined)
1561
- if (value === null || value === undefined ||
1562
- value_type === 'string' || value_type === 'number' ||
1563
- value_type === 'boolean') {
1564
- serializable_args[key] = value;
1565
- continue;
1566
- }
1567
- // Handle functions and objects
1568
- if (value_type === 'function' || value_type === 'object') {
1569
- // Check for ._jqhtml_cache_id property (fastest, what RSpade assigns)
1570
- if (value._jqhtml_cache_id !== undefined) {
1571
- serializable_args[key] = `__JQHTML_CACHE_ID__:${String(value._jqhtml_cache_id)}`;
1572
- continue;
1573
- }
1574
- // Check for .jqhtml_cache_id() method (more flexible, for custom objects)
1575
- if (typeof value.jqhtml_cache_id === 'function') {
1576
- try {
1577
- const cache_id = value.jqhtml_cache_id();
1578
- serializable_args[key] = `__JQHTML_CACHE_ID__:${String(cache_id)}`;
1579
- continue;
1580
- }
1581
- catch (error) {
1582
- // Method threw error - treat as uncacheable
1583
- if (!uncacheable_property) {
1584
- uncacheable_property = key;
1585
- uncacheable_reason = 'cache-id-threw';
1586
- }
1587
- return { key: null, uncacheable_property, uncacheable_reason };
1588
- }
1589
- }
1590
- // No author-supplied id. The cache may fall back to keying by
1591
- // deterministic content; deduplication deliberately may not.
1592
- if (options.allow_content_serialization) {
1593
- const serialized = serialize_for_cache_key(value);
1594
- if (serialized.ok) {
1595
- serializable_args[key] = `__JQHTML_CONTENT__:${serialized.text}`;
1596
- continue;
1597
- }
1598
- if (!uncacheable_property) {
1599
- uncacheable_property = key;
1600
- // This package compiles with strictNullChecks off, and without it
1601
- // TypeScript will not narrow a discriminated union by its boolean
1602
- // discriminant - so `serialized` is still the full Serialize_Result
1603
- // here even though `ok` has been ruled out above. The cast states
1604
- // what the control flow already guarantees.
1605
- uncacheable_reason = serialized.reason;
1606
- }
1607
- return { key: null, uncacheable_property, uncacheable_reason };
1608
- }
1609
- if (!uncacheable_property) {
1610
- uncacheable_property = key;
1611
- uncacheable_reason = value_type === 'function' ? 'function' : 'object';
1612
- }
1613
- return { key: null, uncacheable_property, uncacheable_reason };
1614
- }
1615
- // Unknown type (symbol, bigint, etc.) - uncacheable
1616
- if (!uncacheable_property) {
1617
- uncacheable_property = key;
1618
- uncacheable_reason = value_type;
1619
- }
1620
- return { key: null, uncacheable_property, uncacheable_reason };
1621
- }
1622
- // Try to serialize - if it fails (shouldn't happen now, but safety net), return null
1623
- try {
1624
- const sorted_args = JSON.stringify(serializable_args);
1625
- return { key: `${component_name}::${sorted_args}` };
1612
+ // Registry mapping class names to constructors and their restore hooks
1613
+ const class_registry = Object.create(null);
1614
+ // Markers for serialized class instances (unique to avoid collisions with user data)
1615
+ // Replaced at build time by rollup (see rollup.config.js).
1616
+ const CORE_VERSION = '2.3.72';
1617
+ const CLASS_MARKER = '__jqhtml_class__';
1618
+ const PROPS_MARKER = '__jqhtml_props__';
1619
+ /**
1620
+ * Register a class for cache serialization/deserialization.
1621
+ * Must be called before attempting to cache instances of this class.
1622
+ *
1623
+ * @param klass - The class constructor to register
1624
+ * @param options - How to convert instances to and from their plain form; see
1625
+ * Cache_Class_Options. Omit for a class whose state is its own
1626
+ * enumerable properties.
1627
+ * @throws Error if klass is not a named function/class, or if to_plain is given
1628
+ * without the from_plain that undoes it
1629
+ */
1630
+ function register_cache_class(klass, options = {}) {
1631
+ if (typeof klass !== 'function' || !klass.name) {
1632
+ throw new Error('[JQHTML Cache] register_cache_class requires a named class constructor');
1633
+ }
1634
+ const to_plain = typeof options.to_plain === 'function' ? options.to_plain : null;
1635
+ const from_plain = typeof options.from_plain === 'function' ? options.from_plain : null;
1636
+ if (to_plain && !from_plain) {
1637
+ throw new Error(`[JQHTML Cache] register_cache_class(${klass.name}): to_plain needs a from_plain. ` +
1638
+ `The serializer cannot rebuild an instance from a custom wire form on its own.`);
1639
+ }
1640
+ class_registry[klass.name] = { klass, to_plain, from_plain };
1641
+ }
1642
+ // Built-ins travel through the same hook as user classes. Their wire forms are
1643
+ // the ones the cache has always stored (ISO string, entry pairs, item list), so
1644
+ // entries written before this existed still restore.
1645
+ register_cache_class(Date, {
1646
+ to_plain: (date) => date.toISOString(),
1647
+ from_plain: (iso) => new Date(iso)
1648
+ });
1649
+ register_cache_class(Map, {
1650
+ to_plain: (map) => Array.from(map.entries()),
1651
+ from_plain: (entries) => new Map(entries)
1652
+ });
1653
+ register_cache_class(Set, {
1654
+ to_plain: (set) => Array.from(set),
1655
+ from_plain: (items) => new Set(items)
1656
+ });
1657
+ /**
1658
+ * Find the registry entry for a live value: by constructor name first, then by
1659
+ * instanceof for the built-ins so a subclass of Date/Map/Set (whose name is not
1660
+ * registered) still serializes as the built-in it is.
1661
+ */
1662
+ function lookup_registered(value) {
1663
+ const ctor = value.constructor;
1664
+ if (ctor && ctor.name && class_registry[ctor.name]) {
1665
+ return { name: ctor.name, entry: class_registry[ctor.name] };
1666
+ }
1667
+ if (value instanceof Date)
1668
+ return { name: 'Date', entry: class_registry['Date'] };
1669
+ if (value instanceof Map)
1670
+ return { name: 'Map', entry: class_registry['Map'] };
1671
+ if (value instanceof Set)
1672
+ return { name: 'Set', entry: class_registry['Set'] };
1673
+ return null;
1674
+ }
1675
+ /**
1676
+ * Serialize a value to JSON string, handling ES6 class instances recursively.
1677
+ * Returns null if serialization fails for any reason.
1678
+ *
1679
+ * @param value - The value to serialize
1680
+ * @param verbose - Whether to log warnings
1681
+ * @param path - Root path used when reporting drops (only used with a collector)
1682
+ * @param collector - Optional reporter, see the file header
1683
+ * @returns Serialized JSON string, or null if serialization failed
1684
+ */
1685
+ function serialize_value(value, verbose, path = '', collector) {
1686
+ try {
1687
+ const seen = new WeakSet();
1688
+ const processed = process_for_serialization(value, verbose, seen, path, collector);
1689
+ if (processed === undefined) {
1690
+ // Serialization failed - undefined signals failure
1691
+ return null;
1626
1692
  }
1627
- catch (error) {
1628
- // Serialization failed unexpectedly
1629
- return { key: null, uncacheable_property };
1693
+ return JSON.stringify(processed);
1694
+ }
1695
+ catch (e) {
1696
+ if (verbose) {
1697
+ console.warn('[JQHTML Cache] Serialization failed:', e);
1630
1698
  }
1699
+ return null;
1631
1700
  }
1632
- /**
1633
- * Check if a component should execute on_load() or wait for existing request
1634
- * Returns true if component should execute (is leader), false if should wait (is follower)
1635
- *
1636
- * @param key - The dedup key the caller captured for this load. Every coordinator
1637
- * method takes it, because args may legally change during on_load()
1638
- * and a recomputed key would address a different (or no) entry.
1639
- */
1640
- static should_execute_on_load(component, key) {
1641
- const entry = this._registry.get(key);
1642
- if (!entry) {
1643
- // No existing request - this component becomes the leader
1644
- return true;
1645
- }
1646
- if (entry.status === 'loading') {
1647
- // Request in progress - this component becomes a follower
1648
- entry.waiting.push(component);
1649
- return false;
1650
- }
1651
- // Entry exists but completed/failed - should have been cleaned up
1652
- // Treat as new leader
1653
- return true;
1654
- }
1655
- /**
1656
- * Register a leader component that will execute on_load()
1657
- * Creates coordination entry and returns a function to call when data is ready
1658
- *
1659
- * @param key - The dedup key captured by the caller (see should_execute_on_load)
1660
- * @returns A function that accepts the final data and completes coordination
1661
- */
1662
- static register_leader(component, key) {
1663
- // Create a promise that we control - it settles when coordination completes or fails
1664
- let resolve_promise;
1665
- let reject_promise;
1666
- const coordination_promise = new Promise((resolve, reject) => {
1667
- resolve_promise = resolve;
1668
- reject_promise = reject;
1669
- });
1670
- // A leader with no followers still has to be able to reject this promise on
1671
- // error; without a handler that rejection surfaces as an unhandled rejection.
1672
- coordination_promise.catch(() => { });
1673
- const entry = {
1674
- status: 'loading',
1675
- promise: coordination_promise, // Followers await THIS promise, not on_load's
1676
- resolve_promise,
1677
- reject_promise,
1678
- leader_component: component,
1679
- leader_data: null,
1680
- waiting: []
1681
- };
1682
- this._registry.set(key, entry);
1683
- // Return cleanup function that accepts the final data
1684
- return (final_data) => this._complete_coordination(key, component, final_data);
1701
+ }
1702
+ /**
1703
+ * Recursively process a value for serialization.
1704
+ *
1705
+ * Values the serializer cannot express are DROPPED, never passed through: the
1706
+ * result of this function is what becomes `this.data`, so letting a function or
1707
+ * a DOM node survive here would make `this.data` differ from what the cache can
1708
+ * ever return. A dropped property is omitted from an object and becomes `null`
1709
+ * in an array - JSON's own semantics for the same situation.
1710
+ *
1711
+ * Returns undefined for a value that has to be dropped.
1712
+ *
1713
+ * @param value - The value to process
1714
+ * @param verbose - Whether to log warnings
1715
+ * @param seen - WeakSet to detect circular references
1716
+ * @param path - Dotted path of this value (only built when a collector is present)
1717
+ * @param collector - Optional reporter for dropped/degraded values
1718
+ * @returns Processed value ready for JSON.stringify, or undefined if dropped
1719
+ */
1720
+ function process_for_serialization(value, verbose, seen, path = '', collector) {
1721
+ // Handle null and undefined
1722
+ if (value === null) {
1723
+ return null;
1685
1724
  }
1686
- /**
1687
- * Get the coordination promise for a follower component
1688
- * Returns a promise that resolves when the leader completes, or rejects if it failed
1689
- */
1690
- static get_coordination_promise(key) {
1691
- const entry = this._registry.get(key);
1692
- if (!entry || entry.status !== 'loading') {
1693
- return null;
1694
- }
1695
- return entry.promise;
1725
+ if (value === undefined) {
1726
+ return undefined; // JSON.stringify will omit this property
1696
1727
  }
1697
- /**
1698
- * Complete coordination after leader's on_load() finishes
1699
- * Stores leader's data, marks entry as completed, and resolves the promise.
1700
- * Followers retrieve the data themselves via get_leader_data().
1701
- *
1702
- * @param key - The coordination key captured at registration
1703
- * @param leader - The leader component
1704
- * @param final_data - The final data after on_load and normalization
1705
- * @private
1706
- */
1707
- static _complete_coordination(key, leader, final_data) {
1708
- const entry = this._registry.get(key);
1709
- if (!entry) {
1710
- return;
1728
+ // Handle primitives
1729
+ if (typeof value !== 'object') {
1730
+ // string, number, boolean are fine
1731
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
1732
+ return value;
1711
1733
  }
1712
- // Stored as TEXT so each follower parses its own object graph - sharing one
1713
- // decoded object would let one component's mutation reach every other.
1714
- try {
1715
- entry.leader_data = JSON.stringify(final_data);
1734
+ // bigint, symbol, function cannot be serialized
1735
+ if (typeof value === 'function') {
1736
+ collector?.(path, 'function');
1716
1737
  }
1717
- catch (error) {
1718
- // Unserializable data cannot be shared; followers load independently.
1719
- entry.leader_data = null;
1738
+ else if (typeof value === 'symbol') {
1739
+ collector?.(path, 'symbol');
1720
1740
  }
1721
- entry.status = 'completed';
1722
- if (window.jqhtml?.debug?.verbose) {
1723
- console.log(`[Load Coordinator] Leader ${leader._cid} completed, data available for ${entry.waiting.length} followers`, { key, data: entry.leader_data });
1741
+ else if (typeof value === 'bigint') {
1742
+ collector?.(path, 'bigint');
1724
1743
  }
1725
- // Resolve the promise - followers waiting on it will now wake up
1726
- entry.resolve_promise();
1727
- // Nobody is waiting, so nothing will ever come back to collect the data.
1728
- // Without this the registry grows once per distinct name+args, forever.
1729
- if (entry.waiting.length === 0) {
1730
- this._registry.delete(key);
1744
+ if (verbose) {
1745
+ console.warn(`[JQHTML Cache] Cannot serialize ${typeof value} - value will be omitted`);
1731
1746
  }
1747
+ // Return undefined to omit this value (not fail entire serialization)
1748
+ return undefined;
1732
1749
  }
1733
- /**
1734
- * Get leader's data for a follower component
1735
- * Called by follower after coordination promise resolves
1736
- * Returns a freshly parsed copy and cleans up if this is the last follower
1737
- *
1738
- * @param key - The dedup key captured by the follower before it began waiting
1739
- */
1740
- static get_leader_data(component, key) {
1741
- const entry = this._registry.get(key);
1742
- if (!entry || entry.status !== 'completed' || entry.leader_data === null) {
1743
- return null;
1744
- }
1745
- // Remove this follower from the waiting list
1746
- const follower_index = entry.waiting.indexOf(component);
1747
- if (follower_index !== -1) {
1748
- entry.waiting.splice(follower_index, 1);
1749
- }
1750
- // One parse per follower: each gets its OWN object, never a shared reference.
1751
- const data = JSON.parse(entry.leader_data);
1752
- if (window.jqhtml?.debug?.verbose) {
1753
- console.log(`[Load Coordinator] Follower ${component._cid} retrieving data from leader ${entry.leader_component._cid}`, { key, remaining_followers: entry.waiting.length });
1750
+ // Live objects that only LOOK like data. Each is checked before anything
1751
+ // treats it as a bag of properties, because walking one produces a
1752
+ // meaningless husk (a jQuery object becomes {0: ..., length: 1}) instead of
1753
+ // the drop the author needs to hear about.
1754
+ if (typeof value.nodeType === 'number') {
1755
+ collector?.(path, 'dom-node');
1756
+ return undefined;
1757
+ }
1758
+ if (value.jquery) {
1759
+ collector?.(path, 'jquery');
1760
+ return undefined;
1761
+ }
1762
+ // Duck-typed on purpose: importing Jqhtml_Component here would be a cycle
1763
+ // (component.ts imports this file). _cid + component_name() is the pair no
1764
+ // plain data object carries.
1765
+ if (value._cid !== undefined && typeof value.component_name === 'function') {
1766
+ collector?.(path, 'component');
1767
+ return undefined;
1768
+ }
1769
+ if (typeof value.then === 'function') {
1770
+ collector?.(path, 'promise');
1771
+ return undefined;
1772
+ }
1773
+ // Handle circular references.
1774
+ // `seen` tracks only the current ancestor path (the DFS stack): an object is
1775
+ // added on the way down and removed on the way back up (see finally below).
1776
+ // This flags a genuine cycle (a back-edge to an ancestor) while allowing a
1777
+ // shared reference in a DAG to be serialized independently on each visit.
1778
+ // JSON round-trip semantics do not preserve identity anyway, so emitting a
1779
+ // copy per reference is correct; silently omitting the property is not.
1780
+ if (seen.has(value)) {
1781
+ collector?.(path, 'circular');
1782
+ if (verbose) {
1783
+ console.warn('[JQHTML Cache] Circular reference detected - cutting the cycle');
1754
1784
  }
1755
- // If this was the last follower, clean up the entry
1756
- if (entry.waiting.length === 0) {
1757
- this._registry.delete(key);
1758
- if (window.jqhtml?.debug?.verbose) {
1759
- console.log(`[Load Coordinator] Coordination complete for key: ${key}`, { registry_size: this._registry.size });
1785
+ return undefined; // Cut the cycle here; the rest of the tree still serializes
1786
+ }
1787
+ seen.add(value);
1788
+ try {
1789
+ // Handle arrays
1790
+ if (Array.isArray(value)) {
1791
+ const result = [];
1792
+ for (let i = 0; i < value.length; i++) {
1793
+ const item = value[i];
1794
+ const processed = process_for_serialization(item, verbose, seen, collector ? `${path}[${i}]` : '', collector);
1795
+ // For arrays, we keep undefined as null to preserve indices
1796
+ result.push(processed === undefined ? null : processed);
1760
1797
  }
1798
+ return result;
1761
1799
  }
1762
- return data;
1763
- }
1764
- /**
1765
- * Handle leader on_load() error
1766
- * Rejects every waiting follower and clears the entry so the next component retries
1767
- *
1768
- * @param key - The dedup key captured at registration
1769
- */
1770
- static handle_leader_error(key, error) {
1771
- const entry = this._registry.get(key);
1772
- if (!entry) {
1773
- return;
1800
+ // Registered classes - Date, Map and Set included - go out as
1801
+ // {__jqhtml_class__, __jqhtml_props__} through their restore hook.
1802
+ const registered = lookup_registered(value);
1803
+ if (registered) {
1804
+ const plain = registered_plain_form(registered, value, verbose, seen, path, collector);
1805
+ if (plain === undefined) {
1806
+ return undefined; // to_plain threw; the value is dropped, and reported
1807
+ }
1808
+ return {
1809
+ [CLASS_MARKER]: registered.name,
1810
+ [PROPS_MARKER]: plain
1811
+ };
1774
1812
  }
1775
- entry.status = 'failed';
1776
- console.error(`[Load Coordinator] Leader ${entry.leader_component._cid} on_load() failed for key: ${key}`, error);
1777
- // Reject FIRST: followers are parked on this promise and their catch in _load()
1778
- // propagates the failure exactly as if their own on_load() had thrown. Deleting
1779
- // without rejecting left them awaiting a promise nobody could ever settle.
1780
- entry.reject_promise(error);
1781
- // Clear coordination entry so future requests can retry
1782
- this._registry.delete(key);
1783
- if (window.jqhtml?.debug?.verbose) {
1784
- console.log(`[Load Coordinator] Cleared failed coordination for key: ${key}`, { followers_count: entry.waiting.length });
1813
+ const ctor = value.constructor;
1814
+ // Handle plain objects (constructor is Object or no constructor)
1815
+ if (ctor === Object || ctor === undefined || ctor === null) {
1816
+ return process_own_properties(value, verbose, seen, path, collector);
1785
1817
  }
1786
- }
1787
- /**
1788
- * Get current registry state (for debugging)
1789
- */
1790
- static get_registry_state() {
1791
- const state = {};
1792
- for (const [key, entry] of this._registry.entries()) {
1793
- state[key] = {
1794
- status: entry.status,
1795
- leader_cid: entry.leader_component._cid,
1796
- waiting_count: entry.waiting.length,
1797
- waiting_cids: entry.waiting.map(c => c._cid)
1798
- };
1818
+ // Unregistered class instance - convert to plain object for hot/cold parity.
1819
+ // Properties are preserved, prototype methods are lost, exactly as a cache
1820
+ // hit would produce, so the loss shows up on the first load rather than on
1821
+ // the next page view.
1822
+ collector?.(path, 'unregistered-class', ctor.name);
1823
+ if (verbose) {
1824
+ console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
1825
+ `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
1799
1826
  }
1800
- return state;
1827
+ return process_own_properties(value, verbose, seen, path, collector);
1801
1828
  }
1802
- /**
1803
- * Clear all coordination entries (for testing/debugging)
1804
- */
1805
- static clear_all() {
1806
- this._registry.clear();
1829
+ finally {
1830
+ // Pop this object off the ancestor path now that its subtree is done.
1831
+ seen.delete(value);
1807
1832
  }
1808
1833
  }
1809
- Load_Coordinator._registry = new Map();
1810
-
1811
1834
  /**
1812
- * Jqhtml_Local_Storage - Scoped local storage for JQHTML component caching
1835
+ * The plain value stored for a registered instance.
1813
1836
  *
1814
- * Provides safe, scoped access to localStorage with automatic handling of
1815
- * unavailable storage, quota exceeded errors, and scope invalidation.
1816
- *
1817
- * Key Features:
1818
- * - **Manual scoping**: Cache key must be set via set_cache_key() before use
1819
- * - **Graceful degradation**: Returns null when storage unavailable or cache key not set
1820
- * - **Quota management**: Auto-clears storage when full and retries operation
1821
- * - **Scope validation**: Clears storage when cache key changes
1822
- * - **Developer-friendly keys**: Scoped suffix allows easy inspection in dev tools
1823
- * - **Class-aware serialization**: ES6 class instances serialize and restore properly
1824
- *
1825
- * Class-Aware Serialization:
1826
- * ES6 class instances can be serialized and deserialized if registered via
1827
- * register_cache_class(). Classes are wrapped as {__jqhtml_class__: "Name", __jqhtml_props__: {...}}
1828
- * and restored to proper instances on retrieval. Nested class instances in objects
1829
- * and arrays are handled recursively.
1830
- *
1831
- * Scoping Strategy:
1832
- * Storage is scoped by a user-provided cache key (typically a session identifier,
1833
- * user ID, or combination of relevant scope factors). This scope is stored in
1834
- * `_jqhtml_cache_key`. If the cache key changes between page loads, all JQHTML
1835
- * storage is cleared to prevent stale data from different sessions/users.
1836
- *
1837
- * Key Format:
1838
- * Keys are stored as: `jqhtml::developer_key::cache_key`
1839
- * Example: `jqhtml::User_Profile_data::user_123`
1840
- *
1841
- * The `jqhtml::` prefix identifies JQHTML keys, allowing safe clearing of only our keys
1842
- * without affecting other JavaScript libraries. This enables transparent coexistence
1843
- * with third-party libraries that also use browser storage.
1844
- *
1845
- * Quota Exceeded Handling:
1846
- * When storage quota is exceeded during a set operation, only JQHTML keys (prefixed with
1847
- * `jqhtml::`) are cleared, preserving other libraries' data. The operation is then retried
1848
- * once. This ensures the application continues functioning even when storage is full.
1849
- *
1850
- * Usage:
1851
- * // Register classes that need to be cached (call once at startup)
1852
- * jqhtml.register_cache_class(Contact_Model);
1853
- * jqhtml.register_cache_class(User_Profile);
1854
- *
1855
- * // Must set cache key first (typically done once on page load)
1856
- * Jqhtml_Local_Storage.set_cache_key('user_123');
1857
- *
1858
- * // Then use storage normally - ES6 classes serialize automatically
1859
- * Jqhtml_Local_Storage.set('cached_component', {
1860
- * contact: new Contact_Model(),
1861
- * timestamp: Date.now()
1862
- * });
1863
- * const cached = Jqhtml_Local_Storage.get('cached_component');
1864
- * // cached.contact instanceof Contact_Model === true
1865
- *
1866
- * IMPORTANT - Volatile Storage:
1867
- * Storage can be cleared at any time due to:
1868
- * - User clearing browser data
1869
- * - Private browsing mode restrictions
1870
- * - Quota exceeded errors
1871
- * - Cache key changes
1872
- * - Browser storage unavailable
1873
- *
1874
- * Therefore, NEVER store critical data. Only use for:
1875
- * - Cached component HTML (performance optimization)
1876
- * - Transient UI state (convenience, not required)
1877
- *
1878
- * @internal This class is not exposed in the public API
1879
- *
1880
- * ---------------------------------------------------------------------------
1881
- * REPORTING WHAT WAS DROPPED
1882
- *
1883
- * `this.data` is always the serialized copy this file produces - in EVERY cache
1884
- * mode, including 'none' (see component.ts `_apply_load_result`). Whatever the
1885
- * serializer cannot express is therefore not merely missing from the cache, it
1886
- * is missing from `this.data`, and an author needs to be told once rather than
1887
- * discover it on the next cache hit.
1888
- *
1889
- * Two small optional parameters carry that:
1890
- *
1891
- * process_for_serialization(value, verbose, seen, path, collector?)
1892
- * `collector(path, kind)` is invoked for every value that is dropped or
1893
- * degraded. `path` is a dotted/bracketed path from the root the caller
1894
- * named; `kind` is one of Strip_Kind. Paths are only BUILT when a
1895
- * collector is present, so the no-collector path costs nothing.
1837
+ * No from_plain: own enumerable properties (toJSON() is deliberately bypassed,
1838
+ * because Object.assign is the only way back and it needs the properties).
1839
+ * With from_plain: to_plain(instance), or toJSON() when the class defines one,
1840
+ * or own properties as the last resort. Whatever comes back is walked by the
1841
+ * serializer like any other value.
1896
1842
  *
1897
- * Jqhtml_Local_Storage.normalize_for_cache(value, component_name?)
1898
- * With a component name, and only in development mode, each dropped path
1899
- * prints exactly ONE console.warn for the life of the page (keyed
1900
- * `${component_name}:${path}`, the same once-only shape as
1901
- * warn_uncacheable_args in component-cache.ts). Production converts
1902
- * silently. Neither ever throws.
1903
- * ---------------------------------------------------------------------------
1843
+ * Returns undefined when to_plain threw - the caller drops the value.
1844
+ */
1845
+ function registered_plain_form(registered, value, verbose, seen, path, collector) {
1846
+ const { name, entry } = registered;
1847
+ if (!entry.from_plain) {
1848
+ return process_own_properties(value, verbose, seen, path, collector);
1849
+ }
1850
+ let plain;
1851
+ try {
1852
+ if (entry.to_plain) {
1853
+ plain = entry.to_plain(value);
1854
+ }
1855
+ else if (typeof value.toJSON === 'function') {
1856
+ plain = value.toJSON();
1857
+ }
1858
+ else {
1859
+ return process_own_properties(value, verbose, seen, path, collector);
1860
+ }
1861
+ }
1862
+ catch (e) {
1863
+ collector?.(path, 'to-plain-threw', name);
1864
+ if (verbose) {
1865
+ console.warn(`[JQHTML Cache] to_plain for class "${name}" threw - value will be omitted:`, e);
1866
+ }
1867
+ return undefined;
1868
+ }
1869
+ // A toJSON() that returns `this` has no separate wire form; own properties it is.
1870
+ if (plain === value) {
1871
+ return process_own_properties(value, verbose, seen, path, collector);
1872
+ }
1873
+ const processed = process_for_serialization(plain, verbose, seen, path, collector);
1874
+ return processed === undefined ? null : processed;
1875
+ }
1876
+ /**
1877
+ * Walk an object's own enumerable properties (bypassing any toJSON) into a plain
1878
+ * object. Shared by plain objects, registered class instances and degraded
1879
+ * unregistered instances - all three keep exactly the same property semantics.
1904
1880
  */
1881
+ function process_own_properties(value, verbose, seen, path, collector) {
1882
+ const result = {};
1883
+ for (const key of Object.keys(value)) {
1884
+ const propValue = value[key];
1885
+ const processed = process_for_serialization(propValue, verbose, seen, collector ? `${path}.${key}` : '', collector);
1886
+ // Only include if not undefined (unless original was undefined)
1887
+ if (processed !== undefined || propValue === undefined) {
1888
+ result[key] = processed;
1889
+ }
1890
+ }
1891
+ return result;
1892
+ }
1905
1893
  // ============================================================================
1906
- // Class Registry for Serialization
1894
+ // Development warnings for dropped values
1907
1895
  // ============================================================================
1908
- // Registry mapping class names to constructors
1909
- const class_registry = Object.create(null);
1910
- // Markers for serialized class instances (unique to avoid collisions with user data)
1911
- // Replaced at build time by rollup (see rollup.config.js).
1912
- const CORE_VERSION = '2.3.70';
1913
- const CLASS_MARKER = '__jqhtml_class__';
1914
- const PROPS_MARKER = '__jqhtml_props__';
1896
+ // One warning per component + path, for the life of the page. A list of 50 rows
1897
+ // each carrying an $on_select callback must print ONE warning, not 50, and must
1898
+ // not print it again on the next reload() or on the next instance of the same
1899
+ // component. Same shape as _warned_uncacheable in component-cache.ts.
1900
+ const _warned_stripped = new Set();
1915
1901
  /**
1916
- * Register a class for cache serialization/deserialization.
1917
- * Must be called before attempting to cache instances of this class.
1918
- *
1919
- * @param klass - The class constructor to register
1920
- * @throws Error if klass is not a named function/class
1902
+ * What was lost, and where the value actually belongs. Every message names a
1903
+ * destination, because "it was dropped" without "put it here instead" is not
1904
+ * actionable.
1921
1905
  */
1922
- function register_cache_class(klass) {
1923
- if (typeof klass !== 'function' || !klass.name) {
1924
- throw new Error('[JQHTML Cache] register_cache_class requires a named class constructor');
1906
+ function strip_advice(kind, detail) {
1907
+ switch (kind) {
1908
+ case 'function':
1909
+ return 'a function cannot be serialized. Callbacks are configuration, not loaded data - ' +
1910
+ 'pass it in this.args (from the parent template) and keep only ids in this.data.';
1911
+ case 'promise':
1912
+ return 'a promise cannot be serialized. Await it inside on_load() and store the RESULT, ' +
1913
+ 'or hold the pending promise in this.state.';
1914
+ case 'dom-node':
1915
+ return 'a DOM node cannot be serialized. Elements, timers, files and sockets belong in this.state.';
1916
+ case 'jquery':
1917
+ return 'a jQuery object cannot be serialized. Elements, timers, files and sockets belong in this.state.';
1918
+ case 'component':
1919
+ return 'a Jqhtml_Component cannot be serialized. Keep component references in this.state ' +
1920
+ 'and address children with this.sid().';
1921
+ case 'symbol':
1922
+ return 'a symbol cannot be serialized. Use a string, or keep it in this.state.';
1923
+ case 'bigint':
1924
+ return 'a bigint cannot be serialized. Convert it to a string in on_load(), or keep it in this.state.';
1925
+ case 'circular':
1926
+ return 'it points back to one of its own ancestors, and the cycle was cut. Store the graph ' +
1927
+ 'flat (ids instead of back-references) in this.data, or keep the linked form in this.state.';
1928
+ case 'unregistered-class':
1929
+ return `it is an instance of the unregistered class "${detail}", so it was degraded to a plain ` +
1930
+ `object and its methods are gone. Call jqhtml.register_cache_class(${detail}) at startup ` +
1931
+ `to get real instances back - with { from_plain } if the class defines toJSON() or keeps ` +
1932
+ `state outside its own properties.`;
1933
+ case 'to-plain-threw':
1934
+ return `the to_plain hook registered for class "${detail}" threw, so the value was dropped. ` +
1935
+ `Make to_plain total over every instance the class can produce.`;
1925
1936
  }
1926
- class_registry[klass.name] = klass;
1927
1937
  }
1928
1938
  /**
1929
- * Serialize a value to JSON string, handling ES6 class instances recursively.
1930
- * Returns null if serialization fails for any reason.
1939
+ * Build the collector normalize_for_cache() hands to the serializer, or
1940
+ * `undefined` when nobody is listening - production, or a caller that named no
1941
+ * component. Returning undefined (rather than a no-op function) is what keeps
1942
+ * the serializer from building path strings at all on the hot path.
1943
+ */
1944
+ function make_strip_collector(component_name) {
1945
+ if (!component_name)
1946
+ return undefined;
1947
+ if (get_config().mode !== 'development')
1948
+ return undefined;
1949
+ return (path, kind, detail) => {
1950
+ try {
1951
+ const dedupe_key = `${component_name}:${path}`;
1952
+ if (_warned_stripped.has(dedupe_key))
1953
+ return;
1954
+ _warned_stripped.add(dedupe_key);
1955
+ console.warn(`[JQHTML] <${component_name}> dropped ${path} from this.data: ${strip_advice(kind, detail)}\n` +
1956
+ ` this.data is always the serialized copy jqhtml stores in and restores from cache, ` +
1957
+ `so only serializable values survive on_load() - in every cache mode.`, { component: component_name, path, kind });
1958
+ }
1959
+ catch {
1960
+ // A warning must never be able to break a load.
1961
+ }
1962
+ };
1963
+ }
1964
+ // ============================================================================
1965
+ // Deserialization (String → Object)
1966
+ // ============================================================================
1967
+ /**
1968
+ * Deserialize a JSON string, restoring ES6 class instances.
1969
+ * Returns null if deserialization fails.
1931
1970
  *
1932
- * @param value - The value to serialize
1971
+ * @param str - The JSON string to deserialize
1933
1972
  * @param verbose - Whether to log warnings
1934
- * @param path - Root path used when reporting drops (only used with a collector)
1935
- * @param collector - Optional reporter, see the file header
1936
- * @returns Serialized JSON string, or null if serialization failed
1973
+ * @returns Deserialized value with class instances restored, or null if failed
1937
1974
  */
1938
- function serialize_value(value, verbose, path = '', collector) {
1975
+ function deserialize_value(str, verbose) {
1939
1976
  try {
1940
- const seen = new WeakSet();
1941
- const processed = process_for_serialization(value, verbose, seen, path, collector);
1942
- if (processed === undefined) {
1943
- // Serialization failed - undefined signals failure
1944
- return null;
1945
- }
1946
- return JSON.stringify(processed);
1977
+ const parsed = JSON.parse(str);
1978
+ return process_for_deserialization(parsed, verbose);
1947
1979
  }
1948
1980
  catch (e) {
1949
1981
  if (verbose) {
1950
- console.warn('[JQHTML Cache] Serialization failed:', e);
1982
+ console.warn('[JQHTML Cache] Deserialization failed:', e);
1951
1983
  }
1952
1984
  return null;
1953
1985
  }
1954
1986
  }
1955
1987
  /**
1956
- * Recursively process a value for serialization.
1957
- *
1958
- * Values the serializer cannot express are DROPPED, never passed through: the
1959
- * result of this function is what becomes `this.data`, so letting a function or
1960
- * a DOM node survive here would make `this.data` differ from what the cache can
1961
- * ever return. A dropped property is omitted from an object and becomes `null`
1962
- * in an array - JSON's own semantics for the same situation.
1963
- *
1964
- * Returns undefined for a value that has to be dropped.
1988
+ * Recursively process a parsed value, restoring class instances.
1965
1989
  *
1966
- * @param value - The value to process
1990
+ * @param value - The parsed value to process
1967
1991
  * @param verbose - Whether to log warnings
1968
- * @param seen - WeakSet to detect circular references
1969
- * @param path - Dotted path of this value (only built when a collector is present)
1970
- * @param collector - Optional reporter for dropped/degraded values
1971
- * @returns Processed value ready for JSON.stringify, or undefined if dropped
1992
+ * @returns Processed value with class instances restored
1972
1993
  */
1973
- function process_for_serialization(value, verbose, seen, path = '', collector) {
1974
- // Handle null and undefined
1975
- if (value === null) {
1976
- return null;
1994
+ function process_for_deserialization(value, verbose) {
1995
+ // Handle primitives and null
1996
+ if (value === null || value === undefined || typeof value !== 'object') {
1997
+ return value;
1977
1998
  }
1978
- if (value === undefined) {
1979
- return undefined; // JSON.stringify will omit this property
1980
- }
1981
- // Handle primitives
1982
- if (typeof value !== 'object') {
1983
- // string, number, boolean are fine
1984
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
1985
- return value;
1986
- }
1987
- // bigint, symbol, function cannot be serialized
1988
- if (typeof value === 'function') {
1989
- collector?.(path, 'function');
1990
- }
1991
- else if (typeof value === 'symbol') {
1992
- collector?.(path, 'symbol');
1993
- }
1994
- else if (typeof value === 'bigint') {
1995
- collector?.(path, 'bigint');
1996
- }
1997
- if (verbose) {
1998
- console.warn(`[JQHTML Cache] Cannot serialize ${typeof value} - value will be omitted`);
1999
- }
2000
- // Return undefined to omit this value (not fail entire serialization)
2001
- return undefined;
2002
- }
2003
- // Live objects that only LOOK like data. Each is checked before anything
2004
- // treats it as a bag of properties, because walking one produces a
2005
- // meaningless husk (a jQuery object becomes {0: ..., length: 1}) instead of
2006
- // the drop the author needs to hear about.
2007
- if (typeof value.nodeType === 'number') {
2008
- collector?.(path, 'dom-node');
2009
- return undefined;
2010
- }
2011
- if (value.jquery) {
2012
- collector?.(path, 'jquery');
2013
- return undefined;
2014
- }
2015
- // Duck-typed on purpose: importing Jqhtml_Component here would be a cycle
2016
- // (component.ts imports this file). _cid + component_name() is the pair no
2017
- // plain data object carries.
2018
- if (value._cid !== undefined && typeof value.component_name === 'function') {
2019
- collector?.(path, 'component');
2020
- return undefined;
2021
- }
2022
- if (typeof value.then === 'function') {
2023
- collector?.(path, 'promise');
2024
- return undefined;
2025
- }
2026
- // Handle circular references.
2027
- // `seen` tracks only the current ancestor path (the DFS stack): an object is
2028
- // added on the way down and removed on the way back up (see finally below).
2029
- // This flags a genuine cycle (a back-edge to an ancestor) while allowing a
2030
- // shared reference in a DAG to be serialized independently on each visit.
2031
- // JSON round-trip semantics do not preserve identity anyway, so emitting a
2032
- // copy per reference is correct; silently omitting the property is not.
2033
- if (seen.has(value)) {
2034
- collector?.(path, 'circular');
2035
- if (verbose) {
2036
- console.warn('[JQHTML Cache] Circular reference detected - cutting the cycle');
2037
- }
2038
- return undefined; // Cut the cycle here; the rest of the tree still serializes
2039
- }
2040
- seen.add(value);
2041
- try {
2042
- // Handle arrays
2043
- if (Array.isArray(value)) {
2044
- const result = [];
2045
- for (let i = 0; i < value.length; i++) {
2046
- const item = value[i];
2047
- const processed = process_for_serialization(item, verbose, seen, collector ? `${path}[${i}]` : '', collector);
2048
- // For arrays, we keep undefined as null to preserve indices
2049
- result.push(processed === undefined ? null : processed);
2050
- }
2051
- return result;
2052
- }
2053
- // Handle Date objects specially
2054
- if (value instanceof Date) {
2055
- return {
2056
- [CLASS_MARKER]: 'Date',
2057
- [PROPS_MARKER]: value.toISOString()
2058
- };
2059
- }
2060
- // Handle Map objects
2061
- if (value instanceof Map) {
2062
- const entries = [];
2063
- for (const [k, v] of value) {
2064
- const entry_path = collector ? `${path}.get(${String(k)})` : '';
2065
- const processedKey = process_for_serialization(k, verbose, seen, entry_path, collector);
2066
- const processedValue = process_for_serialization(v, verbose, seen, entry_path, collector);
2067
- entries.push([processedKey, processedValue]);
2068
- }
2069
- return {
2070
- [CLASS_MARKER]: 'Map',
2071
- [PROPS_MARKER]: entries
2072
- };
2073
- }
2074
- // Handle Set objects
2075
- if (value instanceof Set) {
2076
- const items = [];
2077
- let index = 0;
2078
- for (const item of value) {
2079
- items.push(process_for_serialization(item, verbose, seen, collector ? `${path}[Set ${index++}]` : '', collector));
2080
- }
2081
- return {
2082
- [CLASS_MARKER]: 'Set',
2083
- [PROPS_MARKER]: items
2084
- };
2085
- }
2086
- // Get the constructor
2087
- const ctor = value.constructor;
2088
- // Handle registered class instances
2089
- if (ctor && ctor.name && class_registry[ctor.name]) {
2090
- return {
2091
- [CLASS_MARKER]: ctor.name,
2092
- [PROPS_MARKER]: process_own_properties(value, verbose, seen, path, collector)
2093
- };
2094
- }
2095
- // Handle plain objects (constructor is Object or no constructor)
2096
- if (ctor === Object || ctor === undefined || ctor === null) {
2097
- return process_own_properties(value, verbose, seen, path, collector);
2098
- }
2099
- // Unregistered class instance - convert to plain object for hot/cold parity.
2100
- // Properties are preserved, prototype methods are lost, exactly as a cache
2101
- // hit would produce, so the loss shows up on the first load rather than on
2102
- // the next page view.
2103
- collector?.(path, 'unregistered-class', ctor.name);
2104
- if (verbose) {
2105
- console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
2106
- `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
2107
- }
2108
- return process_own_properties(value, verbose, seen, path, collector);
2109
- }
2110
- finally {
2111
- // Pop this object off the ancestor path now that its subtree is done.
2112
- seen.delete(value);
2113
- }
2114
- }
2115
- /**
2116
- * Walk an object's own enumerable properties (bypassing any toJSON) into a plain
2117
- * object. Shared by plain objects, registered class instances and degraded
2118
- * unregistered instances - all three keep exactly the same property semantics.
2119
- */
2120
- function process_own_properties(value, verbose, seen, path, collector) {
2121
- const result = {};
2122
- for (const key of Object.keys(value)) {
2123
- const propValue = value[key];
2124
- const processed = process_for_serialization(propValue, verbose, seen, collector ? `${path}.${key}` : '', collector);
2125
- // Only include if not undefined (unless original was undefined)
2126
- if (processed !== undefined || propValue === undefined) {
2127
- result[key] = processed;
2128
- }
2129
- }
2130
- return result;
2131
- }
2132
- // ============================================================================
2133
- // Development warnings for dropped values
2134
- // ============================================================================
2135
- // One warning per component + path, for the life of the page. A list of 50 rows
2136
- // each carrying an $on_select callback must print ONE warning, not 50, and must
2137
- // not print it again on the next reload() or on the next instance of the same
2138
- // component. Same shape as _warned_uncacheable in component-cache.ts.
2139
- const _warned_stripped = new Set();
2140
- /**
2141
- * What was lost, and where the value actually belongs. Every message names a
2142
- * destination, because "it was dropped" without "put it here instead" is not
2143
- * actionable.
2144
- */
2145
- function strip_advice(kind, detail) {
2146
- switch (kind) {
2147
- case 'function':
2148
- return 'a function cannot be serialized. Callbacks are configuration, not loaded data - ' +
2149
- 'pass it in this.args (from the parent template) and keep only ids in this.data.';
2150
- case 'promise':
2151
- return 'a promise cannot be serialized. Await it inside on_load() and store the RESULT, ' +
2152
- 'or hold the pending promise in this.state.';
2153
- case 'dom-node':
2154
- return 'a DOM node cannot be serialized. Elements, timers, files and sockets belong in this.state.';
2155
- case 'jquery':
2156
- return 'a jQuery object cannot be serialized. Elements, timers, files and sockets belong in this.state.';
2157
- case 'component':
2158
- return 'a Jqhtml_Component cannot be serialized. Keep component references in this.state ' +
2159
- 'and address children with this.sid().';
2160
- case 'symbol':
2161
- return 'a symbol cannot be serialized. Use a string, or keep it in this.state.';
2162
- case 'bigint':
2163
- return 'a bigint cannot be serialized. Convert it to a string in on_load(), or keep it in this.state.';
2164
- case 'circular':
2165
- return 'it points back to one of its own ancestors, and the cycle was cut. Store the graph ' +
2166
- 'flat (ids instead of back-references) in this.data, or keep the linked form in this.state.';
2167
- case 'unregistered-class':
2168
- return `it is an instance of the unregistered class "${detail}", so it was degraded to a plain ` +
2169
- `object and its methods are gone. Call jqhtml.register_cache_class(${detail}) at startup ` +
2170
- `to get real instances back.`;
2171
- }
2172
- }
2173
- /**
2174
- * Build the collector normalize_for_cache() hands to the serializer, or
2175
- * `undefined` when nobody is listening - production, or a caller that named no
2176
- * component. Returning undefined (rather than a no-op function) is what keeps
2177
- * the serializer from building path strings at all on the hot path.
2178
- */
2179
- function make_strip_collector(component_name) {
2180
- if (!component_name)
2181
- return undefined;
2182
- if (get_config().mode !== 'development')
2183
- return undefined;
2184
- return (path, kind, detail) => {
2185
- try {
2186
- const dedupe_key = `${component_name}:${path}`;
2187
- if (_warned_stripped.has(dedupe_key))
2188
- return;
2189
- _warned_stripped.add(dedupe_key);
2190
- console.warn(`[JQHTML] <${component_name}> dropped ${path} from this.data: ${strip_advice(kind, detail)}\n` +
2191
- ` this.data is always the serialized copy jqhtml stores in and restores from cache, ` +
2192
- `so only serializable values survive on_load() - in every cache mode.`, { component: component_name, path, kind });
2193
- }
2194
- catch {
2195
- // A warning must never be able to break a load.
2196
- }
2197
- };
2198
- }
2199
- // ============================================================================
2200
- // Deserialization (String → Object)
2201
- // ============================================================================
2202
- /**
2203
- * Deserialize a JSON string, restoring ES6 class instances.
2204
- * Returns null if deserialization fails.
2205
- *
2206
- * @param str - The JSON string to deserialize
2207
- * @param verbose - Whether to log warnings
2208
- * @returns Deserialized value with class instances restored, or null if failed
2209
- */
2210
- function deserialize_value(str, verbose) {
2211
- try {
2212
- const parsed = JSON.parse(str);
2213
- return process_for_deserialization(parsed, verbose);
2214
- }
2215
- catch (e) {
2216
- if (verbose) {
2217
- console.warn('[JQHTML Cache] Deserialization failed:', e);
2218
- }
2219
- return null;
2220
- }
2221
- }
2222
- /**
2223
- * Recursively process a parsed value, restoring class instances.
2224
- *
2225
- * @param value - The parsed value to process
2226
- * @param verbose - Whether to log warnings
2227
- * @returns Processed value with class instances restored
2228
- */
2229
- function process_for_deserialization(value, verbose) {
2230
- // Handle primitives and null
2231
- if (value === null || value === undefined || typeof value !== 'object') {
2232
- return value;
2233
- }
2234
- // Handle arrays
2235
- if (Array.isArray(value)) {
2236
- return value.map(item => process_for_deserialization(item, verbose));
1999
+ // Handle arrays
2000
+ if (Array.isArray(value)) {
2001
+ return value.map(item => process_for_deserialization(item, verbose));
2237
2002
  }
2238
2003
  // Check for class marker
2239
2004
  if (value[CLASS_MARKER] !== undefined && value[PROPS_MARKER] !== undefined) {
2240
2005
  const class_name = value[CLASS_MARKER];
2241
2006
  const props = value[PROPS_MARKER];
2242
- // Handle built-in types
2243
- if (class_name === 'Date') {
2244
- return new Date(props);
2245
- }
2246
- if (class_name === 'Map') {
2247
- const map = new Map();
2248
- for (const [k, v] of props) {
2249
- map.set(process_for_deserialization(k, verbose), process_for_deserialization(v, verbose));
2250
- }
2251
- return map;
2252
- }
2253
- if (class_name === 'Set') {
2254
- const set = new Set();
2255
- for (const item of props) {
2256
- set.add(process_for_deserialization(item, verbose));
2257
- }
2258
- return set;
2259
- }
2260
- // Look up registered class
2261
- const klass = class_registry[class_name];
2262
- if (!klass) {
2007
+ // Look up registered class (Date, Map and Set are registered like any other)
2008
+ const entry = class_registry[class_name];
2009
+ if (!entry) {
2263
2010
  if (verbose) {
2264
2011
  console.warn(`[JQHTML Cache] Cannot restore class "${class_name}" - not registered. ` +
2265
2012
  `Data will be returned as plain object. ` +
@@ -2268,10 +2015,14 @@ function process_for_deserialization(value, verbose) {
2268
2015
  // Return as plain object rather than failing completely
2269
2016
  return process_for_deserialization(props, verbose);
2270
2017
  }
2271
- // Create instance without calling constructor and assign properties
2018
+ // Restore through from_plain when the class has one; otherwise create an
2019
+ // instance without calling the constructor and assign the properties back.
2272
2020
  try {
2273
- const instance = Object.create(klass.prototype);
2274
2021
  const processed_props = process_for_deserialization(props, verbose);
2022
+ if (entry.from_plain) {
2023
+ return entry.from_plain(processed_props);
2024
+ }
2025
+ const instance = Object.create(entry.klass.prototype);
2275
2026
  Object.assign(instance, processed_props);
2276
2027
  return instance;
2277
2028
  }
@@ -2279,355 +2030,689 @@ function process_for_deserialization(value, verbose) {
2279
2030
  if (verbose) {
2280
2031
  console.warn(`[JQHTML Cache] Failed to restore class "${class_name}":`, e);
2281
2032
  }
2282
- // Return null to signal cache should be treated as miss
2283
- return null;
2033
+ // Return null to signal cache should be treated as miss
2034
+ return null;
2035
+ }
2036
+ }
2037
+ // Plain object - process recursively
2038
+ const result = {};
2039
+ for (const key of Object.keys(value)) {
2040
+ result[key] = process_for_deserialization(value[key], verbose);
2041
+ }
2042
+ return result;
2043
+ }
2044
+ class Jqhtml_Local_Storage {
2045
+ /**
2046
+ * Set the cache key and initialize storage
2047
+ * Must be called before any get/set operations
2048
+ * @param {string} cache_key - Unique identifier for this cache scope
2049
+ * @param {CacheMode} cache_mode - Cache strategy: 'data' (default, recommended) or 'html'
2050
+ */
2051
+ static set_cache_key(cache_key, cache_mode = 'data') {
2052
+ this._cache_key = cache_key;
2053
+ // Key SHAPE is a function of the library (see cache-key-serializer.ts), so an
2054
+ // upgrade that changes it must invalidate everything persisted under the old shape.
2055
+ // Version the SCOPE MARKER rather than the key itself: _validate_scope() already
2056
+ // clears every jqhtml key when this value changes, and leaving the per-entry key
2057
+ // format alone keeps stored keys readable and avoids repeating the version in each.
2058
+ this._scope_marker = `${CORE_VERSION}::${cache_key}`;
2059
+ this._cache_mode = cache_mode;
2060
+ this._init();
2061
+ }
2062
+ /**
2063
+ * Check if cache key has been set
2064
+ * @returns {boolean} True if cache key is configured
2065
+ */
2066
+ static has_cache_key() {
2067
+ return this._cache_key !== null;
2068
+ }
2069
+ /**
2070
+ * Get the current cache mode
2071
+ * @returns {CacheMode} Current cache mode ('data' or 'html')
2072
+ */
2073
+ static get_cache_mode() {
2074
+ return this._cache_mode;
2075
+ }
2076
+ /**
2077
+ * Initialize storage system and validate scope
2078
+ * Called automatically after cache key is set
2079
+ * @private
2080
+ */
2081
+ static _init() {
2082
+ // Check storage availability
2083
+ if (this._storage_available === null) {
2084
+ this._storage_available = this._is_storage_available();
2085
+ }
2086
+ if (!this._storage_available || !this._cache_key) {
2087
+ return;
2088
+ }
2089
+ // Validate scope
2090
+ this._validate_scope();
2091
+ this._initialized = true;
2092
+ }
2093
+ /**
2094
+ * Check if localStorage is available
2095
+ * @returns {boolean}
2096
+ * @private
2097
+ */
2098
+ static _is_storage_available() {
2099
+ try {
2100
+ const storage = window.localStorage;
2101
+ const test = '__jqhtml_storage_test__';
2102
+ storage.setItem(test, test);
2103
+ storage.removeItem(test);
2104
+ return true;
2105
+ }
2106
+ catch (e) {
2107
+ return false;
2108
+ }
2109
+ }
2110
+ /**
2111
+ * Check if verbose mode is enabled
2112
+ * @private
2113
+ */
2114
+ static _is_verbose() {
2115
+ return window.jqhtml?.debug?.verbose === true;
2116
+ }
2117
+ /**
2118
+ * Validate storage scope and clear JQHTML keys if cache key changed
2119
+ * Only clears keys prefixed with 'jqhtml::' to preserve other libraries' data
2120
+ * @private
2121
+ */
2122
+ static _validate_scope() {
2123
+ if (!this._storage_available) {
2124
+ return;
2125
+ }
2126
+ try {
2127
+ const stored_key = localStorage.getItem('_jqhtml_cache_key');
2128
+ // If the scope marker (core version + developer key) changed, clear only JQHTML keys
2129
+ if (stored_key !== null && stored_key !== this._scope_marker) {
2130
+ console.log('[JQHTML Local Storage] Cache scope changed, clearing JQHTML keys:', {
2131
+ old_key: stored_key,
2132
+ new_key: this._scope_marker,
2133
+ });
2134
+ this._clear_jqhtml_keys();
2135
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2136
+ }
2137
+ else if (stored_key === null) {
2138
+ // First time JQHTML is using this storage - just set the key, don't clear
2139
+ console.log('[JQHTML Local Storage] Initializing cache scope (first use):', {
2140
+ new_key: this._scope_marker,
2141
+ });
2142
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2143
+ }
2144
+ }
2145
+ catch (e) {
2146
+ console.error('[JQHTML Local Storage] Failed to validate scope:', e);
2147
+ }
2148
+ }
2149
+ /**
2150
+ * Clear only JQHTML keys from storage (keys starting with 'jqhtml::')
2151
+ * Preserves keys from other libraries
2152
+ * @private
2153
+ */
2154
+ static _clear_jqhtml_keys() {
2155
+ if (!this._storage_available) {
2156
+ return;
2157
+ }
2158
+ const keys_to_remove = [];
2159
+ // Collect all JQHTML keys
2160
+ for (let i = 0; i < localStorage.length; i++) {
2161
+ const key = localStorage.key(i);
2162
+ if (key && key.startsWith('jqhtml::')) {
2163
+ keys_to_remove.push(key);
2164
+ }
2165
+ }
2166
+ // Remove collected keys
2167
+ keys_to_remove.forEach(key => {
2168
+ try {
2169
+ localStorage.removeItem(key);
2170
+ }
2171
+ catch (e) {
2172
+ console.error('[JQHTML Local Storage] Failed to remove key:', key, e);
2173
+ }
2174
+ });
2175
+ console.log(`[JQHTML Local Storage] Cleared ${keys_to_remove.length} JQHTML keys`);
2176
+ }
2177
+ /**
2178
+ * Build scoped key with JQHTML namespace prefix
2179
+ * @param {string} key - Developer-provided key
2180
+ * @returns {string}
2181
+ * @private
2182
+ */
2183
+ static _build_key(key) {
2184
+ return `jqhtml::${key}::${this._cache_key}`;
2185
+ }
2186
+ /**
2187
+ * Check if storage is ready for use
2188
+ * @returns {boolean}
2189
+ * @private
2190
+ */
2191
+ static _is_ready() {
2192
+ return this._storage_available === true && this._cache_key !== null && this._initialized;
2193
+ }
2194
+ /**
2195
+ * Set item in localStorage with class-aware serialization.
2196
+ *
2197
+ * If serialization fails (e.g., unregistered class instances, circular refs),
2198
+ * the existing cache entry is removed and nothing is stored.
2199
+ *
2200
+ * @param {string} key - Storage key
2201
+ * @param {*} value - Value to store (primitives, objects, arrays, or registered class instances)
2202
+ */
2203
+ static set(key, value) {
2204
+ if (!this._is_ready()) {
2205
+ return;
2206
+ }
2207
+ const verbose = this._is_verbose();
2208
+ const scoped_key = this._build_key(key);
2209
+ // Serialize with class-aware processing
2210
+ const serialized = serialize_value(value, verbose);
2211
+ if (serialized === null) {
2212
+ // Serialization failed - remove any existing cache entry
2213
+ if (verbose) {
2214
+ console.warn(`[JQHTML Cache] Failed to serialize value for key "${key}". ` +
2215
+ `Removing existing cache entry if present.`);
2216
+ }
2217
+ try {
2218
+ localStorage.removeItem(scoped_key);
2219
+ }
2220
+ catch (e) {
2221
+ // Ignore removal errors
2222
+ }
2223
+ return;
2224
+ }
2225
+ // Check size before attempting to store (1MB limit)
2226
+ const size_bytes = new Blob([serialized]).size;
2227
+ const size_mb = size_bytes / (1024 * 1024);
2228
+ if (size_mb > 1) {
2229
+ if (verbose) {
2230
+ console.warn(`[JQHTML Cache] Skipping set - value too large (${size_mb.toFixed(2)}MB > 1MB limit)`, { key, size_bytes, size_mb });
2231
+ }
2232
+ // Remove existing cache entry since we can't update it
2233
+ try {
2234
+ localStorage.removeItem(scoped_key);
2235
+ }
2236
+ catch (e) {
2237
+ // Ignore removal errors
2238
+ }
2239
+ return;
2240
+ }
2241
+ this._set_item(key, serialized);
2242
+ }
2243
+ /**
2244
+ * Get item from localStorage with class-aware deserialization.
2245
+ *
2246
+ * If deserialization fails, returns null (as if no cache exists).
2247
+ *
2248
+ * @param {string} key - Storage key
2249
+ * @returns {*|null} Deserialized value with class instances restored, or null if not found/failed
2250
+ */
2251
+ static get(key) {
2252
+ if (!this._is_ready()) {
2253
+ return null;
2254
+ }
2255
+ const verbose = this._is_verbose();
2256
+ const scoped_key = this._build_key(key);
2257
+ try {
2258
+ const serialized = localStorage.getItem(scoped_key);
2259
+ if (serialized === null) {
2260
+ return null;
2261
+ }
2262
+ const result = deserialize_value(serialized, verbose);
2263
+ if (result === null) {
2264
+ // Deserialization failed - treat as cache miss
2265
+ if (verbose) {
2266
+ console.warn(`[JQHTML Cache] Failed to deserialize value for key "${key}". ` +
2267
+ `Treating as cache miss.`);
2268
+ }
2269
+ return null;
2270
+ }
2271
+ return result;
2272
+ }
2273
+ catch (e) {
2274
+ if (verbose) {
2275
+ console.warn('[JQHTML Cache] Failed to get item:', e);
2276
+ }
2277
+ return null;
2278
+ }
2279
+ }
2280
+ /**
2281
+ * Remove item from localStorage
2282
+ * @param {string} key - Storage key
2283
+ */
2284
+ static remove(key) {
2285
+ if (!this._is_ready()) {
2286
+ return;
2287
+ }
2288
+ this._remove_item(key);
2289
+ }
2290
+ /**
2291
+ * Serialize a value to its class-aware TEXT form - the same text set() stores.
2292
+ *
2293
+ * This is the copy-by-value primitive the rest of the framework uses whenever
2294
+ * data has to cross from one component to another (load-coordinator.ts hands a
2295
+ * leader's data to its followers through it). Plain JSON.stringify is not a
2296
+ * substitute: it consults toJSON() and produces a wire form that deserialize()
2297
+ * cannot recognise, so a registered class would come back as a plain object.
2298
+ *
2299
+ * @returns The text, or null when the value as a whole cannot be expressed.
2300
+ */
2301
+ static serialize(value) {
2302
+ return serialize_value(value, this._is_verbose());
2303
+ }
2304
+ /**
2305
+ * Rebuild a value from text produced by serialize(), restoring Date, Map, Set
2306
+ * and every register_cache_class() class. Returns null when the text is not
2307
+ * restorable (a registered from_plain threw at the root) - the same signal
2308
+ * get() gives for a corrupt entry.
2309
+ */
2310
+ static deserialize(text) {
2311
+ return deserialize_value(text, this._is_verbose());
2312
+ }
2313
+ /**
2314
+ * Perform a serialize/deserialize round-trip on a value.
2315
+ *
2316
+ * The result is ALWAYS jqhtml's own copy: nothing of the caller's object graph
2317
+ * is aliased through, and a value the serializer cannot express is dropped
2318
+ * rather than smuggled out. That is what makes `this.data` identical whether it
2319
+ * came from on_load() or from a cache hit - the old "on failure return the
2320
+ * original" branch broke exactly that promise, and only on the hard cases.
2321
+ *
2322
+ * @param {any} value - The value to normalize
2323
+ * @param {string} [component_name] - Names the component in development warnings.
2324
+ * Omit to convert silently (the unit tests and non-component callers).
2325
+ * @returns {any} The round-tripped value. Never the original object.
2326
+ */
2327
+ static normalize_for_cache(value, component_name) {
2328
+ const verbose = this._is_verbose();
2329
+ const collector = make_strip_collector(component_name);
2330
+ // Serialize to JSON string
2331
+ const serialized = serialize_value(value, verbose, 'this.data', collector);
2332
+ if (serialized === null) {
2333
+ // The value as a WHOLE could not be expressed (it was itself a function,
2334
+ // a promise, a DOM node...). The round trip of such a value is nothing;
2335
+ // returning the original would put an uncacheable object into this.data.
2336
+ return {};
2337
+ }
2338
+ // Deserialize back to object
2339
+ const deserialized = deserialize_value(serialized, verbose);
2340
+ // `null` from deserialize_value() is ambiguous: it means "failed", but a value
2341
+ // that legitimately serialized to the text `null` also comes back as null. The
2342
+ // serialized text disambiguates.
2343
+ if (deserialized === null && serialized !== 'null') {
2344
+ // Only reachable when a registered class constructor blew up on restore.
2345
+ return {};
2346
+ }
2347
+ return deserialized;
2348
+ }
2349
+ /**
2350
+ * Internal set implementation with scope validation and quota handling
2351
+ * @param {string} key
2352
+ * @param {string} serialized - Pre-serialized JSON string
2353
+ * @private
2354
+ */
2355
+ static _set_item(key, serialized) {
2356
+ // Validate scope before every write
2357
+ this._validate_scope();
2358
+ const scoped_key = this._build_key(key);
2359
+ try {
2360
+ localStorage.setItem(scoped_key, serialized);
2361
+ }
2362
+ catch (e) {
2363
+ // Check if quota exceeded
2364
+ if (e.name === 'QuotaExceededError' || e.code === 22) {
2365
+ console.warn('[JQHTML Local Storage] Quota exceeded, clearing JQHTML keys and retrying');
2366
+ // Clear only JQHTML keys and retry once
2367
+ this._clear_jqhtml_keys();
2368
+ // Re-stamp the SCOPE MARKER, not the raw developer key: _validate_scope()
2369
+ // compares against `${CORE_VERSION}::${key}`, so writing the bare key here
2370
+ // made the very next write look like a scope change and wipe the cache again.
2371
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2372
+ try {
2373
+ localStorage.setItem(scoped_key, serialized);
2374
+ }
2375
+ catch (retry_error) {
2376
+ console.error('[JQHTML Local Storage] Failed to set item after clearing JQHTML keys:', retry_error);
2377
+ }
2378
+ }
2379
+ else {
2380
+ console.error('[JQHTML Local Storage] Failed to set item:', e);
2381
+ }
2382
+ }
2383
+ }
2384
+ /**
2385
+ * Internal remove implementation
2386
+ * @param {string} key
2387
+ * @private
2388
+ */
2389
+ static _remove_item(key) {
2390
+ const scoped_key = this._build_key(key);
2391
+ try {
2392
+ localStorage.removeItem(scoped_key);
2393
+ }
2394
+ catch (e) {
2395
+ console.error('[JQHTML Local Storage] Failed to remove item:', e);
2396
+ }
2397
+ }
2398
+ }
2399
+ Jqhtml_Local_Storage._cache_key = null;
2400
+ /** Versioned scope identity - compared in _validate_scope() to clear on a core upgrade. */
2401
+ Jqhtml_Local_Storage._scope_marker = null;
2402
+ Jqhtml_Local_Storage._cache_mode = 'data';
2403
+ Jqhtml_Local_Storage._storage_available = null;
2404
+ Jqhtml_Local_Storage._initialized = false;
2405
+
2406
+ /**
2407
+ * Load Coordinator - Request deduplication for component on_load() calls
2408
+ *
2409
+ * Coordinates parallel component loading to prevent duplicate requests.
2410
+ * When multiple components with identical names and args load simultaneously,
2411
+ * only the first (leader) executes on_load(). Others (followers) wait for
2412
+ * the leader's result.
2413
+ *
2414
+ * Key Concepts:
2415
+ * - **INVOCATION_KEY**: Unique identifier for component name + args combination
2416
+ * - **Leader**: First component to reach on_load() for a given INVOCATION_KEY
2417
+ * - **Follower**: Subsequent components that wait for leader's result
2418
+ *
2419
+ * Lifecycle:
2420
+ * 1. Leader reaches on_load() → create coordination entry
2421
+ * 2. Followers reach on_load() → join waiting queue
2422
+ * 3. Leader completes → distribute data to all followers
2423
+ * 4. Clear coordination entry (no caching)
2424
+ *
2425
+ * The hand-off is a copy, and it is made by the cache serializer
2426
+ * (Jqhtml_Local_Storage.serialize()/deserialize()), never by JSON.stringify.
2427
+ * A follower never runs on_load() and never revalidates, so whatever it is
2428
+ * handed is final: the copy has to rebuild Date, Map, Set and every
2429
+ * register_cache_class() instance exactly as the leader's this.data holds them.
2430
+ * JSON.stringify would consult toJSON() and hand out a wire form that
2431
+ * normalize_for_cache() cannot recognise - the follower would then render
2432
+ * against plain objects while the leader renders against instances.
2433
+ *
2434
+ * @internal This class is not exposed in the public API
2435
+ */
2436
+ class Load_Coordinator {
2437
+ /**
2438
+ * Generate INVOCATION_KEY from component name and args
2439
+ * Uses deterministic JSON serialization (sorted keys)
2440
+ * Excludes internal properties (those starting with _)
2441
+ *
2442
+ * For functions/objects:
2443
+ * - Checks for ._jqhtml_cache_id property (assigned by RSpade)
2444
+ * - Falls back to .jqhtml_cache_id() method if property doesn't exist
2445
+ * - If neither exists, marks property as uncacheable
2446
+ *
2447
+ * Returns object with:
2448
+ * - key: Cache key string, or null if uncacheable
2449
+ * - uncacheable_property: Name of first property that prevented caching (for debugging)
2450
+ */
2451
+ static generate_invocation_key(component_name, args, options = {}) {
2452
+ let uncacheable_property;
2453
+ let uncacheable_reason;
2454
+ // Filter out internal properties (starting with _) and serialize args
2455
+ const serializable_args = {};
2456
+ for (const key of Object.keys(args).sort()) {
2457
+ if (key.startsWith('_')) {
2458
+ continue; // Skip internal properties
2459
+ }
2460
+ // Skip framework properties that shouldn't affect cache identity
2461
+ // Note: _load_only and _load_render_only are already filtered by the _ prefix check above
2462
+ if (key === 'use_cached_data') {
2463
+ continue;
2464
+ }
2465
+ const value = args[key];
2466
+ const value_type = typeof value;
2467
+ // Handle primitives (string, number, boolean, null, undefined)
2468
+ if (value === null || value === undefined ||
2469
+ value_type === 'string' || value_type === 'number' ||
2470
+ value_type === 'boolean') {
2471
+ serializable_args[key] = value;
2472
+ continue;
2473
+ }
2474
+ // Handle functions and objects
2475
+ if (value_type === 'function' || value_type === 'object') {
2476
+ // Check for ._jqhtml_cache_id property (fastest, what RSpade assigns)
2477
+ if (value._jqhtml_cache_id !== undefined) {
2478
+ serializable_args[key] = `__JQHTML_CACHE_ID__:${String(value._jqhtml_cache_id)}`;
2479
+ continue;
2480
+ }
2481
+ // Check for .jqhtml_cache_id() method (more flexible, for custom objects)
2482
+ if (typeof value.jqhtml_cache_id === 'function') {
2483
+ try {
2484
+ const cache_id = value.jqhtml_cache_id();
2485
+ serializable_args[key] = `__JQHTML_CACHE_ID__:${String(cache_id)}`;
2486
+ continue;
2487
+ }
2488
+ catch (error) {
2489
+ // Method threw error - treat as uncacheable
2490
+ if (!uncacheable_property) {
2491
+ uncacheable_property = key;
2492
+ uncacheable_reason = 'cache-id-threw';
2493
+ }
2494
+ return { key: null, uncacheable_property, uncacheable_reason };
2495
+ }
2496
+ }
2497
+ // No author-supplied id. The cache may fall back to keying by
2498
+ // deterministic content; deduplication deliberately may not.
2499
+ if (options.allow_content_serialization) {
2500
+ const serialized = serialize_for_cache_key(value);
2501
+ if (serialized.ok) {
2502
+ serializable_args[key] = `__JQHTML_CONTENT__:${serialized.text}`;
2503
+ continue;
2504
+ }
2505
+ if (!uncacheable_property) {
2506
+ uncacheable_property = key;
2507
+ // This package compiles with strictNullChecks off, and without it
2508
+ // TypeScript will not narrow a discriminated union by its boolean
2509
+ // discriminant - so `serialized` is still the full Serialize_Result
2510
+ // here even though `ok` has been ruled out above. The cast states
2511
+ // what the control flow already guarantees.
2512
+ uncacheable_reason = serialized.reason;
2513
+ }
2514
+ return { key: null, uncacheable_property, uncacheable_reason };
2515
+ }
2516
+ if (!uncacheable_property) {
2517
+ uncacheable_property = key;
2518
+ uncacheable_reason = value_type === 'function' ? 'function' : 'object';
2519
+ }
2520
+ return { key: null, uncacheable_property, uncacheable_reason };
2521
+ }
2522
+ // Unknown type (symbol, bigint, etc.) - uncacheable
2523
+ if (!uncacheable_property) {
2524
+ uncacheable_property = key;
2525
+ uncacheable_reason = value_type;
2526
+ }
2527
+ return { key: null, uncacheable_property, uncacheable_reason };
2284
2528
  }
2285
- }
2286
- // Plain object - process recursively
2287
- const result = {};
2288
- for (const key of Object.keys(value)) {
2289
- result[key] = process_for_deserialization(value[key], verbose);
2290
- }
2291
- return result;
2292
- }
2293
- class Jqhtml_Local_Storage {
2294
- /**
2295
- * Set the cache key and initialize storage
2296
- * Must be called before any get/set operations
2297
- * @param {string} cache_key - Unique identifier for this cache scope
2298
- * @param {CacheMode} cache_mode - Cache strategy: 'data' (default, recommended) or 'html'
2299
- */
2300
- static set_cache_key(cache_key, cache_mode = 'data') {
2301
- this._cache_key = cache_key;
2302
- // Key SHAPE is a function of the library (see cache-key-serializer.ts), so an
2303
- // upgrade that changes it must invalidate everything persisted under the old shape.
2304
- // Version the SCOPE MARKER rather than the key itself: _validate_scope() already
2305
- // clears every jqhtml key when this value changes, and leaving the per-entry key
2306
- // format alone keeps stored keys readable and avoids repeating the version in each.
2307
- this._scope_marker = `${CORE_VERSION}::${cache_key}`;
2308
- this._cache_mode = cache_mode;
2309
- this._init();
2310
- }
2311
- /**
2312
- * Check if cache key has been set
2313
- * @returns {boolean} True if cache key is configured
2314
- */
2315
- static has_cache_key() {
2316
- return this._cache_key !== null;
2317
- }
2318
- /**
2319
- * Get the current cache mode
2320
- * @returns {CacheMode} Current cache mode ('data' or 'html')
2321
- */
2322
- static get_cache_mode() {
2323
- return this._cache_mode;
2324
- }
2325
- /**
2326
- * Initialize storage system and validate scope
2327
- * Called automatically after cache key is set
2328
- * @private
2329
- */
2330
- static _init() {
2331
- // Check storage availability
2332
- if (this._storage_available === null) {
2333
- this._storage_available = this._is_storage_available();
2529
+ // Try to serialize - if it fails (shouldn't happen now, but safety net), return null
2530
+ try {
2531
+ const sorted_args = JSON.stringify(serializable_args);
2532
+ return { key: `${component_name}::${sorted_args}` };
2334
2533
  }
2335
- if (!this._storage_available || !this._cache_key) {
2336
- return;
2534
+ catch (error) {
2535
+ // Serialization failed unexpectedly
2536
+ return { key: null, uncacheable_property };
2337
2537
  }
2338
- // Validate scope
2339
- this._validate_scope();
2340
- this._initialized = true;
2341
2538
  }
2342
2539
  /**
2343
- * Check if localStorage is available
2344
- * @returns {boolean}
2345
- * @private
2540
+ * Check if a component should execute on_load() or wait for existing request
2541
+ * Returns true if component should execute (is leader), false if should wait (is follower)
2542
+ *
2543
+ * @param key - The dedup key the caller captured for this load. Every coordinator
2544
+ * method takes it, because args may legally change during on_load()
2545
+ * and a recomputed key would address a different (or no) entry.
2346
2546
  */
2347
- static _is_storage_available() {
2348
- try {
2349
- const storage = window.localStorage;
2350
- const test = '__jqhtml_storage_test__';
2351
- storage.setItem(test, test);
2352
- storage.removeItem(test);
2547
+ static should_execute_on_load(component, key) {
2548
+ const entry = this._registry.get(key);
2549
+ if (!entry) {
2550
+ // No existing request - this component becomes the leader
2353
2551
  return true;
2354
2552
  }
2355
- catch (e) {
2553
+ if (entry.status === 'loading') {
2554
+ // Request in progress - this component becomes a follower
2555
+ entry.waiting.push(component);
2356
2556
  return false;
2357
2557
  }
2558
+ // Entry exists but completed/failed - should have been cleaned up
2559
+ // Treat as new leader
2560
+ return true;
2358
2561
  }
2359
2562
  /**
2360
- * Check if verbose mode is enabled
2361
- * @private
2362
- */
2363
- static _is_verbose() {
2364
- return window.jqhtml?.debug?.verbose === true;
2365
- }
2366
- /**
2367
- * Validate storage scope and clear JQHTML keys if cache key changed
2368
- * Only clears keys prefixed with 'jqhtml::' to preserve other libraries' data
2369
- * @private
2370
- */
2371
- static _validate_scope() {
2372
- if (!this._storage_available) {
2373
- return;
2374
- }
2375
- try {
2376
- const stored_key = localStorage.getItem('_jqhtml_cache_key');
2377
- // If the scope marker (core version + developer key) changed, clear only JQHTML keys
2378
- if (stored_key !== null && stored_key !== this._scope_marker) {
2379
- console.log('[JQHTML Local Storage] Cache scope changed, clearing JQHTML keys:', {
2380
- old_key: stored_key,
2381
- new_key: this._scope_marker,
2382
- });
2383
- this._clear_jqhtml_keys();
2384
- localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2385
- }
2386
- else if (stored_key === null) {
2387
- // First time JQHTML is using this storage - just set the key, don't clear
2388
- console.log('[JQHTML Local Storage] Initializing cache scope (first use):', {
2389
- new_key: this._scope_marker,
2390
- });
2391
- localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2392
- }
2393
- }
2394
- catch (e) {
2395
- console.error('[JQHTML Local Storage] Failed to validate scope:', e);
2396
- }
2397
- }
2398
- /**
2399
- * Clear only JQHTML keys from storage (keys starting with 'jqhtml::')
2400
- * Preserves keys from other libraries
2401
- * @private
2563
+ * Register a leader component that will execute on_load()
2564
+ * Creates coordination entry and returns a function to call when data is ready
2565
+ *
2566
+ * @param key - The dedup key captured by the caller (see should_execute_on_load)
2567
+ * @returns A function that accepts the final data and completes coordination
2402
2568
  */
2403
- static _clear_jqhtml_keys() {
2404
- if (!this._storage_available) {
2405
- return;
2406
- }
2407
- const keys_to_remove = [];
2408
- // Collect all JQHTML keys
2409
- for (let i = 0; i < localStorage.length; i++) {
2410
- const key = localStorage.key(i);
2411
- if (key && key.startsWith('jqhtml::')) {
2412
- keys_to_remove.push(key);
2413
- }
2414
- }
2415
- // Remove collected keys
2416
- keys_to_remove.forEach(key => {
2417
- try {
2418
- localStorage.removeItem(key);
2419
- }
2420
- catch (e) {
2421
- console.error('[JQHTML Local Storage] Failed to remove key:', key, e);
2422
- }
2569
+ static register_leader(component, key) {
2570
+ // Create a promise that we control - it settles when coordination completes or fails
2571
+ let resolve_promise;
2572
+ let reject_promise;
2573
+ const coordination_promise = new Promise((resolve, reject) => {
2574
+ resolve_promise = resolve;
2575
+ reject_promise = reject;
2423
2576
  });
2424
- console.log(`[JQHTML Local Storage] Cleared ${keys_to_remove.length} JQHTML keys`);
2425
- }
2426
- /**
2427
- * Build scoped key with JQHTML namespace prefix
2428
- * @param {string} key - Developer-provided key
2429
- * @returns {string}
2430
- * @private
2431
- */
2432
- static _build_key(key) {
2433
- return `jqhtml::${key}::${this._cache_key}`;
2577
+ // A leader with no followers still has to be able to reject this promise on
2578
+ // error; without a handler that rejection surfaces as an unhandled rejection.
2579
+ coordination_promise.catch(() => { });
2580
+ const entry = {
2581
+ status: 'loading',
2582
+ promise: coordination_promise, // Followers await THIS promise, not on_load's
2583
+ resolve_promise,
2584
+ reject_promise,
2585
+ leader_component: component,
2586
+ leader_data: null,
2587
+ waiting: []
2588
+ };
2589
+ this._registry.set(key, entry);
2590
+ // Return cleanup function that accepts the final data
2591
+ return (final_data) => this._complete_coordination(key, component, final_data);
2434
2592
  }
2435
2593
  /**
2436
- * Check if storage is ready for use
2437
- * @returns {boolean}
2438
- * @private
2594
+ * Get the coordination promise for a follower component
2595
+ * Returns a promise that resolves when the leader completes, or rejects if it failed
2439
2596
  */
2440
- static _is_ready() {
2441
- return this._storage_available === true && this._cache_key !== null && this._initialized;
2597
+ static get_coordination_promise(key) {
2598
+ const entry = this._registry.get(key);
2599
+ if (!entry || entry.status !== 'loading') {
2600
+ return null;
2601
+ }
2602
+ return entry.promise;
2442
2603
  }
2443
2604
  /**
2444
- * Set item in localStorage with class-aware serialization.
2445
- *
2446
- * If serialization fails (e.g., unregistered class instances, circular refs),
2447
- * the existing cache entry is removed and nothing is stored.
2605
+ * Complete coordination after leader's on_load() finishes
2606
+ * Stores leader's data, marks entry as completed, and resolves the promise.
2607
+ * Followers retrieve the data themselves via get_leader_data().
2448
2608
  *
2449
- * @param {string} key - Storage key
2450
- * @param {*} value - Value to store (primitives, objects, arrays, or registered class instances)
2609
+ * @param key - The coordination key captured at registration
2610
+ * @param leader - The leader component
2611
+ * @param final_data - The final data after on_load and normalization
2612
+ * @private
2451
2613
  */
2452
- static set(key, value) {
2453
- if (!this._is_ready()) {
2454
- return;
2455
- }
2456
- const verbose = this._is_verbose();
2457
- const scoped_key = this._build_key(key);
2458
- // Serialize with class-aware processing
2459
- const serialized = serialize_value(value, verbose);
2460
- if (serialized === null) {
2461
- // Serialization failed - remove any existing cache entry
2462
- if (verbose) {
2463
- console.warn(`[JQHTML Cache] Failed to serialize value for key "${key}". ` +
2464
- `Removing existing cache entry if present.`);
2465
- }
2466
- try {
2467
- localStorage.removeItem(scoped_key);
2468
- }
2469
- catch (e) {
2470
- // Ignore removal errors
2471
- }
2614
+ static _complete_coordination(key, leader, final_data) {
2615
+ const entry = this._registry.get(key);
2616
+ if (!entry) {
2472
2617
  return;
2473
2618
  }
2474
- // Check size before attempting to store (1MB limit)
2475
- const size_bytes = new Blob([serialized]).size;
2476
- const size_mb = size_bytes / (1024 * 1024);
2477
- if (size_mb > 1) {
2478
- if (verbose) {
2479
- console.warn(`[JQHTML Cache] Skipping set - value too large (${size_mb.toFixed(2)}MB > 1MB limit)`, { key, size_bytes, size_mb });
2480
- }
2481
- // Remove existing cache entry since we can't update it
2482
- try {
2483
- localStorage.removeItem(scoped_key);
2484
- }
2485
- catch (e) {
2486
- // Ignore removal errors
2487
- }
2488
- return;
2619
+ // Stored as TEXT so each follower rebuilds its own object graph - sharing one
2620
+ // decoded object would let one component's mutation reach every other.
2621
+ // The cache serializer, not JSON.stringify: this.data holds live Date/Map/Set
2622
+ // and register_cache_class() instances, and only the serializer that made
2623
+ // them knows how to carry them across. null means the data as a whole could
2624
+ // not be expressed; followers then load independently.
2625
+ entry.leader_data = Jqhtml_Local_Storage.serialize(final_data);
2626
+ entry.status = 'completed';
2627
+ if (window.jqhtml?.debug?.verbose) {
2628
+ console.log(`[Load Coordinator] Leader ${leader._cid} completed, data available for ${entry.waiting.length} followers`, { key, data: entry.leader_data });
2629
+ }
2630
+ // Resolve the promise - followers waiting on it will now wake up
2631
+ entry.resolve_promise();
2632
+ // Nobody is waiting, so nothing will ever come back to collect the data.
2633
+ // Without this the registry grows once per distinct name+args, forever.
2634
+ if (entry.waiting.length === 0) {
2635
+ this._registry.delete(key);
2489
2636
  }
2490
- this._set_item(key, serialized);
2491
2637
  }
2492
2638
  /**
2493
- * Get item from localStorage with class-aware deserialization.
2494
- *
2495
- * If deserialization fails, returns null (as if no cache exists).
2639
+ * Get leader's data for a follower component
2640
+ * Called by follower after coordination promise resolves
2641
+ * Returns a freshly parsed copy and cleans up if this is the last follower
2496
2642
  *
2497
- * @param {string} key - Storage key
2498
- * @returns {*|null} Deserialized value with class instances restored, or null if not found/failed
2643
+ * @param key - The dedup key captured by the follower before it began waiting
2499
2644
  */
2500
- static get(key) {
2501
- if (!this._is_ready()) {
2645
+ static get_leader_data(component, key) {
2646
+ const entry = this._registry.get(key);
2647
+ if (!entry || entry.status !== 'completed' || entry.leader_data === null) {
2502
2648
  return null;
2503
2649
  }
2504
- const verbose = this._is_verbose();
2505
- const scoped_key = this._build_key(key);
2506
- try {
2507
- const serialized = localStorage.getItem(scoped_key);
2508
- if (serialized === null) {
2509
- return null;
2510
- }
2511
- const result = deserialize_value(serialized, verbose);
2512
- if (result === null) {
2513
- // Deserialization failed - treat as cache miss
2514
- if (verbose) {
2515
- console.warn(`[JQHTML Cache] Failed to deserialize value for key "${key}". ` +
2516
- `Treating as cache miss.`);
2517
- }
2518
- return null;
2519
- }
2520
- return result;
2650
+ // Remove this follower from the waiting list
2651
+ const follower_index = entry.waiting.indexOf(component);
2652
+ if (follower_index !== -1) {
2653
+ entry.waiting.splice(follower_index, 1);
2521
2654
  }
2522
- catch (e) {
2523
- if (verbose) {
2524
- console.warn('[JQHTML Cache] Failed to get item:', e);
2525
- }
2526
- return null;
2655
+ // One deserialize per follower: each gets its OWN object graph, never a
2656
+ // shared reference, with the same instances the leader's this.data holds.
2657
+ const data = Jqhtml_Local_Storage.deserialize(entry.leader_data);
2658
+ if (window.jqhtml?.debug?.verbose) {
2659
+ console.log(`[Load Coordinator] Follower ${component._cid} retrieving data from leader ${entry.leader_component._cid}`, { key, remaining_followers: entry.waiting.length });
2527
2660
  }
2528
- }
2529
- /**
2530
- * Remove item from localStorage
2531
- * @param {string} key - Storage key
2532
- */
2533
- static remove(key) {
2534
- if (!this._is_ready()) {
2535
- return;
2661
+ // If this was the last follower, clean up the entry
2662
+ if (entry.waiting.length === 0) {
2663
+ this._registry.delete(key);
2664
+ if (window.jqhtml?.debug?.verbose) {
2665
+ console.log(`[Load Coordinator] Coordination complete for key: ${key}`, { registry_size: this._registry.size });
2666
+ }
2536
2667
  }
2537
- this._remove_item(key);
2668
+ return data;
2538
2669
  }
2539
2670
  /**
2540
- * Perform a serialize/deserialize round-trip on a value.
2541
- *
2542
- * The result is ALWAYS jqhtml's own copy: nothing of the caller's object graph
2543
- * is aliased through, and a value the serializer cannot express is dropped
2544
- * rather than smuggled out. That is what makes `this.data` identical whether it
2545
- * came from on_load() or from a cache hit - the old "on failure return the
2546
- * original" branch broke exactly that promise, and only on the hard cases.
2671
+ * Handle leader on_load() error
2672
+ * Rejects every waiting follower and clears the entry so the next component retries
2547
2673
  *
2548
- * @param {any} value - The value to normalize
2549
- * @param {string} [component_name] - Names the component in development warnings.
2550
- * Omit to convert silently (the unit tests and non-component callers).
2551
- * @returns {any} The round-tripped value. Never the original object.
2674
+ * @param key - The dedup key captured at registration
2552
2675
  */
2553
- static normalize_for_cache(value, component_name) {
2554
- const verbose = this._is_verbose();
2555
- const collector = make_strip_collector(component_name);
2556
- // Serialize to JSON string
2557
- const serialized = serialize_value(value, verbose, 'this.data', collector);
2558
- if (serialized === null) {
2559
- // The value as a WHOLE could not be expressed (it was itself a function,
2560
- // a promise, a DOM node...). The round trip of such a value is nothing;
2561
- // returning the original would put an uncacheable object into this.data.
2562
- return {};
2676
+ static handle_leader_error(key, error) {
2677
+ const entry = this._registry.get(key);
2678
+ if (!entry) {
2679
+ return;
2563
2680
  }
2564
- // Deserialize back to object
2565
- const deserialized = deserialize_value(serialized, verbose);
2566
- // `null` from deserialize_value() is ambiguous: it means "failed", but a value
2567
- // that legitimately serialized to the text `null` also comes back as null. The
2568
- // serialized text disambiguates.
2569
- if (deserialized === null && serialized !== 'null') {
2570
- // Only reachable when a registered class constructor blew up on restore.
2571
- return {};
2681
+ entry.status = 'failed';
2682
+ console.error(`[Load Coordinator] Leader ${entry.leader_component._cid} on_load() failed for key: ${key}`, error);
2683
+ // Reject FIRST: followers are parked on this promise and their catch in _load()
2684
+ // propagates the failure exactly as if their own on_load() had thrown. Deleting
2685
+ // without rejecting left them awaiting a promise nobody could ever settle.
2686
+ entry.reject_promise(error);
2687
+ // Clear coordination entry so future requests can retry
2688
+ this._registry.delete(key);
2689
+ if (window.jqhtml?.debug?.verbose) {
2690
+ console.log(`[Load Coordinator] Cleared failed coordination for key: ${key}`, { followers_count: entry.waiting.length });
2572
2691
  }
2573
- return deserialized;
2574
2692
  }
2575
2693
  /**
2576
- * Internal set implementation with scope validation and quota handling
2577
- * @param {string} key
2578
- * @param {string} serialized - Pre-serialized JSON string
2579
- * @private
2694
+ * Get current registry state (for debugging)
2580
2695
  */
2581
- static _set_item(key, serialized) {
2582
- // Validate scope before every write
2583
- this._validate_scope();
2584
- const scoped_key = this._build_key(key);
2585
- try {
2586
- localStorage.setItem(scoped_key, serialized);
2587
- }
2588
- catch (e) {
2589
- // Check if quota exceeded
2590
- if (e.name === 'QuotaExceededError' || e.code === 22) {
2591
- console.warn('[JQHTML Local Storage] Quota exceeded, clearing JQHTML keys and retrying');
2592
- // Clear only JQHTML keys and retry once
2593
- this._clear_jqhtml_keys();
2594
- // Re-stamp the SCOPE MARKER, not the raw developer key: _validate_scope()
2595
- // compares against `${CORE_VERSION}::${key}`, so writing the bare key here
2596
- // made the very next write look like a scope change and wipe the cache again.
2597
- localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
2598
- try {
2599
- localStorage.setItem(scoped_key, serialized);
2600
- }
2601
- catch (retry_error) {
2602
- console.error('[JQHTML Local Storage] Failed to set item after clearing JQHTML keys:', retry_error);
2603
- }
2604
- }
2605
- else {
2606
- console.error('[JQHTML Local Storage] Failed to set item:', e);
2607
- }
2696
+ static get_registry_state() {
2697
+ const state = {};
2698
+ for (const [key, entry] of this._registry.entries()) {
2699
+ state[key] = {
2700
+ status: entry.status,
2701
+ leader_cid: entry.leader_component._cid,
2702
+ waiting_count: entry.waiting.length,
2703
+ waiting_cids: entry.waiting.map(c => c._cid)
2704
+ };
2608
2705
  }
2706
+ return state;
2609
2707
  }
2610
2708
  /**
2611
- * Internal remove implementation
2612
- * @param {string} key
2613
- * @private
2709
+ * Clear all coordination entries (for testing/debugging)
2614
2710
  */
2615
- static _remove_item(key) {
2616
- const scoped_key = this._build_key(key);
2617
- try {
2618
- localStorage.removeItem(scoped_key);
2619
- }
2620
- catch (e) {
2621
- console.error('[JQHTML Local Storage] Failed to remove item:', e);
2622
- }
2711
+ static clear_all() {
2712
+ this._registry.clear();
2623
2713
  }
2624
2714
  }
2625
- Jqhtml_Local_Storage._cache_key = null;
2626
- /** Versioned scope identity - compared in _validate_scope() to clear on a core upgrade. */
2627
- Jqhtml_Local_Storage._scope_marker = null;
2628
- Jqhtml_Local_Storage._cache_mode = 'data';
2629
- Jqhtml_Local_Storage._storage_available = null;
2630
- Jqhtml_Local_Storage._initialized = false;
2715
+ Load_Coordinator._registry = new Map();
2631
2716
 
2632
2717
  /**
2633
2718
  * JQHTML Component Event System
@@ -3089,6 +3174,85 @@ async function execute_on_load_detached(component, dedup_key = null) {
3089
3174
  };
3090
3175
  }
3091
3176
 
3177
+ /**
3178
+ * JQHTML DOM Attachment Tracking
3179
+ *
3180
+ * Backs the component 'attach' / 'detach' lifecycle events.
3181
+ *
3182
+ * One document-level MutationObserver (childList + subtree) is installed the first
3183
+ * time any component expresses interest in attachment, and disconnected when the
3184
+ * last interested component is stopped or collected. The observer never inspects
3185
+ * mutation records: it is only a "the tree changed" tick. On each batch it walks
3186
+ * the tracked components and asks each to compare its root's isConnected against
3187
+ * its own recorded attachment state (Jqhtml_Component._attachment_check()). Cost is
3188
+ * O(tracked components) per mutation batch, independent of how much of the page
3189
+ * changed, and zero when nothing has opted in.
3190
+ *
3191
+ * Because MutationObserver delivers per microtask, a node moved synchronously
3192
+ * (remove + insert in one task, e.g. appendTo) never shows a transition. Only a
3193
+ * component whose root is actually off-document when the batch flushes is detached.
3194
+ *
3195
+ * Tracked components are held by WeakRef. A component that is removed from the
3196
+ * document natively (never stopped) and then dropped by everything else is therefore
3197
+ * collectable: the tracker pins nothing. Dead refs are pruned on the next batch.
3198
+ */
3199
+ const tracked = new Set();
3200
+ const ref_of = new WeakMap();
3201
+ let observer = null;
3202
+ function on_mutation() {
3203
+ for (const ref of tracked) {
3204
+ const component = ref.deref();
3205
+ if (!component || component._stopped) {
3206
+ tracked.delete(ref);
3207
+ continue;
3208
+ }
3209
+ component._attachment_check();
3210
+ }
3211
+ if (tracked.size === 0)
3212
+ disconnect();
3213
+ }
3214
+ function connect() {
3215
+ if (observer !== null)
3216
+ return;
3217
+ if (typeof MutationObserver === 'undefined' || typeof document === 'undefined')
3218
+ return;
3219
+ observer = new MutationObserver(on_mutation);
3220
+ observer.observe(document.documentElement, { childList: true, subtree: true });
3221
+ }
3222
+ function disconnect() {
3223
+ if (observer === null)
3224
+ return;
3225
+ observer.disconnect();
3226
+ observer = null;
3227
+ }
3228
+ /** Start watching a component's root for attach/detach transitions. Idempotent. */
3229
+ function track_attachment(component) {
3230
+ if (ref_of.has(component))
3231
+ return;
3232
+ const ref = new WeakRef(component);
3233
+ ref_of.set(component, ref);
3234
+ tracked.add(ref);
3235
+ connect();
3236
+ }
3237
+ /** Stop watching a component (called from _stop()). Idempotent. */
3238
+ function untrack_attachment(component) {
3239
+ const ref = ref_of.get(component);
3240
+ if (!ref)
3241
+ return;
3242
+ ref_of.delete(component);
3243
+ tracked.delete(ref);
3244
+ if (tracked.size === 0)
3245
+ disconnect();
3246
+ }
3247
+ /** Number of components currently tracked (diagnostics / tests). */
3248
+ function tracked_attachment_count() {
3249
+ return tracked.size;
3250
+ }
3251
+ /** Whether the document observer is currently installed (diagnostics / tests). */
3252
+ function attachment_observer_active() {
3253
+ return observer !== null;
3254
+ }
3255
+
3092
3256
  /**
3093
3257
  * JQHTML Component Cache Integration
3094
3258
  *
@@ -3997,6 +4161,12 @@ class Jqhtml_Component {
3997
4161
  this.__load_gates = []; // Pending gates (cleared once the first load begins)
3998
4162
  this.__first_load_started = false; // Latch: true once the first load phase begins (enforces one-shot + throw-after)
3999
4163
  this.__gate_resume = null; // Resolver to release an in-progress gate wait early (reload/refresh/stop)
4164
+ // DOM attachment state machine - see _attachment_check() / dom-attachment.ts.
4165
+ // _attached is the component's OWN belief about whether it is in the document;
4166
+ // it flips at most once per direction, and 'attach' / 'detach' fire only on a flip.
4167
+ this._attached = false;
4168
+ this._attachment_checked = false; // First check has run (after the first 'ready' dispatch)
4169
+ this._attachment_tracking = false; // Something is interested: on_attach/on_detach overridden, or .on('attach'|'detach')
4000
4170
  // Detect custom on_load() override immediately
4001
4171
  // Prototype chain is set up before constructor runs, so this.on_load
4002
4172
  // correctly resolves to child class override if one exists
@@ -4070,6 +4240,12 @@ class Jqhtml_Component {
4070
4240
  // Initialize this.state as an empty object (convention for arbitrary component state)
4071
4241
  // No special meaning to framework - mutable anywhere, not cached, not frozen
4072
4242
  this.state = {};
4243
+ // Overriding on_attach()/on_detach() is interest in attachment tracking. Tracking
4244
+ // itself only starts after the first 'ready' dispatch (see _attachment_check()).
4245
+ if (this.on_attach !== Jqhtml_Component.prototype.on_attach ||
4246
+ this.on_detach !== Jqhtml_Component.prototype.on_detach) {
4247
+ this._attachment_tracking = true;
4248
+ }
4073
4249
  this._log_lifecycle('construct', 'complete');
4074
4250
  }
4075
4251
  /**
@@ -4083,7 +4259,9 @@ class Jqhtml_Component {
4083
4259
  on_render: 'Use render() to trigger a re-render.',
4084
4260
  on_load: 'Use reload() to refresh data.',
4085
4261
  on_ready: 'Called automatically when ready.',
4086
- on_stop: 'Use stop() to stop the component.'
4262
+ on_stop: 'Use stop() to stop the component.',
4263
+ on_attach: 'Called automatically when the component enters the document.',
4264
+ on_detach: 'Called automatically when the component leaves the document.'
4087
4265
  };
4088
4266
  const impls = {};
4089
4267
  const self = this;
@@ -5437,8 +5615,13 @@ class Jqhtml_Component {
5437
5615
  // stopped children into the parent's registry.
5438
5616
  this._log_lifecycle('destroy', 'start');
5439
5617
  this.$.addClass('_Component_Stopped');
5440
- // Unregister from lifecycle manager
5441
- this._lifecycle_manager.unregister_component(this);
5618
+ // A component that believes it is attached is detached first, so 'detach' always
5619
+ // precedes 'stop' and subscribers can rely on strict attach/detach alternation.
5620
+ // A component that never fired 'attach' (stopped before ready, or born and kept
5621
+ // off-document) fires no 'detach' either. Either way it leaves the tracker.
5622
+ if (this._attached)
5623
+ this._transition_attachment(false);
5624
+ untrack_attachment(this);
5442
5625
  // Call user's on_stop() hook with authorization (sync) - only when actually
5443
5626
  // overridden, since _call_lifecycle_sync() on the base no-op costs per child
5444
5627
  // on every re-render.
@@ -5483,6 +5666,89 @@ class Jqhtml_Component {
5483
5666
  on_loaded() { } // Override to process loaded data (e.g., clone this.data to this.state)
5484
5667
  async on_ready() { }
5485
5668
  on_stop() { }
5669
+ on_attach() { } // Sync. Root entered the document (first checked after 'ready')
5670
+ on_detach() { } // Sync. Root left the document, or the component is being stopped while attached
5671
+ // -------------------------------------------------------------------------
5672
+ // DOM attachment state machine
5673
+ // -------------------------------------------------------------------------
5674
+ /**
5675
+ * Whether this component currently considers itself attached to the document.
5676
+ *
5677
+ * This is the component's recorded state, not a live isConnected read: it is
5678
+ * false until the first check after 'ready', and from then on flips only when a
5679
+ * transition is observed (or on stop()). It is exactly the state 'attach' and
5680
+ * 'detach' have reported.
5681
+ */
5682
+ is_attached() {
5683
+ return this._attached;
5684
+ }
5685
+ /**
5686
+ * Flip the recorded state and fire the matching hook + event. The opposite
5687
+ * sticky event is invalidated first, so a late subscriber only ever sees the
5688
+ * current state. Hook errors are isolated; the event still fires.
5689
+ * @private
5690
+ */
5691
+ _transition_attachment(attached) {
5692
+ this._attached = attached;
5693
+ const event_name = attached ? 'attach' : 'detach';
5694
+ const hook_name = attached ? 'on_attach' : 'on_detach';
5695
+ this.invalidate(attached ? 'detach' : 'attach');
5696
+ if (this[hook_name] !== Jqhtml_Component.prototype[hook_name]) {
5697
+ try {
5698
+ const result = this._call_lifecycle_sync(hook_name);
5699
+ if (result && typeof result.then === 'function') {
5700
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from ${hook_name}(). ` +
5701
+ `${hook_name}() must be synchronous code. Remove 'async' from the function declaration.`);
5702
+ }
5703
+ }
5704
+ catch (error) {
5705
+ console.error(`[JQHTML] Error in ${hook_name}() for ${this.component_name()}:`, error);
5706
+ }
5707
+ }
5708
+ this.trigger(event_name);
5709
+ }
5710
+ /**
5711
+ * Compare the root's live connectivity with the recorded state and transition
5712
+ * on a difference. Idempotent. Called by the document observer on every
5713
+ * mutation batch for tracked components, and directly by the framework after
5714
+ * 'ready' and when interest is registered late.
5715
+ * @private
5716
+ */
5717
+ _attachment_check() {
5718
+ if (this._stopped)
5719
+ return;
5720
+ const connected = !!this.$[0].isConnected;
5721
+ if (connected !== this._attached)
5722
+ this._transition_attachment(connected);
5723
+ }
5724
+ /**
5725
+ * The first check, run once the 'ready' handlers have completed. Fires 'attach'
5726
+ * if the component was born attached, even with no listener, so a later
5727
+ * .on('attach') gets the sticky fire. Deferred interest starts tracking here.
5728
+ * @private
5729
+ */
5730
+ _attachment_first_check() {
5731
+ const first = !this._attachment_checked;
5732
+ this._attachment_checked = true;
5733
+ this._attachment_check();
5734
+ if (first && this._attachment_tracking)
5735
+ track_attachment(this);
5736
+ }
5737
+ /**
5738
+ * Register interest in attach/detach. Before the first ready check this only
5739
+ * records the interest; after it, tracking starts immediately and a check runs
5740
+ * at once, so a late subscriber on a natively-removed component sees 'detach'.
5741
+ * @private
5742
+ */
5743
+ _watch_attachment() {
5744
+ if (this._attachment_tracking)
5745
+ return;
5746
+ this._attachment_tracking = true;
5747
+ if (this._attachment_checked && !this._stopped) {
5748
+ track_attachment(this);
5749
+ this._attachment_check();
5750
+ }
5751
+ }
5486
5752
  /**
5487
5753
  * Called with the viewport width in CSS pixels:
5488
5754
  * - after every on_render()
@@ -5547,6 +5813,8 @@ class Jqhtml_Component {
5547
5813
  * @see component-events.ts for full documentation
5548
5814
  */
5549
5815
  on(event_name, callback) {
5816
+ if (event_name === 'attach' || event_name === 'detach')
5817
+ this._watch_attachment();
5550
5818
  return event_on(this, event_name, callback);
5551
5819
  }
5552
5820
  /**
@@ -5555,14 +5823,24 @@ class Jqhtml_Component {
5555
5823
  * @see component-events.ts for full documentation
5556
5824
  */
5557
5825
  once(event_name, callback) {
5826
+ if (event_name === 'attach' || event_name === 'detach')
5827
+ this._watch_attachment();
5558
5828
  return event_once(this, event_name, callback);
5559
5829
  }
5560
5830
  /**
5561
5831
  * Trigger a lifecycle event - delegates to component-events.ts
5562
5832
  * @see component-events.ts for full documentation
5833
+ *
5834
+ * 'ready' is special: once its handlers have run, the component runs its first
5835
+ * attachment check (and every later one, idempotently). Doing it here rather than
5836
+ * at each of the call sites that trigger 'ready' guarantees the order
5837
+ * on_ready() -> 'ready' handlers -> 'attach', so everything on_ready() set up is
5838
+ * complete before anyone learns the component is in the document.
5563
5839
  */
5564
5840
  trigger(event_name, data) {
5565
5841
  event_trigger(this, event_name, data);
5842
+ if (event_name === 'ready' && !this._stopped)
5843
+ this._attachment_first_check();
5566
5844
  }
5567
5845
  /**
5568
5846
  * Check if any callbacks are registered for a given event
@@ -6996,9 +7274,42 @@ function init_jquery_plugin(jQuery) {
6996
7274
  return jQuery(results);
6997
7275
  };
6998
7276
  // Store original jQuery methods
6999
- const originalEmpty = jQuery.fn.empty;
7000
7277
  const originalHtml = jQuery.fn.html;
7001
- const originalText = jQuery.fn.text;
7278
+ // ---------------------------------------------------------------------------
7279
+ // Stop components on every jQuery-driven removal by hooking jQuery.cleanData.
7280
+ //
7281
+ // jQuery routes .remove(), .empty(), .html(x), .text(x), .replaceWith() and
7282
+ // .replaceAll() through jQuery.cleanData(elems) to drop the data store and
7283
+ // handlers of every element about to leave the tree - and `elems` is already the
7284
+ // flattened subtree, in document order (parent before child). Stopping here is
7285
+ // therefore one classList check per removed element, no extra traversal, and
7286
+ // covers every jQuery removal path at once. It is the same hook jQuery UI's
7287
+ // widget factory uses for the same reason.
7288
+ //
7289
+ // It MUST be installed on the original jQuery object: jQuery's own code calls
7290
+ // cleanData through its closure-local reference, not through our wrapper. The
7291
+ // wrapper's copied static is updated below so both names agree.
7292
+ //
7293
+ // .detach() does NOT call cleanData, by jQuery's own design (it keeps data for
7294
+ // reinsertion), and native DOM removal (el.remove(), innerHTML = '') bypasses
7295
+ // jQuery entirely. Neither stops a component; the 'detach' lifecycle event is
7296
+ // the signal for those. Moving a component (.appendTo) is not a removal.
7297
+ // ---------------------------------------------------------------------------
7298
+ const originalCleanData = _jqhtml_original_jquery.cleanData;
7299
+ const cleanDataWithComponentStop = function (elems) {
7300
+ for (let i = 0; i < elems.length; i++) {
7301
+ const el = elems[i];
7302
+ if (el.nodeType !== 1 || !el.classList.contains('Component'))
7303
+ continue;
7304
+ const component = _jqhtml_original_jquery.data(el, '_component');
7305
+ if (component && !component._stopped) {
7306
+ component._stop(); // Not recursive: every descendant is in elems too
7307
+ }
7308
+ }
7309
+ return originalCleanData(elems);
7310
+ };
7311
+ _jqhtml_original_jquery.cleanData = cleanDataWithComponentStop;
7312
+ jQuery.cleanData = cleanDataWithComponentStop;
7002
7313
  // ---------------------------------------------------------------------------
7003
7314
  // Guard against hand-creating elements with data-sid via jQuery.
7004
7315
  //
@@ -7055,53 +7366,15 @@ function init_jquery_plugin(jQuery) {
7055
7366
  ` • <div class="MyComponent__${sid}"> → .find('.MyComponent__${sid}')`);
7056
7367
  };
7057
7368
  /**
7058
- * Override jQuery.fn.empty() to stop child components before clearing DOM
7059
- * This ensures component cleanup hooks fire when DOM is cleared
7060
- */
7061
- jQuery.fn.empty = function () {
7062
- return this.each(function () {
7063
- // Stop all child components before clearing DOM
7064
- jQuery(this).find('.Component').each(function () {
7065
- const component = jQuery(this).data('_component');
7066
- if (component && !component._stopped) {
7067
- component._stop(); // Stop just the component, DOM will be cleared anyway
7068
- }
7069
- });
7070
- // Call original empty
7071
- originalEmpty.call(jQuery(this));
7072
- });
7073
- };
7074
- /**
7075
- * Override jQuery.fn.html() to stop child components when setting new content
7076
- * When used as setter, calls .empty() first to properly cleanup components
7369
+ * Override jQuery.fn.html() setter to reject hand-written data-sid before the
7370
+ * DOM is mutated. Component stopping is handled by the cleanData hook above.
7077
7371
  */
7078
7372
  jQuery.fn.html = function (value) {
7079
- // Getter - just pass through
7080
7373
  if (arguments.length === 0) {
7081
7374
  return originalHtml.call(this);
7082
7375
  }
7083
- // Reject hand-written data-sid before mutating the DOM
7084
7376
  assert_no_manual_sid(value, '.html()');
7085
- // Setter - empty first (which stops components), then set content
7086
- return this.each(function () {
7087
- jQuery(this).empty();
7088
- originalHtml.call(jQuery(this), value);
7089
- });
7090
- };
7091
- /**
7092
- * Override jQuery.fn.text() to stop child components when setting new content
7093
- * When used as setter, calls .empty() first to properly cleanup components
7094
- */
7095
- jQuery.fn.text = function (value) {
7096
- // Getter - just pass through
7097
- if (arguments.length === 0) {
7098
- return originalText.call(this);
7099
- }
7100
- // Setter - empty first (which stops components), then set content
7101
- return this.each(function () {
7102
- jQuery(this).empty();
7103
- originalText.call(jQuery(this), value);
7104
- });
7377
+ return originalHtml.call(this, value);
7105
7378
  };
7106
7379
  // Store original jQuery.fn.on
7107
7380
  const originalOn = jQuery.fn.on;
@@ -7243,7 +7516,7 @@ function init(jQuery, config) {
7243
7516
  }
7244
7517
  }
7245
7518
  // Version - will be replaced during build with actual version from package.json
7246
- const version = '2.3.70';
7519
+ const version = '2.3.72';
7247
7520
  // Default export with all functionality
7248
7521
  const jqhtml = {
7249
7522
  // Core
@@ -7358,7 +7631,11 @@ const jqhtml = {
7358
7631
  get_captured_data,
7359
7632
  stop_data_capture,
7360
7633
  set_preload_data,
7361
- clear_preload_data
7634
+ clear_preload_data,
7635
+ // Attachment tracking diagnostics - how many components are watched for
7636
+ // attach/detach and whether the document observer is currently installed
7637
+ tracked_attachment_count,
7638
+ attachment_observer_active
7362
7639
  };
7363
7640
  // Auto-register on window for browser environments
7364
7641
  // This is REQUIRED for compiled templates which use window.jqhtml.register_template()
@@ -7388,5 +7665,5 @@ if (typeof window !== 'undefined' && !window.jqhtml) {
7388
7665
  }
7389
7666
  }
7390
7667
 
7391
- export { COMPONENT_NAME_PATTERN, COMPONENT_NAME_RULE, Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, add_object_printer, applyDebugDelay, boot, clear_preload_data, configure, create_component, debug_overlay, jqhtml as default, devWarn, dynamic_component_name, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_object_printers, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, is_component_name, list_components, logDataChange, logDispatch, logInstruction, logLifecycle, print_object, process_instructions, register, register_cache_class, register_component, register_template, set_preload_data, start_data_capture, stop_data_capture, version };
7668
+ export { COMPONENT_NAME_PATTERN, COMPONENT_NAME_RULE, Jqhtml_Component, LifecycleManager as Jqhtml_LifecycleManager, Jqhtml_Local_Storage, LifecycleManager, Load_Coordinator, add_object_printer, applyDebugDelay, attachment_observer_active, boot, clear_preload_data, configure, create_component, debug_overlay, jqhtml as default, devWarn, dynamic_component_name, escape_html, escape_html_nl2br, extract_slots, get_captured_data, get_component_class, get_component_names, get_config, get_object_printers, get_registered_templates, get_template, get_template_by_class, handleComponentError, has_component, init, init_jquery_plugin, isSequentialProcessing, is_component_name, list_components, logDataChange, logDispatch, logInstruction, logLifecycle, print_object, process_instructions, register, register_cache_class, register_component, register_template, set_preload_data, start_data_capture, stop_data_capture, tracked_attachment_count, version };
7392
7669
  //# sourceMappingURL=index.js.map