@jqhtml/core 2.3.35 → 2.3.54

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.cjs CHANGED
@@ -38,11 +38,9 @@ class LifecycleManager {
38
38
  * Boot a component - run its full lifecycle
39
39
  * Called when component is created
40
40
  *
41
- * Supports lifecycle skip flags:
42
- * - skip_render_and_ready: Skip first render/on_render and skip on_ready entirely.
43
- * Component reports ready after on_load completes.
44
- * - skip_ready: Skip on_ready only.
45
- * Component reports ready after on_render completes (after potential re-render from on_load).
41
+ * Supports lifecycle truncation flags:
42
+ * - _load_only: on_create + on_load only. No render, no children, no on_render, no on_loaded, no on_ready.
43
+ * - _load_render_only: on_create + render + on_load + re-render. No on_render, no on_loaded, no on_ready.
46
44
  */
47
45
  async boot_component(component) {
48
46
  this.active_components.add(component);
@@ -54,20 +52,25 @@ class LifecycleManager {
54
52
  return;
55
53
  // Trigger create event
56
54
  component.trigger('create');
57
- // Check for skip_render_and_ready flag
58
- const skip_render_and_ready = component._skip_render_and_ready;
59
- const skip_ready = component._skip_ready;
55
+ // Check for lifecycle truncation flags
56
+ const load_only = component._load_only;
57
+ const load_render_only = component._load_render_only;
58
+ const is_detached = component._is_detached;
60
59
  let render_id;
61
- if (skip_render_and_ready) {
62
- // Skip the first render/on_render before on_load
63
- // Still need to set render_id to 0 for tracking
60
+ if (load_only || is_detached) {
61
+ // _load_only or detached: skip initial render entirely
64
62
  render_id = 0;
65
63
  component._render_count = 0;
66
64
  }
65
+ else if (load_render_only) {
66
+ // _load_render_only: render to create children, but skip on_render()
67
+ render_id = component._render(null, { skip_on_render: true });
68
+ // Check if stopped during render
69
+ if (component._stopped)
70
+ return;
71
+ }
67
72
  else {
68
- // Render phase - SYNCHRONOUS, creates DOM and child components
69
- // Note: _render() now calls on_render() internally after DOM update
70
- // Capture render ID to detect if another render happens before ready
73
+ // Normal: render with on_render()
71
74
  render_id = component._render();
72
75
  // Check if stopped during render
73
76
  if (component._stopped)
@@ -76,30 +79,39 @@ class LifecycleManager {
76
79
  // Load phase - ASYNC, but only if on_load() is overridden
77
80
  // Skip entirely if component uses default stub to avoid unnecessary yield
78
81
  if (component._has_on_load()) {
82
+ // Load gates: await any promises registered via gate_load() during
83
+ // on_create() before the FIRST on_load(). Gates delay ONLY this load
84
+ // phase — create/render/on_render/cached-paint already happened above.
85
+ // Released early by reload()/refresh()/stop() while gated (see component).
86
+ // Returns null (no await) for the common no-gate case to keep timing
87
+ // identical for ungated components.
88
+ const gate_wait = component._await_load_gates();
89
+ if (gate_wait) {
90
+ await gate_wait;
91
+ // Check if stopped while awaiting gates
92
+ if (component._stopped)
93
+ return;
94
+ }
79
95
  await component._load();
80
96
  // Yield to microtask queue after on_load completes
81
97
  // This ensures async queue tasks always run before the on_load process completes,
82
98
  // even if on_load() itself completes instantly (deterministic behavior)
83
99
  await Promise.resolve();
84
100
  }
85
- // Trigger 'loaded' event - fires after on_load completes (or would have completed)
86
- // This happens before the render/on_render second step
87
- component.trigger('loaded');
88
101
  // Check if stopped during load
89
102
  if (component._stopped)
90
103
  return;
91
- // If skip_render_and_ready, mark component as ready now and return
92
- if (skip_render_and_ready) {
93
- // Set ready state and trigger event
104
+ // If _load_only, mark component as ready now and return
105
+ if (load_only) {
94
106
  component._ready_state = 4;
95
107
  component._update_debug_attrs();
96
- component._log_lifecycle('ready', 'complete (skip_render_and_ready)');
108
+ component._log_lifecycle('ready', 'complete (_load_only)');
97
109
  component.trigger('ready');
98
110
  return;
99
111
  }
100
- // If data changed during load, re-render
101
- // Note: _render() now calls on_render() internally after DOM update
102
- if (component._should_rerender()) {
112
+ // Detached elements always render here (initial render was skipped)
113
+ // Normal elements re-render only if data changed during on_load
114
+ if (is_detached || component._should_rerender()) {
103
115
  // Disable animations during re-render to prevent visual artifacts
104
116
  // from CSS transitions/animations firing on newly rendered elements
105
117
  const $el = component.$;
@@ -116,11 +128,25 @@ class LifecycleManager {
116
128
  }, 5);
117
129
  });
118
130
  }
119
- render_id = component._render();
131
+ // _load_render_only: re-render with skip_on_render to suppress DOM hooks
132
+ if (load_render_only) {
133
+ render_id = component._render(null, { skip_on_render: true });
134
+ }
135
+ else {
136
+ render_id = component._render();
137
+ }
120
138
  // Check if stopped during re-render
121
139
  if (component._stopped)
122
140
  return;
123
141
  }
142
+ // _load_render_only: skip waiting for children, on_ready — mark ready and return
143
+ if (load_render_only) {
144
+ component._ready_state = 4;
145
+ component._update_debug_attrs();
146
+ component._log_lifecycle('ready', 'complete (_load_render_only)');
147
+ component.trigger('ready');
148
+ return;
149
+ }
124
150
  // Fire 'rendered' event - component has completed its synchronous render chain
125
151
  // This happens once, after the final on_render (whether from first render or re-render after on_load)
126
152
  if (!component._has_rendered) {
@@ -144,15 +170,6 @@ class LifecycleManager {
144
170
  if (component._render_count !== render_id) {
145
171
  return; // Stale render, don't call ready
146
172
  }
147
- // If skip_ready, mark component as ready now without calling _ready()
148
- if (skip_ready) {
149
- // Set ready state and trigger event
150
- component._ready_state = 4;
151
- component._update_debug_attrs();
152
- component._log_lifecycle('ready', 'complete (skip_ready)');
153
- component.trigger('ready');
154
- return;
155
- }
156
173
  // Ready phase - waits for children, then calls on_ready()
157
174
  await component._ready();
158
175
  // Check if stopped during ready
@@ -483,6 +500,70 @@ function register(source) {
483
500
  'class name mangling, define static component_name or use register_component().');
484
501
  }
485
502
 
503
+ /**
504
+ * JQHTML Runtime Configuration
505
+ *
506
+ * Integration-level settings supplied by the host application (RSpade, Laravel,
507
+ * a bundler entry point) when jqhtml is loaded. Distinct from `jqhtml.debug`,
508
+ * which is a developer's interactive tracing switch: config here describes the
509
+ * ENVIRONMENT the app is running in, and jqhtml derives behaviour from it.
510
+ *
511
+ * jqhtml.init($, { mode: 'production' });
512
+ * jqhtml.configure({ mode: 'development' });
513
+ *
514
+ * Default mode is 'development', so an integration that passes nothing keeps
515
+ * every diagnostic. Production is always opt-in.
516
+ */
517
+ /** Flags implied by each mode. Add future conventions here, not at call sites. */
518
+ const MODE_DEFAULTS = {
519
+ development: {
520
+ warn_uncacheable_args: true,
521
+ debug_attributes: true,
522
+ },
523
+ production: {
524
+ warn_uncacheable_args: false,
525
+ debug_attributes: false,
526
+ },
527
+ };
528
+ let _mode = 'development';
529
+ let _flags = { ...MODE_DEFAULTS.development };
530
+ /**
531
+ * Apply integration configuration.
532
+ *
533
+ * `mode` resets every flag to that mode's defaults; any explicit flag in the
534
+ * same call then overrides it. Calling with only flags leaves the mode alone.
535
+ * Repeated calls merge.
536
+ */
537
+ function configure(config) {
538
+ if (!config)
539
+ return;
540
+ if (config.mode) {
541
+ if (!MODE_DEFAULTS[config.mode]) {
542
+ throw new Error(`[JQHTML] Unknown mode '${config.mode}'. Expected 'development' or 'production'.`);
543
+ }
544
+ _mode = config.mode;
545
+ _flags = { ...MODE_DEFAULTS[config.mode] };
546
+ }
547
+ if (config.warn_uncacheable_args !== undefined) {
548
+ _flags.warn_uncacheable_args = !!config.warn_uncacheable_args;
549
+ }
550
+ if (config.debug_attributes !== undefined) {
551
+ _flags.debug_attributes = !!config.debug_attributes;
552
+ }
553
+ }
554
+ /** Current mode plus every resolved flag. */
555
+ function get_config() {
556
+ return { mode: _mode, ..._flags };
557
+ }
558
+ /** True when debug-only DOM attributes (data-sid) should be emitted. */
559
+ function debug_attributes_enabled() {
560
+ return _flags.debug_attributes;
561
+ }
562
+ /** True when uncacheable-args warnings should be printed. */
563
+ function warn_uncacheable_args_enabled() {
564
+ return _flags.warn_uncacheable_args;
565
+ }
566
+
486
567
  /**
487
568
  * JQHTML v2 Instruction Processor
488
569
  *
@@ -620,6 +701,9 @@ function process_tag_to_html(instruction, html, tagElements, components, context
620
701
  }
621
702
  // Add simple string/numeric attributes directly
622
703
  for (const [key, value] of Object.entries(attrs)) {
704
+ if (key === 'data-sid' && !debug_attributes_enabled()) {
705
+ continue; // debug-only attribute; the scoped id is what $sid() resolves
706
+ }
623
707
  if (!key.startsWith('$') && !key.startsWith('on') && !key.startsWith('@') &&
624
708
  !key.startsWith('data-bind-') && !key.startsWith('data-__-on-') &&
625
709
  (typeof value === 'string' || typeof value === 'number')) {
@@ -658,20 +742,26 @@ function process_component_to_html(instruction, html, components, context) {
658
742
  // pass this behavior to all child components rendered in its template
659
743
  let props = originalProps;
660
744
  const parentArgs = context.args;
661
- // Check if we need to propagate any flags
662
- const propagate_use_cached_data = parentArgs?.use_cached_data === true && props.use_cached_data === undefined;
663
- const propagate_skip_render_and_ready = parentArgs?.skip_render_and_ready === true && props.skip_render_and_ready === undefined;
664
- const propagate_skip_ready = parentArgs?.skip_ready === true && props.skip_ready === undefined;
665
- if (propagate_use_cached_data || propagate_skip_render_and_ready || propagate_skip_ready) {
745
+ // Check if we need to propagate any flags.
746
+ // Template-authored flags arrive with the '$' still on the key ($_load_only=false
747
+ // compiles to props['$_load_only']) - honor both spellings so a child template can
748
+ // opt out of a cascading parent flag with an explicit false.
749
+ const own_use_cached_data = props.use_cached_data !== undefined ? props.use_cached_data : props['$use_cached_data'];
750
+ const own_load_only = props._load_only !== undefined ? props._load_only : props['$_load_only'];
751
+ const own_load_render_only = props._load_render_only !== undefined ? props._load_render_only : props['$_load_render_only'];
752
+ const propagate_use_cached_data = parentArgs?.use_cached_data === true && own_use_cached_data === undefined;
753
+ const propagate_load_only = parentArgs?._load_only === true && own_load_only === undefined;
754
+ const propagate_load_render_only = parentArgs?._load_render_only === true && own_load_render_only === undefined;
755
+ if (propagate_use_cached_data || propagate_load_only || propagate_load_render_only) {
666
756
  props = { ...originalProps };
667
757
  if (propagate_use_cached_data) {
668
758
  props.use_cached_data = true;
669
759
  }
670
- if (propagate_skip_render_and_ready) {
671
- props.skip_render_and_ready = true;
760
+ if (propagate_load_only) {
761
+ props._load_only = true;
672
762
  }
673
- if (propagate_skip_ready) {
674
- props.skip_ready = true;
763
+ if (propagate_load_render_only) {
764
+ props._load_render_only = true;
675
765
  }
676
766
  }
677
767
  // Determine if third parameter is a function (default content) or object (named slots)
@@ -703,7 +793,10 @@ function process_component_to_html(instruction, html, components, context) {
703
793
  const baseId = props['data-sid'];
704
794
  // The compiled code ALWAYS sets props['id'] with the correct scoped value
705
795
  // Just use it directly - it already has the correct parent _cid baked in
706
- html.push(` id="${props['id']}" data-sid="${baseId}"`);
796
+ // data-sid is debug-only: $sid() resolves via the scoped id, never this.
797
+ html.push(debug_attributes_enabled()
798
+ ? ` id="${props['id']}" data-sid="${baseId}"`
799
+ : ` id="${props['id']}"`);
707
800
  }
708
801
  // Regular id passes through unchanged
709
802
  else if (props['id']) {
@@ -845,6 +938,10 @@ function apply_attributes(element, attrs, context) {
845
938
  }
846
939
  }
847
940
  else if (key.startsWith('data-')) {
941
+ // data-sid is debug-only - suppressed entirely in production
942
+ if (key === 'data-sid' && !debug_attributes_enabled()) {
943
+ continue;
944
+ }
848
945
  // Data attributes - go into DOM
849
946
  const attrValue = typeof value === "string" ? value.trim() : value;
850
947
  element.attr(key, attrValue);
@@ -987,6 +1084,14 @@ async function initialize_component(element, compData) {
987
1084
  if (ComponentClass.name !== name) {
988
1085
  options._component_name = name;
989
1086
  }
1087
+ // Pass lifecycle truncation flags via options (not DOM attributes, since _ prefix is filtered).
1088
+ // Accept both the plain key (cascaded/programmatic) and the '$'-prefixed key (template-authored).
1089
+ if (props._load_only === true || props['$_load_only'] === true) {
1090
+ options._load_only = true;
1091
+ }
1092
+ if (props._load_render_only === true || props['$_load_render_only'] === true) {
1093
+ options._load_render_only = true;
1094
+ }
990
1095
  // Create component instance - element first, then options
991
1096
  const instance = new ComponentClass(element, options);
992
1097
  // Set the instantiator (the component that rendered this one in their template)
@@ -1199,6 +1304,146 @@ function handleComponentError(component, phase, error) {
1199
1304
  // 9. Performance Budgets - Warn when components exceed size/time limits
1200
1305
  // 10. Accessibility Auditing - Check for missing ARIA attributes
1201
1306
 
1307
+ /**
1308
+ * JQHTML Cache Key Serializer
1309
+ *
1310
+ * Produces a deterministic string for a plain-data argument value, so that two
1311
+ * structurally equal objects built on separate renders yield the SAME cache key.
1312
+ * Templates rebuild `{contact_id: 12}` on every render, so identity-based keying
1313
+ * can never match and permanently opts the receiving component out of caching.
1314
+ *
1315
+ * ---------------------------------------------------------------------------
1316
+ * THIS IS NOT `process_for_serialization()` IN local-storage.ts. DO NOT MERGE THEM.
1317
+ *
1318
+ * That serializer stores cache VALUES and deliberately degrades: a function, a
1319
+ * symbol or a circular reference is dropped and serialization continues, because
1320
+ * losing a method while keeping the data is the right trade for a payload.
1321
+ *
1322
+ * For a cache KEY that policy manufactures false hits. Two argument objects that
1323
+ * differ ONLY by a callback would serialize identically, and a component would
1324
+ * render with another component's cached content - strictly worse than not
1325
+ * caching at all. So this serializer DECLINES on the first value it cannot
1326
+ * express exactly. It never drops anything.
1327
+ * ---------------------------------------------------------------------------
1328
+ *
1329
+ * Allow-list, and nothing else: null, undefined, boolean, number, string, Date,
1330
+ * arrays, and plain objects (prototype Object.prototype or null), in any nesting.
1331
+ * Everything else declines with a reason that reaches `data-nocache`.
1332
+ */
1333
+ /**
1334
+ * Values larger than this are declined rather than keyed. The supported case is a
1335
+ * handful of key/value pairs or a list of ids - not a payload. Declining loudly
1336
+ * beats spending the budget on a key nobody benefits from.
1337
+ */
1338
+ const MAX_KEY_BYTES = 500;
1339
+ class Decline extends Error {
1340
+ constructor(reason) {
1341
+ super(reason);
1342
+ this.reason = reason;
1343
+ }
1344
+ }
1345
+ function push(state, text) {
1346
+ state.size += text.length;
1347
+ if (state.size > MAX_KEY_BYTES) {
1348
+ throw new Decline('too-large');
1349
+ }
1350
+ return text;
1351
+ }
1352
+ /**
1353
+ * Length-prefix strings so that no combination of separators can make two
1354
+ * different structures produce the same text.
1355
+ */
1356
+ function encode_string(state, prefix, value) {
1357
+ return push(state, `${prefix}${value.length}:${value}`);
1358
+ }
1359
+ function walk(value, state) {
1360
+ // --- primitives, each tagged so shapes cannot collide ---
1361
+ if (value === null)
1362
+ return push(state, 'n');
1363
+ if (value === undefined)
1364
+ return push(state, 'u');
1365
+ const type = typeof value;
1366
+ if (type === 'boolean')
1367
+ return push(state, value ? 'b1' : 'b0');
1368
+ if (type === 'number')
1369
+ return push(state, `d${String(value)}`);
1370
+ if (type === 'string')
1371
+ return encode_string(state, 's', value);
1372
+ if (type === 'function')
1373
+ throw new Decline('function');
1374
+ if (type === 'symbol')
1375
+ throw new Decline('symbol');
1376
+ if (type === 'bigint')
1377
+ throw new Decline('bigint');
1378
+ if (type !== 'object')
1379
+ throw new Decline(type);
1380
+ // --- objects: reject the impostors before treating anything as data ---
1381
+ if (typeof value.nodeType === 'number')
1382
+ throw new Decline('dom-node');
1383
+ if (value.jquery)
1384
+ throw new Decline('jquery');
1385
+ if (state.seen.has(value))
1386
+ throw new Decline('circular');
1387
+ state.seen.add(value);
1388
+ try {
1389
+ if (value instanceof Date) {
1390
+ const time = value.getTime();
1391
+ if (Number.isNaN(time))
1392
+ throw new Decline('invalid-date');
1393
+ return push(state, `t${value.toISOString()}`);
1394
+ }
1395
+ if (Array.isArray(value)) {
1396
+ // Order is meaningful - never sorted.
1397
+ const parts = [];
1398
+ push(state, 'a[');
1399
+ for (let i = 0; i < value.length; i++) {
1400
+ parts.push(walk(value[i], state));
1401
+ }
1402
+ push(state, ']');
1403
+ return `a[${parts.join(',')}]`;
1404
+ }
1405
+ // Plain object ONLY. A class instance, Map, Set, RegExp, Error, etc. is
1406
+ // declined: two different classes with identical fields would otherwise
1407
+ // serialize the same and collide.
1408
+ const proto = Object.getPrototypeOf(value);
1409
+ if (proto !== Object.prototype && proto !== null) {
1410
+ throw new Decline('non-plain-object');
1411
+ }
1412
+ // Recursive key sort - the existing top-level sort is not enough for nesting.
1413
+ const keys = Object.keys(value).sort();
1414
+ const parts = [];
1415
+ push(state, 'o{');
1416
+ for (const key of keys) {
1417
+ const encoded_key = encode_string(state, 'k', key);
1418
+ parts.push(`${encoded_key}=${walk(value[key], state)}`);
1419
+ }
1420
+ push(state, '}');
1421
+ return `o{${parts.join(',')}}`;
1422
+ }
1423
+ finally {
1424
+ state.seen.delete(value);
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Serialize a value for use in a cache key.
1429
+ *
1430
+ * @returns `{ok: true, text}` when the value is exactly expressible, or
1431
+ * `{ok: false, reason}` naming why it is not. Never throws.
1432
+ */
1433
+ function serialize_for_cache_key(value) {
1434
+ const state = { seen: new WeakSet(), size: 0 };
1435
+ try {
1436
+ return { ok: true, text: walk(value, state) };
1437
+ }
1438
+ catch (error) {
1439
+ if (error instanceof Decline) {
1440
+ return { ok: false, reason: error.reason };
1441
+ }
1442
+ // A throwing getter or exotic proxy trap - decline rather than guess.
1443
+ return { ok: false, reason: 'unserializable' };
1444
+ }
1445
+ }
1446
+
1202
1447
  /**
1203
1448
  * Load Coordinator - Request deduplication for component on_load() calls
1204
1449
  *
@@ -1235,8 +1480,9 @@ class Load_Coordinator {
1235
1480
  * - key: Cache key string, or null if uncacheable
1236
1481
  * - uncacheable_property: Name of first property that prevented caching (for debugging)
1237
1482
  */
1238
- static generate_invocation_key(component_name, args) {
1483
+ static generate_invocation_key(component_name, args, options = {}) {
1239
1484
  let uncacheable_property;
1485
+ let uncacheable_reason;
1240
1486
  // Filter out internal properties (starting with _) and serialize args
1241
1487
  const serializable_args = {};
1242
1488
  for (const key of Object.keys(args).sort()) {
@@ -1244,7 +1490,8 @@ class Load_Coordinator {
1244
1490
  continue; // Skip internal properties
1245
1491
  }
1246
1492
  // Skip framework properties that shouldn't affect cache identity
1247
- if (key === 'use_cached_data' || key === 'skip_render_and_ready' || key === 'skip_ready') {
1493
+ // Note: _load_only and _load_render_only are already filtered by the _ prefix check above
1494
+ if (key === 'use_cached_data') {
1248
1495
  continue;
1249
1496
  }
1250
1497
  const value = args[key];
@@ -1274,21 +1521,37 @@ class Load_Coordinator {
1274
1521
  // Method threw error - treat as uncacheable
1275
1522
  if (!uncacheable_property) {
1276
1523
  uncacheable_property = key;
1524
+ uncacheable_reason = 'cache-id-threw';
1277
1525
  }
1278
- return { key: null, uncacheable_property };
1526
+ return { key: null, uncacheable_property, uncacheable_reason };
1527
+ }
1528
+ }
1529
+ // No author-supplied id. The cache may fall back to keying by
1530
+ // deterministic content; deduplication deliberately may not.
1531
+ if (options.allow_content_serialization) {
1532
+ const serialized = serialize_for_cache_key(value);
1533
+ if (serialized.ok) {
1534
+ serializable_args[key] = `__JQHTML_CONTENT__:${serialized.text}`;
1535
+ continue;
1279
1536
  }
1537
+ if (!uncacheable_property) {
1538
+ uncacheable_property = key;
1539
+ uncacheable_reason = serialized.reason;
1540
+ }
1541
+ return { key: null, uncacheable_property, uncacheable_reason };
1280
1542
  }
1281
- // No cache ID available - this property is uncacheable
1282
1543
  if (!uncacheable_property) {
1283
1544
  uncacheable_property = key;
1545
+ uncacheable_reason = value_type === 'function' ? 'function' : 'object';
1284
1546
  }
1285
- return { key: null, uncacheable_property };
1547
+ return { key: null, uncacheable_property, uncacheable_reason };
1286
1548
  }
1287
1549
  // Unknown type (symbol, bigint, etc.) - uncacheable
1288
1550
  if (!uncacheable_property) {
1289
1551
  uncacheable_property = key;
1552
+ uncacheable_reason = value_type;
1290
1553
  }
1291
- return { key: null, uncacheable_property };
1554
+ return { key: null, uncacheable_property, uncacheable_reason };
1292
1555
  }
1293
1556
  // Try to serialize - if it fails (shouldn't happen now, but safety net), return null
1294
1557
  try {
@@ -1306,6 +1569,12 @@ class Load_Coordinator {
1306
1569
  */
1307
1570
  static should_execute_on_load(component) {
1308
1571
  const { key } = this.generate_invocation_key(component.component_name(), component.args);
1572
+ // No identity means no coordination. Without this, every un-keyable component
1573
+ // would share the single `null` registry entry and adopt an unrelated
1574
+ // component's data - the worst failure this system can produce.
1575
+ if (key === null) {
1576
+ return true;
1577
+ }
1309
1578
  const entry = this._registry.get(key);
1310
1579
  if (!entry) {
1311
1580
  // No existing request - this component becomes the leader
@@ -1328,6 +1597,10 @@ class Load_Coordinator {
1328
1597
  */
1329
1598
  static register_leader(component, on_load_promise) {
1330
1599
  const { key } = this.generate_invocation_key(component.component_name(), component.args);
1600
+ // Un-keyable component: run alone, register nothing. See should_execute_on_load().
1601
+ if (key === null) {
1602
+ return () => { };
1603
+ }
1331
1604
  // Create a promise that we control - it resolves when complete_coordination is called
1332
1605
  let resolve_promise;
1333
1606
  const coordination_promise = new Promise((resolve) => {
@@ -1549,6 +1822,8 @@ Load_Coordinator._registry = new Map();
1549
1822
  // Registry mapping class names to constructors
1550
1823
  const class_registry = Object.create(null);
1551
1824
  // Markers for serialized class instances (unique to avoid collisions with user data)
1825
+ // Replaced at build time by rollup (see rollup.config.js).
1826
+ const CORE_VERSION = '2.3.54';
1552
1827
  const CLASS_MARKER = '__jqhtml_class__';
1553
1828
  const PROPS_MARKER = '__jqhtml_props__';
1554
1829
  /**
@@ -1622,7 +1897,13 @@ function process_for_serialization(value, verbose, seen) {
1622
1897
  // Return undefined to omit this value (not fail entire serialization)
1623
1898
  return undefined;
1624
1899
  }
1625
- // Handle circular references
1900
+ // Handle circular references.
1901
+ // `seen` tracks only the current ancestor path (the DFS stack): an object is
1902
+ // added on the way down and removed on the way back up (see finally below).
1903
+ // This flags a genuine cycle (a back-edge to an ancestor) while allowing a
1904
+ // shared reference in a DAG to be serialized independently on each visit.
1905
+ // JSON round-trip semantics do not preserve identity anyway, so emitting a
1906
+ // copy per reference is correct; silently omitting the property is not.
1626
1907
  if (seen.has(value)) {
1627
1908
  if (verbose) {
1628
1909
  console.warn('[JQHTML Cache] Circular reference detected - cannot serialize');
@@ -1630,69 +1911,89 @@ function process_for_serialization(value, verbose, seen) {
1630
1911
  return undefined; // Fail entire serialization
1631
1912
  }
1632
1913
  seen.add(value);
1633
- // Handle arrays
1634
- if (Array.isArray(value)) {
1635
- const result = [];
1636
- for (let i = 0; i < value.length; i++) {
1637
- const item = value[i];
1638
- const processed = process_for_serialization(item, verbose, seen);
1639
- // For arrays, we keep undefined as null to preserve indices
1640
- result.push(processed === undefined ? null : processed);
1914
+ try {
1915
+ // Handle arrays
1916
+ if (Array.isArray(value)) {
1917
+ const result = [];
1918
+ for (let i = 0; i < value.length; i++) {
1919
+ const item = value[i];
1920
+ const processed = process_for_serialization(item, verbose, seen);
1921
+ // For arrays, we keep undefined as null to preserve indices
1922
+ result.push(processed === undefined ? null : processed);
1923
+ }
1924
+ return result;
1641
1925
  }
1642
- return result;
1643
- }
1644
- // Handle Date objects specially
1645
- if (value instanceof Date) {
1646
- return {
1647
- [CLASS_MARKER]: 'Date',
1648
- [PROPS_MARKER]: value.toISOString()
1649
- };
1650
- }
1651
- // Handle Map objects
1652
- if (value instanceof Map) {
1653
- const entries = [];
1654
- for (const [k, v] of value) {
1655
- const processedKey = process_for_serialization(k, verbose, seen);
1656
- const processedValue = process_for_serialization(v, verbose, seen);
1657
- entries.push([processedKey, processedValue]);
1658
- }
1659
- return {
1660
- [CLASS_MARKER]: 'Map',
1661
- [PROPS_MARKER]: entries
1662
- };
1663
- }
1664
- // Handle Set objects
1665
- if (value instanceof Set) {
1666
- const items = [];
1667
- for (const item of value) {
1668
- items.push(process_for_serialization(item, verbose, seen));
1926
+ // Handle Date objects specially
1927
+ if (value instanceof Date) {
1928
+ return {
1929
+ [CLASS_MARKER]: 'Date',
1930
+ [PROPS_MARKER]: value.toISOString()
1931
+ };
1669
1932
  }
1670
- return {
1671
- [CLASS_MARKER]: 'Set',
1672
- [PROPS_MARKER]: items
1673
- };
1674
- }
1675
- // Get the constructor
1676
- const ctor = value.constructor;
1677
- // Handle registered class instances
1678
- if (ctor && ctor.name && class_registry[ctor.name]) {
1679
- const props = {};
1680
- // Extract own enumerable properties (bypass any toJSON method)
1681
- for (const key of Object.keys(value)) {
1682
- const propValue = value[key];
1683
- const processed = process_for_serialization(propValue, verbose, seen);
1684
- // Only include if not undefined (failed serialization)
1685
- if (processed !== undefined || propValue === undefined) {
1686
- props[key] = processed;
1933
+ // Handle Map objects
1934
+ if (value instanceof Map) {
1935
+ const entries = [];
1936
+ for (const [k, v] of value) {
1937
+ const processedKey = process_for_serialization(k, verbose, seen);
1938
+ const processedValue = process_for_serialization(v, verbose, seen);
1939
+ entries.push([processedKey, processedValue]);
1940
+ }
1941
+ return {
1942
+ [CLASS_MARKER]: 'Map',
1943
+ [PROPS_MARKER]: entries
1944
+ };
1945
+ }
1946
+ // Handle Set objects
1947
+ if (value instanceof Set) {
1948
+ const items = [];
1949
+ for (const item of value) {
1950
+ items.push(process_for_serialization(item, verbose, seen));
1687
1951
  }
1952
+ return {
1953
+ [CLASS_MARKER]: 'Set',
1954
+ [PROPS_MARKER]: items
1955
+ };
1688
1956
  }
1689
- return {
1690
- [CLASS_MARKER]: ctor.name,
1691
- [PROPS_MARKER]: props
1692
- };
1693
- }
1694
- // Handle plain objects (constructor is Object or no constructor)
1695
- if (ctor === Object || ctor === undefined || ctor === null) {
1957
+ // Get the constructor
1958
+ const ctor = value.constructor;
1959
+ // Handle registered class instances
1960
+ if (ctor && ctor.name && class_registry[ctor.name]) {
1961
+ const props = {};
1962
+ // Extract own enumerable properties (bypass any toJSON method)
1963
+ for (const key of Object.keys(value)) {
1964
+ const propValue = value[key];
1965
+ const processed = process_for_serialization(propValue, verbose, seen);
1966
+ // Only include if not undefined (failed serialization)
1967
+ if (processed !== undefined || propValue === undefined) {
1968
+ props[key] = processed;
1969
+ }
1970
+ }
1971
+ return {
1972
+ [CLASS_MARKER]: ctor.name,
1973
+ [PROPS_MARKER]: props
1974
+ };
1975
+ }
1976
+ // Handle plain objects (constructor is Object or no constructor)
1977
+ if (ctor === Object || ctor === undefined || ctor === null) {
1978
+ const result = {};
1979
+ for (const key of Object.keys(value)) {
1980
+ const propValue = value[key];
1981
+ const processed = process_for_serialization(propValue, verbose, seen);
1982
+ // Only include if not undefined (unless original was undefined)
1983
+ if (processed !== undefined || propValue === undefined) {
1984
+ result[key] = processed;
1985
+ }
1986
+ }
1987
+ return result;
1988
+ }
1989
+ // Unregistered class instance - convert to plain object for hot/cold parity
1990
+ // This ensures developers catch missing class registrations during development
1991
+ // (methods will be lost, only properties preserved)
1992
+ if (verbose) {
1993
+ console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
1994
+ `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
1995
+ }
1996
+ // Convert to plain object - properties are preserved, prototype methods are lost
1696
1997
  const result = {};
1697
1998
  for (const key of Object.keys(value)) {
1698
1999
  const propValue = value[key];
@@ -1704,24 +2005,10 @@ function process_for_serialization(value, verbose, seen) {
1704
2005
  }
1705
2006
  return result;
1706
2007
  }
1707
- // Unregistered class instance - convert to plain object for hot/cold parity
1708
- // This ensures developers catch missing class registrations during development
1709
- // (methods will be lost, only properties preserved)
1710
- if (verbose) {
1711
- console.warn(`[JQHTML Cache] Converting unregistered class "${ctor.name}" to plain object. ` +
1712
- `Methods will be lost. Call jqhtml.register_cache_class(${ctor.name}) to preserve the class.`);
1713
- }
1714
- // Convert to plain object - properties are preserved, prototype methods are lost
1715
- const result = {};
1716
- for (const key of Object.keys(value)) {
1717
- const propValue = value[key];
1718
- const processed = process_for_serialization(propValue, verbose, seen);
1719
- // Only include if not undefined (unless original was undefined)
1720
- if (processed !== undefined || propValue === undefined) {
1721
- result[key] = processed;
1722
- }
2008
+ finally {
2009
+ // Pop this object off the ancestor path now that its subtree is done.
2010
+ seen.delete(value);
1723
2011
  }
1724
- return result;
1725
2012
  }
1726
2013
  // ============================================================================
1727
2014
  // Deserialization (String → Object)
@@ -1826,6 +2113,12 @@ class Jqhtml_Local_Storage {
1826
2113
  */
1827
2114
  static set_cache_key(cache_key, cache_mode = 'data') {
1828
2115
  this._cache_key = cache_key;
2116
+ // Key SHAPE is a function of the library (see cache-key-serializer.ts), so an
2117
+ // upgrade that changes it must invalidate everything persisted under the old shape.
2118
+ // Version the SCOPE MARKER rather than the key itself: _validate_scope() already
2119
+ // clears every jqhtml key when this value changes, and leaving the per-entry key
2120
+ // format alone keeps stored keys readable and avoids repeating the version in each.
2121
+ this._scope_marker = `${CORE_VERSION}::${cache_key}`;
1829
2122
  this._cache_mode = cache_mode;
1830
2123
  this._init();
1831
2124
  }
@@ -1895,21 +2188,21 @@ class Jqhtml_Local_Storage {
1895
2188
  }
1896
2189
  try {
1897
2190
  const stored_key = localStorage.getItem('_jqhtml_cache_key');
1898
- // If cache key exists and has changed, clear only JQHTML keys
1899
- if (stored_key !== null && stored_key !== this._cache_key) {
1900
- console.log('[JQHTML Local Storage] Cache key changed, clearing JQHTML keys:', {
2191
+ // If the scope marker (core version + developer key) changed, clear only JQHTML keys
2192
+ if (stored_key !== null && stored_key !== this._scope_marker) {
2193
+ console.log('[JQHTML Local Storage] Cache scope changed, clearing JQHTML keys:', {
1901
2194
  old_key: stored_key,
1902
- new_key: this._cache_key,
2195
+ new_key: this._scope_marker,
1903
2196
  });
1904
2197
  this._clear_jqhtml_keys();
1905
- localStorage.setItem('_jqhtml_cache_key', this._cache_key);
2198
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
1906
2199
  }
1907
2200
  else if (stored_key === null) {
1908
2201
  // First time JQHTML is using this storage - just set the key, don't clear
1909
- console.log('[JQHTML Local Storage] Initializing cache key (first use):', {
1910
- new_key: this._cache_key,
2202
+ console.log('[JQHTML Local Storage] Initializing cache scope (first use):', {
2203
+ new_key: this._scope_marker,
1911
2204
  });
1912
- localStorage.setItem('_jqhtml_cache_key', this._cache_key);
2205
+ localStorage.setItem('_jqhtml_cache_key', this._scope_marker);
1913
2206
  }
1914
2207
  }
1915
2208
  catch (e) {
@@ -2141,10 +2434,964 @@ class Jqhtml_Local_Storage {
2141
2434
  }
2142
2435
  }
2143
2436
  Jqhtml_Local_Storage._cache_key = null;
2437
+ /** Versioned scope identity - compared in _validate_scope() to clear on a core upgrade. */
2438
+ Jqhtml_Local_Storage._scope_marker = null;
2144
2439
  Jqhtml_Local_Storage._cache_mode = 'data';
2145
2440
  Jqhtml_Local_Storage._storage_available = null;
2146
2441
  Jqhtml_Local_Storage._initialized = false;
2147
2442
 
2443
+ /**
2444
+ * JQHTML Component Event System
2445
+ *
2446
+ * Extracted from component.ts - handles lifecycle event registration,
2447
+ * triggering, and state tracking.
2448
+ *
2449
+ * Events have "sticky" semantics for lifecycle events: if an event has already
2450
+ * occurred, new .on() handlers fire immediately with the stored data.
2451
+ */
2452
+ /**
2453
+ * Register a callback for an event.
2454
+ *
2455
+ * Lifecycle events (create, render, load, loaded, ready) are "sticky":
2456
+ * If a lifecycle event has already occurred, the callback fires immediately
2457
+ * AND registers for future occurrences.
2458
+ *
2459
+ * Custom events only fire when explicitly triggered via trigger().
2460
+ *
2461
+ * @param component - The component instance
2462
+ * @param event_name - Name of the event
2463
+ * @param callback - Callback: (component, data?) => void
2464
+ */
2465
+ function event_on(component, event_name, callback) {
2466
+ // Initialize callback array for this event if needed
2467
+ if (!component._lifecycle_callbacks.has(event_name)) {
2468
+ component._lifecycle_callbacks.set(event_name, []);
2469
+ }
2470
+ // Add callback to queue
2471
+ component._lifecycle_callbacks.get(event_name).push(callback);
2472
+ // If this lifecycle event has already occurred, fire the callback immediately
2473
+ // with the stored data from when trigger() was called
2474
+ if (component._lifecycle_states.has(event_name)) {
2475
+ try {
2476
+ const stored_data = component._lifecycle_states.get(event_name);
2477
+ callback(component, stored_data);
2478
+ }
2479
+ catch (error) {
2480
+ console.error(`[JQHTML] Error in ${event_name} callback:`, error);
2481
+ }
2482
+ }
2483
+ return component;
2484
+ }
2485
+ /**
2486
+ * Register a callback that fires exactly once.
2487
+ *
2488
+ * - If the event already occurred (sticky), fires immediately and does NOT register.
2489
+ * - If the event has not occurred, registers and auto-deregisters after first fire.
2490
+ *
2491
+ * @param component - The component instance
2492
+ * @param event_name - Name of the event
2493
+ * @param callback - Callback: (component, data?) => void
2494
+ */
2495
+ function event_once(component, event_name, callback) {
2496
+ // If event already occurred, fire immediately and we're done
2497
+ if (component._lifecycle_states.has(event_name)) {
2498
+ try {
2499
+ const stored_data = component._lifecycle_states.get(event_name);
2500
+ callback(component, stored_data);
2501
+ }
2502
+ catch (error) {
2503
+ console.error(`[JQHTML] Error in ${event_name} once callback:`, error);
2504
+ }
2505
+ return component;
2506
+ }
2507
+ // Wrap callback to auto-deregister after first fire
2508
+ const wrapper = (comp, data) => {
2509
+ // Remove ourselves from the callback list
2510
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2511
+ if (callbacks) {
2512
+ const idx = callbacks.indexOf(wrapper);
2513
+ if (idx !== -1)
2514
+ callbacks.splice(idx, 1);
2515
+ }
2516
+ callback(comp, data);
2517
+ };
2518
+ // Initialize callback array for this event if needed
2519
+ if (!component._lifecycle_callbacks.has(event_name)) {
2520
+ component._lifecycle_callbacks.set(event_name, []);
2521
+ }
2522
+ component._lifecycle_callbacks.get(event_name).push(wrapper);
2523
+ return component;
2524
+ }
2525
+ /**
2526
+ * Trigger an event - fires all registered callbacks.
2527
+ * Marks event as occurred so future .on() calls fire immediately.
2528
+ *
2529
+ * @param component - The component instance
2530
+ * @param event_name - Name of the event to trigger
2531
+ * @param data - Optional data to pass to callbacks as second parameter
2532
+ */
2533
+ function event_trigger(component, event_name, data) {
2534
+ // Mark this event as occurred and store the data for late subscribers
2535
+ component._lifecycle_states.set(event_name, data);
2536
+ // Fire all registered callbacks for this event.
2537
+ // Iterate a SNAPSHOT: handlers registered via once() splice themselves out of the
2538
+ // live array while it is being iterated, which would shift later handlers into
2539
+ // already-visited slots and skip them. The snapshot also means a handler
2540
+ // registered during dispatch does not fire in this dispatch (event_on's sticky
2541
+ // immediate-fire already delivered it).
2542
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2543
+ if (callbacks) {
2544
+ for (const callback of [...callbacks]) {
2545
+ try {
2546
+ callback.bind(component)(component, data);
2547
+ }
2548
+ catch (error) {
2549
+ console.error(`[JQHTML] Error in ${event_name} callback:`, error);
2550
+ }
2551
+ }
2552
+ }
2553
+ }
2554
+ /**
2555
+ * Check if any callbacks are registered for a given event.
2556
+ *
2557
+ * @param component - The component instance
2558
+ * @param event_name - Name of the event to check
2559
+ */
2560
+ function event_on_registered(component, event_name) {
2561
+ const callbacks = component._lifecycle_callbacks.get(event_name);
2562
+ return !!(callbacks && callbacks.length > 0);
2563
+ }
2564
+ /**
2565
+ * Invalidate a lifecycle event - removes the "already occurred" marker.
2566
+ *
2567
+ * After invalidate() is called:
2568
+ * - New .on() handlers will NOT fire immediately
2569
+ * - The ready() promise will NOT resolve immediately
2570
+ * - Handlers wait for the next trigger() call
2571
+ *
2572
+ * Existing registered callbacks are NOT removed - they'll fire on next trigger().
2573
+ *
2574
+ * Use case: Call invalidate('ready') at the start of reload() or render()
2575
+ * so that any new .on('ready') handlers wait for the reload/render to complete.
2576
+ *
2577
+ * @param component - The component instance
2578
+ * @param event_name - Name of the event to invalidate
2579
+ */
2580
+ function event_invalidate(component, event_name) {
2581
+ component._lifecycle_states.delete(event_name);
2582
+ }
2583
+
2584
+ /**
2585
+ * JQHTML Data Proxy System
2586
+ *
2587
+ * Extracted from component.ts - handles:
2588
+ * - Data freeze/unfreeze enforcement via Proxy
2589
+ * - Detached on_load() execution with restricted access
2590
+ */
2591
+ /**
2592
+ * Set up the `this.data` property on a component using Object.defineProperty
2593
+ * with a Proxy that enforces freeze/unfreeze semantics.
2594
+ *
2595
+ * After setup:
2596
+ * - `this.data` reads/writes go through a Proxy
2597
+ * - When `component.__data_frozen === true`, writes throw errors
2598
+ * - When frozen is false, writes pass through normally
2599
+ *
2600
+ * @param component - The component instance to set up data on
2601
+ */
2602
+ function setup_data_property(component) {
2603
+ let _data = {};
2604
+ // Helper to create frozen proxy for data object
2605
+ const create_proxy = (obj) => {
2606
+ return new Proxy(obj, {
2607
+ set: (target, prop, value) => {
2608
+ if (component.__data_frozen) {
2609
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to modify this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2610
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2611
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2612
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2613
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2614
+ `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2615
+ ` ❌ In on_ready(): this.data.${String(prop)} = ${JSON.stringify(value)};\n` +
2616
+ ` ✅ In on_create(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Set default\n` +
2617
+ ` ✅ In on_load(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Fetch from API\n` +
2618
+ ` ✅ For component state: this.args.${String(prop)} = ${JSON.stringify(value)}; (accessible in on_load)`);
2619
+ throw new Error(`[JQHTML] Cannot modify this.data.${String(prop)} outside of on_create() or on_load(). ` +
2620
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2621
+ }
2622
+ target[prop] = value;
2623
+ return true;
2624
+ },
2625
+ deleteProperty: (target, prop) => {
2626
+ if (component.__data_frozen) {
2627
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to delete this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2628
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2629
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2630
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2631
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.`);
2632
+ throw new Error(`[JQHTML] Cannot delete this.data.${String(prop)} outside of on_create() or on_load(). ` +
2633
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2634
+ }
2635
+ delete target[prop];
2636
+ return true;
2637
+ }
2638
+ });
2639
+ };
2640
+ // Create initial proxied data object
2641
+ _data = create_proxy({});
2642
+ Object.defineProperty(component, 'data', {
2643
+ get: () => _data,
2644
+ set: (value) => {
2645
+ if (component.__data_frozen) {
2646
+ console.error(`[JQHTML] ERROR: Component "${component.component_name()}" attempted to reassign this.data outside of on_create() or on_load().\n\n` +
2647
+ `RESTRICTION: this.data can ONLY be modified in:\n` +
2648
+ ` - on_create() (set initial defaults, synchronous only)\n` +
2649
+ ` - on_load() (fetch data from APIs, can be async)\n\n` +
2650
+ `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2651
+ `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2652
+ ` ❌ In on_ready(): this.data = {...};\n` +
2653
+ ` ✅ In on_create(): this.data.count = 0; // Set default\n` +
2654
+ ` ✅ In on_load(): this.data = await fetch(...); // Fetch from API\n` +
2655
+ ` ✅ For component state: this.args.count = 5; (accessible in on_load)`);
2656
+ throw new Error(`[JQHTML] Cannot reassign this.data outside of on_create() or on_load(). ` +
2657
+ `this.data is frozen after on_create() and unfrozen only during on_load().`);
2658
+ }
2659
+ // When setting, wrap the new value in a proxy too
2660
+ _data = create_proxy(value);
2661
+ },
2662
+ enumerable: true,
2663
+ configurable: false
2664
+ });
2665
+ }
2666
+ /**
2667
+ * Execute on_load() in a detached context with restricted access.
2668
+ *
2669
+ * Creates a sandboxed environment where on_load() can only access:
2670
+ * - this.args (read-only)
2671
+ * - this.data (read/write, cloned from __initial_data_snapshot)
2672
+ *
2673
+ * All other property access (this.$, this.$sid, etc.) throws errors.
2674
+ *
2675
+ * @param component - The component instance
2676
+ * @param use_load_coordinator - Whether to use Load_Coordinator for deduplication
2677
+ * @returns The resulting data and optional coordination completion function
2678
+ */
2679
+ async function execute_on_load_detached(component, use_load_coordinator = false) {
2680
+ // Clone this.data from the snapshot captured after on_create()
2681
+ const data_clone = component.__initial_data_snapshot
2682
+ ? JSON.parse(JSON.stringify(component.__initial_data_snapshot))
2683
+ : {};
2684
+ // Create a read-only proxy for args that blocks all modifications
2685
+ // Can't use JSON clone because args may contain functions (_slots, callbacks)
2686
+ const component_name = component.component_name();
2687
+ const create_readonly_proxy = (obj, path = 'this.args') => {
2688
+ if (obj === null || typeof obj !== 'object')
2689
+ return obj;
2690
+ return new Proxy(obj, {
2691
+ get(target, prop) {
2692
+ const value = target[prop];
2693
+ // Recursively wrap nested objects (but not functions)
2694
+ if (value !== null && typeof value === 'object' && typeof value !== 'function') {
2695
+ return create_readonly_proxy(value, `${path}.${String(prop)}`);
2696
+ }
2697
+ return value;
2698
+ },
2699
+ set(_target, prop, value) {
2700
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify ${path}.${String(prop)} during on_load().\n\n` +
2701
+ `RESTRICTION: this.args is READ-ONLY during on_load().\n\n` +
2702
+ `WHY: this.args configures what data to fetch. Modifying it during on_load() creates circular dependencies.\n\n` +
2703
+ `FIX: Modify this.args BEFORE on_load() runs (in on_create() or before calling reload()):\n` +
2704
+ ` ❌ Inside on_load(): ${path}.${String(prop)} = ${JSON.stringify(value)};\n` +
2705
+ ` ✅ In on_create(): this.args.${String(prop)} = defaultValue;`);
2706
+ throw new Error(`[JQHTML] Cannot modify ${path}.${String(prop)} during on_load(). ` +
2707
+ `this.args is read-only in on_load().`);
2708
+ },
2709
+ deleteProperty(_target, prop) {
2710
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to delete ${path}.${String(prop)} during on_load().\n\n` +
2711
+ `RESTRICTION: this.args is READ-ONLY during on_load().`);
2712
+ throw new Error(`[JQHTML] Cannot delete ${path}.${String(prop)} during on_load(). ` +
2713
+ `this.args is read-only in on_load().`);
2714
+ }
2715
+ });
2716
+ };
2717
+ // Create a detached context object that on_load will operate on
2718
+ const detached_context = {
2719
+ args: create_readonly_proxy(component.args), // Read-only proxy wrapping real args
2720
+ data: data_clone // Cloned data - modifications stay isolated
2721
+ };
2722
+ // Create restricted proxy that operates on the detached context
2723
+ const restricted_this = new Proxy(detached_context, {
2724
+ get(target, prop) {
2725
+ // Only allow access to args and data
2726
+ if (prop === 'args') {
2727
+ return target.args;
2728
+ }
2729
+ if (prop === 'data') {
2730
+ return target.data;
2731
+ }
2732
+ // Block everything else
2733
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to access this.${String(prop)} during on_load().\n\n` +
2734
+ `RESTRICTION: on_load() may ONLY access:\n` +
2735
+ ` - this.args (read-only)\n` +
2736
+ ` - this.data (read/write)\n\n` +
2737
+ `WHY: on_load() is for data fetching only. All other component functionality should happen in other lifecycle methods.\n\n` +
2738
+ `FIX:\n` +
2739
+ ` - DOM manipulation → use on_render() or on_ready()\n` +
2740
+ ` - Component methods → call them before/after on_load(), not inside it\n` +
2741
+ ` - Other properties → restructure code to only use this.args and this.data in on_load()`);
2742
+ throw new Error(`[JQHTML] Cannot access this.${String(prop)} during on_load(). ` +
2743
+ `on_load() may only access this.args and this.data.`);
2744
+ },
2745
+ set(target, prop, value) {
2746
+ // Only allow setting data
2747
+ if (prop === 'data') {
2748
+ target.data = value;
2749
+ return true;
2750
+ }
2751
+ // Block setting args
2752
+ if (prop === 'args') {
2753
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.args during on_load().\n\n` +
2754
+ `RESTRICTION: on_load() may ONLY modify:\n` +
2755
+ ` - this.data (read/write)\n\n` +
2756
+ `WHY: this.args is component state that on_load() depends on. Modifying it inside on_load() creates circular dependencies.\n\n` +
2757
+ `FIX: Modify this.args BEFORE calling on_load() (in on_create() or other lifecycle methods), not inside on_load():\n` +
2758
+ ` ❌ Inside on_load(): this.args.filter = 'new_value';\n` +
2759
+ ` ✅ In on_create(): this.args.filter = this.args.initial_filter || 'default';`);
2760
+ throw new Error(`[JQHTML] Cannot modify this.args during on_load(). ` +
2761
+ `Modify this.args in other lifecycle methods, not inside on_load().`);
2762
+ }
2763
+ // Block setting any other properties
2764
+ console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.${String(prop)} during on_load().\n\n` +
2765
+ `RESTRICTION: on_load() may ONLY modify:\n` +
2766
+ ` - this.data (read/write)\n\n` +
2767
+ `WHY: on_load() is for data fetching only. Setting properties on the component instance should happen in other lifecycle methods.\n\n` +
2768
+ `FIX: Store your data in this.data instead:\n` +
2769
+ ` ❌ this.${String(prop)} = value;\n` +
2770
+ ` ✅ this.data.${String(prop)} = value;`);
2771
+ throw new Error(`[JQHTML] Cannot modify this.${String(prop)} during on_load(). ` +
2772
+ `Only this.data can be modified in on_load().`);
2773
+ }
2774
+ });
2775
+ // Create promise for this on_load() call
2776
+ const on_load_promise = (async () => {
2777
+ try {
2778
+ await component._call_lifecycle('on_load', restricted_this);
2779
+ }
2780
+ catch (error) {
2781
+ if (use_load_coordinator) {
2782
+ // Handle error and notify coordinator
2783
+ Load_Coordinator.handle_leader_error(component, error);
2784
+ }
2785
+ throw error;
2786
+ }
2787
+ })();
2788
+ // If using Load_Coordinator, register as leader
2789
+ // Note: We store the completion function but DON'T call it here
2790
+ // It will be called by _load() after _apply_load_result() updates this.data
2791
+ let complete_coordination = null;
2792
+ if (use_load_coordinator) {
2793
+ complete_coordination = Load_Coordinator.register_leader(component, on_load_promise);
2794
+ }
2795
+ await on_load_promise;
2796
+ // Note: We don't validate args changes here because external code (like parent
2797
+ // components calling reload()) is allowed to modify component.args during on_load().
2798
+ // The read-only proxy only prevents code INSIDE on_load() from modifying args.
2799
+ // Return the data from the detached context AND the completion function
2800
+ return {
2801
+ data: detached_context.data,
2802
+ complete_coordination
2803
+ };
2804
+ }
2805
+
2806
+ /**
2807
+ * JQHTML Component Cache Integration
2808
+ *
2809
+ * Extracted from component.ts - handles cache key generation,
2810
+ * cache reads during create(), cache checks during reload(),
2811
+ * and HTML cache snapshots during ready().
2812
+ *
2813
+ * Uses Jqhtml_Local_Storage as the underlying storage layer.
2814
+ */
2815
+ /**
2816
+ * Generate a cache key for a component using its name + args.
2817
+ * Supports custom cache_id() override.
2818
+ *
2819
+ * @param component - The component instance
2820
+ * @returns Cache key string or null if caching is disabled
2821
+ */
2822
+ function generate_cache_key(component) {
2823
+ if (typeof component.cache_id === 'function') {
2824
+ try {
2825
+ const custom_cache_id = component.cache_id();
2826
+ return { cache_key: `${component.component_name()}::${String(custom_cache_id)}` };
2827
+ }
2828
+ catch (error) {
2829
+ return { cache_key: null, uncacheable_property: 'cache_id()', uncacheable_reason: 'cache-id-threw' };
2830
+ }
2831
+ }
2832
+ // Standard args-based key. The CACHE opts into content serialization for plain-data
2833
+ // object args; deduplication does not - see InvocationKeyOptions for why.
2834
+ const result = Load_Coordinator.generate_invocation_key(component.component_name(), component.args, { allow_content_serialization: true });
2835
+ return {
2836
+ cache_key: result.key,
2837
+ uncacheable_property: result.uncacheable_property,
2838
+ uncacheable_reason: result.uncacheable_reason,
2839
+ };
2840
+ }
2841
+ // One warning per component+property. A list of 50 rows must not print 50 warnings.
2842
+ const _warned_uncacheable = new Set();
2843
+ /**
2844
+ * Development warning: this component fetches data but cannot be cached, because
2845
+ * its args do not reduce to a stable key and it defines no cache_id() to say what
2846
+ * its identity is. Nothing is broken - the component works - but it silently opts
2847
+ * out of cache reuse and of load deduplication.
2848
+ *
2849
+ * Controlled by the `warn_uncacheable_args` integration flag (see config.ts).
2850
+ */
2851
+ function warn_uncacheable_component(component, uncacheable_property, uncacheable_reason) {
2852
+ if (!warn_uncacheable_args_enabled())
2853
+ return;
2854
+ let name = 'unknown';
2855
+ try {
2856
+ name = component.component_name();
2857
+ }
2858
+ catch { /* name unavailable */ }
2859
+ const dedupe_key = `${name}::${uncacheable_property || '?'}::${uncacheable_reason || '?'}`;
2860
+ if (_warned_uncacheable.has(dedupe_key))
2861
+ return;
2862
+ _warned_uncacheable.add(dedupe_key);
2863
+ // cache_id() exists but threw - a different problem with a different fix
2864
+ if (uncacheable_property === 'cache_id()' || uncacheable_reason === 'cache-id-threw') {
2865
+ console.warn(`[JQHTML] <${name}> defines cache_id() but it threw, so this component is not cached ` +
2866
+ `and its loads are not deduplicated. Fix cache_id() so it returns a stable string.`, { component: name, cid: component._cid });
2867
+ return;
2868
+ }
2869
+ const REASONS = {
2870
+ 'function': 'it contains a function - a callback is real identity that content cannot express',
2871
+ 'symbol': 'it contains a symbol',
2872
+ 'bigint': 'it contains a bigint',
2873
+ 'dom-node': 'it contains a DOM node',
2874
+ 'jquery': 'it contains a jQuery object',
2875
+ 'circular': 'it contains a circular reference',
2876
+ 'non-plain-object': 'it contains a class instance, Map, Set or similar - only plain objects and arrays can be keyed by content',
2877
+ 'too-large': 'it serializes to more than 500 bytes - args are meant to identify data, not carry it',
2878
+ 'invalid-date': 'it contains an invalid Date',
2879
+ };
2880
+ const why = REASONS[uncacheable_reason || ''] || 'it cannot be serialized deterministically';
2881
+ console.warn(`[JQHTML] <${name}> cannot be cached: arg $${uncacheable_property} is not keyable because ` +
2882
+ `${why}.\n` +
2883
+ ` The component works, but it will not be restored from cache when reused.\n` +
2884
+ ` Fix: define cache_id() on the component to state its identity explicitly, e.g.\n` +
2885
+ ` cache_id() { return \`${name.toLowerCase()}_\${this.args.some_id}\`; }\n` +
2886
+ ` Or pass plain data (objects/arrays of primitives are keyed automatically) instead of ` +
2887
+ `$${uncacheable_property}.\n` +
2888
+ ` Find it in DevTools with the selector ` +
2889
+ `[data-nocache="${uncacheable_property}:${uncacheable_reason || ''}"].`, {
2890
+ component: name,
2891
+ cid: component._cid,
2892
+ uncacheable_arg: uncacheable_property,
2893
+ reason: uncacheable_reason,
2894
+ all_args: component.args ? Object.keys(component.args) : [],
2895
+ });
2896
+ }
2897
+ /**
2898
+ * Read cache during create() phase.
2899
+ * Sets component._cache_key, _cached_html, _use_cached_data_hit as side effects.
2900
+ *
2901
+ * @param component - The component instance
2902
+ */
2903
+ function read_cache_in_create(component) {
2904
+ const { cache_key, uncacheable_property, uncacheable_reason } = generate_cache_key(component);
2905
+ // If cache_key is null, caching disabled
2906
+ if (cache_key === null) {
2907
+ // Set data-nocache attribute for debugging
2908
+ if (uncacheable_property) {
2909
+ // "<arg>:<reason>" - a bare property name left authors reverse-engineering why
2910
+ component.$.attr('data-nocache', uncacheable_reason ? `${uncacheable_property}:${uncacheable_reason}` : uncacheable_property);
2911
+ }
2912
+ warn_uncacheable_component(component, uncacheable_property, uncacheable_reason);
2913
+ if (window.jqhtml?.debug?.verbose) {
2914
+ console.log(`[Cache] Component ${component._cid} (${component.component_name()}) has non-serializable args - caching disabled`, { uncacheable_property });
2915
+ }
2916
+ return;
2917
+ }
2918
+ // Store cache key for later use
2919
+ component._cache_key = cache_key;
2920
+ // Get cache mode
2921
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2922
+ if (window.jqhtml?.debug?.verbose) {
2923
+ console.log(`[Cache ${cache_mode}] Component ${component._cid} (${component.component_name()}) checking cache in create()`, { cache_key, cache_mode, has_cache_key_set: Jqhtml_Local_Storage.has_cache_key() });
2924
+ }
2925
+ if (cache_mode === 'html') {
2926
+ // HTML cache mode - check for cached HTML to inject on first render
2927
+ const html_cache_key = `${cache_key}::html`;
2928
+ const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2929
+ if (cached_html !== null && typeof cached_html === 'string') {
2930
+ component._cached_html = cached_html;
2931
+ if (window.jqhtml?.debug?.verbose) {
2932
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.length });
2933
+ }
2934
+ }
2935
+ else {
2936
+ if (window.jqhtml?.debug?.verbose) {
2937
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) cache miss`, { cache_key: html_cache_key });
2938
+ }
2939
+ }
2940
+ // Warn if use_cached_data is set in html cache mode
2941
+ if (component.args.use_cached_data === true) {
2942
+ console.warn(`[JQHTML] Component "${component.component_name()}" has use_cached_data=true but cache mode is 'html'.\n` +
2943
+ `use_cached_data only applies to 'data' cache mode. In 'html' mode, the entire rendered HTML is cached.\n` +
2944
+ `The use_cached_data flag will be ignored.`);
2945
+ }
2946
+ }
2947
+ else {
2948
+ // Data cache mode (default) - check for cached data to hydrate this.data
2949
+ const cached_data = Jqhtml_Local_Storage.get(cache_key);
2950
+ if (cached_data !== null && typeof cached_data === 'object') {
2951
+ // Hydrate this.data with cached data
2952
+ component.data = cached_data;
2953
+ if (component.args.use_cached_data === true) {
2954
+ component._use_cached_data_hit = true;
2955
+ if (window.jqhtml?.debug?.verbose) {
2956
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) using cached data (use_cached_data=true, skipping on_load)`, { cache_key, data: cached_data });
2957
+ }
2958
+ }
2959
+ else {
2960
+ if (window.jqhtml?.debug?.verbose) {
2961
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) hydrated from cache`, { cache_key, data: cached_data });
2962
+ }
2963
+ }
2964
+ }
2965
+ else {
2966
+ if (window.jqhtml?.debug?.verbose) {
2967
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) cache miss`, { cache_key });
2968
+ }
2969
+ }
2970
+ }
2971
+ }
2972
+ /**
2973
+ * Check cache during reload() when args have changed.
2974
+ * If cache hit, hydrates data/html and triggers an immediate render.
2975
+ *
2976
+ * @param component - The component instance
2977
+ * @returns true if rendered from cache, false otherwise
2978
+ */
2979
+ function check_cache_on_reload(component) {
2980
+ const { cache_key } = generate_cache_key(component);
2981
+ if (cache_key === null) {
2982
+ return false;
2983
+ }
2984
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2985
+ component._cache_key = cache_key;
2986
+ if (cache_mode === 'html') {
2987
+ // HTML cache mode - check for cached HTML
2988
+ const html_cache_key = `${cache_key}::html`;
2989
+ const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2990
+ if (cached_html !== null && typeof cached_html === 'string') {
2991
+ if (window.jqhtml?.debug?.verbose) {
2992
+ console.log(`[Cache html] reload() - Component ${component._cid} (${component.component_name()}) found cached HTML (args changed)`, { cache_key: html_cache_key, html_length: cached_html.length });
2993
+ }
2994
+ component._cached_html = cached_html;
2995
+ // Call _render() directly (not render()) since _reload() manages the full lifecycle
2996
+ // Using render() would trigger a separate queue entry and interfere with _reload()'s flow
2997
+ component._render();
2998
+ return true;
2999
+ }
3000
+ }
3001
+ else {
3002
+ // Data cache mode (default) - check for cached data
3003
+ const cached_data = Jqhtml_Local_Storage.get(cache_key);
3004
+ if (cached_data !== null && typeof cached_data === 'object' && JSON.stringify(cached_data) !== '{}') {
3005
+ if (window.jqhtml?.debug?.verbose) {
3006
+ console.log(`[Cache data] reload() - Component ${component._cid} (${component.component_name()}) hydrated from cache (args changed)`, { cache_key, data: cached_data });
3007
+ }
3008
+ // Hydrate this.data with cached data
3009
+ component.__data_frozen = false;
3010
+ component.data = cached_data;
3011
+ component.__data_frozen = true;
3012
+ // Call _render() directly (not render()) since _reload() manages the full lifecycle
3013
+ component._render();
3014
+ return true;
3015
+ }
3016
+ }
3017
+ return false;
3018
+ }
3019
+ /**
3020
+ * Write HTML cache snapshot during ready() phase.
3021
+ * Only caches if the component is dynamic (data changed during on_load).
3022
+ *
3023
+ * @param component - The component instance
3024
+ */
3025
+ function write_html_cache_snapshot(component) {
3026
+ if (!component._should_cache_html_after_ready || !component._cache_key) {
3027
+ return;
3028
+ }
3029
+ if (component._is_dynamic) {
3030
+ component._should_cache_html_after_ready = false;
3031
+ const html = component.$.html();
3032
+ const html_cache_key = `${component._cache_key}::html`;
3033
+ Jqhtml_Local_Storage.set(html_cache_key, html);
3034
+ if (window.jqhtml?.debug?.verbose) {
3035
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) cached HTML after children on_render complete`, { cache_key: html_cache_key, html_length: html.length });
3036
+ }
3037
+ }
3038
+ else {
3039
+ component._should_cache_html_after_ready = false;
3040
+ if (window.jqhtml?.debug?.verbose) {
3041
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) is static (no data change) - skipping HTML cache`);
3042
+ }
3043
+ }
3044
+ }
3045
+ /**
3046
+ * Write data/HTML to cache after on_load() completes.
3047
+ * Called from _apply_load_result().
3048
+ *
3049
+ * @param component - The component instance
3050
+ * @param data_changed - Whether this.data changed during on_load
3051
+ */
3052
+ function write_cache_on_loaded(component, data_changed) {
3053
+ if (!data_changed || !component._cache_key) {
3054
+ return;
3055
+ }
3056
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
3057
+ if (cache_mode === 'html') {
3058
+ // HTML cache mode - flag to cache HTML after children ready in _ready()
3059
+ component._should_cache_html_after_ready = true;
3060
+ if (window.jqhtml?.debug?.verbose) {
3061
+ console.log(`[Cache html] Component ${component._cid} (${component.component_name()}) will cache HTML after ready`, { cache_key: component._cache_key });
3062
+ }
3063
+ }
3064
+ else {
3065
+ // Data cache mode (default) - write this.data to cache
3066
+ Jqhtml_Local_Storage.set(component._cache_key, component.data);
3067
+ if (window.jqhtml?.debug?.verbose) {
3068
+ console.log(`[Cache data] Component ${component._cid} (${component.component_name()}) cached data after on_load()`, { cache_key: component._cache_key, data: component.data });
3069
+ }
3070
+ }
3071
+ }
3072
+
3073
+ /**
3074
+ * JQHTML Component Lifecycle Queue
3075
+ *
3076
+ * Serializes lifecycle operations (render, reload, refresh) per component.
3077
+ * Replaces _create_debounced_function with a proper queue that:
3078
+ *
3079
+ * - At most one operation runs at a time per component
3080
+ * - At most one operation is pending (waiting for the current to finish)
3081
+ * - Same-type pending operations collapse (fan-in: all callers share one execution)
3082
+ * - Different-type pending operations: new replaces old (old callers get the new result)
3083
+ *
3084
+ * Boot bypasses this queue entirely - it runs the lifecycle directly.
3085
+ */
3086
+ class Component_Queue {
3087
+ constructor() {
3088
+ /** Currently executing operation */
3089
+ this._current = null;
3090
+ /** Next operation waiting to execute after current completes */
3091
+ this._pending = null;
3092
+ }
3093
+ /**
3094
+ * Enqueue a lifecycle operation.
3095
+ *
3096
+ * Behavior:
3097
+ * - Nothing running → execute immediately
3098
+ * - Something running, no pending → create pending entry
3099
+ * - Something running, same type pending → collapse (share pending promise)
3100
+ * - Something running, different type pending → replace pending (all callers get new result)
3101
+ *
3102
+ * @param type - Operation type ('render', 'reload', 'refresh', 'load')
3103
+ * @param executor - The async function to execute
3104
+ * @returns Promise that resolves when the operation completes
3105
+ */
3106
+ enqueue(type, executor) {
3107
+ // If nothing running, execute immediately
3108
+ if (!this._current) {
3109
+ return this._execute(type, executor);
3110
+ }
3111
+ // Something is running — add to pending
3112
+ if (this._pending) {
3113
+ if (this._pending.type === type) {
3114
+ // Same type pending → collapse (fan-in)
3115
+ // All callers share the same future execution
3116
+ return new Promise((resolve, reject) => {
3117
+ this._pending.resolvers.push(resolve);
3118
+ this._pending.rejecters.push(reject);
3119
+ });
3120
+ }
3121
+ else {
3122
+ // Different type pending → replace
3123
+ // Old pending callers join the new operation
3124
+ // (their operation was superseded by a different type)
3125
+ const old_resolvers = this._pending.resolvers;
3126
+ const old_rejecters = this._pending.rejecters;
3127
+ return new Promise((resolve, reject) => {
3128
+ this._pending = {
3129
+ type,
3130
+ executor,
3131
+ resolvers: [...old_resolvers, resolve],
3132
+ rejecters: [...old_rejecters, reject]
3133
+ };
3134
+ });
3135
+ }
3136
+ }
3137
+ // No pending entry yet — create one
3138
+ return new Promise((resolve, reject) => {
3139
+ this._pending = {
3140
+ type,
3141
+ executor,
3142
+ resolvers: [resolve],
3143
+ rejecters: [reject]
3144
+ };
3145
+ });
3146
+ }
3147
+ /**
3148
+ * Execute an operation and handle pending queue after completion.
3149
+ * @private
3150
+ */
3151
+ _execute(type, executor) {
3152
+ const promise = (async () => {
3153
+ try {
3154
+ await executor();
3155
+ }
3156
+ finally {
3157
+ this._current = null;
3158
+ // Run pending if exists
3159
+ if (this._pending) {
3160
+ const pending = this._pending;
3161
+ this._pending = null;
3162
+ try {
3163
+ await this._execute(pending.type, pending.executor);
3164
+ for (const resolve of pending.resolvers)
3165
+ resolve();
3166
+ }
3167
+ catch (err) {
3168
+ for (const reject of pending.rejecters)
3169
+ reject(err);
3170
+ }
3171
+ }
3172
+ }
3173
+ })();
3174
+ this._current = { type, promise };
3175
+ return promise;
3176
+ }
3177
+ /**
3178
+ * Check if any operation is currently running.
3179
+ */
3180
+ get is_busy() {
3181
+ return this._current !== null;
3182
+ }
3183
+ /**
3184
+ * Check if there's a pending operation waiting.
3185
+ */
3186
+ get has_pending() {
3187
+ return this._pending !== null;
3188
+ }
3189
+ }
3190
+
3191
+ /**
3192
+ * JQHTML SSR Preload Data System
3193
+ *
3194
+ * Captures component data during SSR rendering and replays it on the client
3195
+ * to skip redundant on_load() calls during hydration.
3196
+ *
3197
+ * Server-side: start_data_capture() → render → get_captured_data()
3198
+ * Client-side: set_preload_data(entries) → components boot with preloaded data → clear_preload_data()
3199
+ */
3200
+ // --- Capture (Server Side) ---
3201
+ let _capture_enabled = false;
3202
+ let _capture_buffer = [];
3203
+ // Track captured keys to avoid duplicates from Load Coordinator followers
3204
+ let _captured_keys = new Set();
3205
+ /**
3206
+ * Enable data capture mode. After this call, every component that completes
3207
+ * on_load() has its final this.data recorded.
3208
+ *
3209
+ * Idempotent — calling twice is fine.
3210
+ */
3211
+ function start_data_capture() {
3212
+ _capture_enabled = true;
3213
+ _capture_buffer = [];
3214
+ _captured_keys.clear();
3215
+ }
3216
+ /**
3217
+ * Record a component's data after on_load() completes.
3218
+ * Called internally from _apply_load_result().
3219
+ *
3220
+ * @param component_name - Component name
3221
+ * @param args - Component args at time of on_load()
3222
+ * @param data - this.data after on_load() completed
3223
+ * @param cache_key - The cache key for deduplication (null = always capture)
3224
+ */
3225
+ function capture_component_data(component_name, args, data, cache_key) {
3226
+ if (!_capture_enabled)
3227
+ return;
3228
+ // Deduplicate: if Load Coordinator already captured this key, skip
3229
+ if (cache_key !== null) {
3230
+ if (_captured_keys.has(cache_key))
3231
+ return;
3232
+ _captured_keys.add(cache_key);
3233
+ }
3234
+ // Deep clone args and data to plain objects (no proxies, no class instances)
3235
+ try {
3236
+ const cloned_args = JSON.parse(JSON.stringify(args));
3237
+ const cloned_data = JSON.parse(JSON.stringify(data));
3238
+ _capture_buffer.push({
3239
+ component: component_name,
3240
+ args: cloned_args,
3241
+ data: cloned_data,
3242
+ });
3243
+ }
3244
+ catch (error) {
3245
+ // Non-serializable data — skip capture for this component
3246
+ if (typeof console !== 'undefined') {
3247
+ console.warn(`[JQHTML SSR Capture] Failed to serialize data for ${component_name}:`, error);
3248
+ }
3249
+ }
3250
+ }
3251
+ /**
3252
+ * Returns all captured component data and resets the capture buffer.
3253
+ * One-shot: calling clears the buffer.
3254
+ */
3255
+ function get_captured_data() {
3256
+ const result = _capture_buffer;
3257
+ _capture_buffer = [];
3258
+ _captured_keys.clear();
3259
+ return result;
3260
+ }
3261
+ /**
3262
+ * Check if data capture is currently enabled.
3263
+ */
3264
+ function is_capture_enabled() {
3265
+ return _capture_enabled;
3266
+ }
3267
+ /**
3268
+ * Stop data capture and clear all state.
3269
+ */
3270
+ function stop_data_capture() {
3271
+ _capture_enabled = false;
3272
+ _capture_buffer = [];
3273
+ _captured_keys.clear();
3274
+ }
3275
+ // --- Preload (Client Side) ---
3276
+ let _preload_cache = new Map();
3277
+ /**
3278
+ * Seed the preload cache with SSR-captured data.
3279
+ * Must be called before any component _load() runs.
3280
+ *
3281
+ * @param entries - Array of { component, args, data } entries from get_captured_data()
3282
+ */
3283
+ function set_preload_data(entries) {
3284
+ if (!entries || entries.length === 0)
3285
+ return;
3286
+ _preload_cache.clear();
3287
+ for (const entry of entries) {
3288
+ // Generate key using the same algorithm as Load Coordinator
3289
+ const result = Load_Coordinator.generate_invocation_key(entry.component, entry.args);
3290
+ if (result.key !== null) {
3291
+ _preload_cache.set(result.key, entry.data);
3292
+ }
3293
+ }
3294
+ }
3295
+ /**
3296
+ * Check if preloaded data exists for a given cache key.
3297
+ * If found, returns the data and removes the entry (one-shot).
3298
+ *
3299
+ * @param cache_key - The cache key (same format as Load Coordinator)
3300
+ * @returns The preloaded data, or null if no match
3301
+ */
3302
+ function consume_preload_data(cache_key) {
3303
+ if (_preload_cache.size === 0)
3304
+ return null;
3305
+ const data = _preload_cache.get(cache_key);
3306
+ if (data !== undefined) {
3307
+ _preload_cache.delete(cache_key);
3308
+ return data;
3309
+ }
3310
+ return null;
3311
+ }
3312
+ /**
3313
+ * Clear any remaining unconsumed preload entries.
3314
+ * Call after initial page hydration is complete.
3315
+ */
3316
+ function clear_preload_data() {
3317
+ _preload_cache.clear();
3318
+ }
3319
+ /**
3320
+ * Check if any preload data is available (for fast early exit in _load).
3321
+ */
3322
+ function has_preload_data() {
3323
+ return _preload_cache.size > 0;
3324
+ }
3325
+
3326
+ /**
3327
+ * JQHTML Viewport Resize Dispatch
3328
+ *
3329
+ * One framework-owned, debounced window 'resize' listener fans out to every live
3330
+ * component in the document by calling on_viewport_resize(viewport_width).
3331
+ *
3332
+ * Components never bind their own window listener, so there is nothing to unbind
3333
+ * in on_stop() - a component that is stopped or removed from the document simply
3334
+ * stops being found by the dispatcher.
3335
+ */
3336
+ /** Trailing-edge debounce applied to the window resize listener. */
3337
+ const VIEWPORT_RESIZE_DEBOUNCE_MS = 30;
3338
+ let debounce_timer = null;
3339
+ let listener_installed = false;
3340
+ /**
3341
+ * Current viewport width in CSS pixels.
3342
+ *
3343
+ * window.innerWidth is used (not $(window).width()) because it matches the width
3344
+ * CSS media queries resolve against. It includes the scrollbar gutter.
3345
+ *
3346
+ * Returns 0 outside a browser (SSR).
3347
+ */
3348
+ function get_viewport_width() {
3349
+ return typeof window !== 'undefined' ? window.innerWidth : 0;
3350
+ }
3351
+ /**
3352
+ * Call on_viewport_resize(width) on every component currently in the document.
3353
+ *
3354
+ * Walks $('.Component') in document order (parents before children). Elements
3355
+ * with no component instance and stopped components are skipped. A component
3356
+ * that throws is logged and the walk continues - one bad handler must not stop
3357
+ * the rest of the page from resizing.
3358
+ */
3359
+ function dispatch_viewport_resize(jQuery) {
3360
+ const viewport_width = get_viewport_width();
3361
+ jQuery('.Component').each(function () {
3362
+ const component = jQuery(this).data('_component');
3363
+ if (!component || component._stopped)
3364
+ return;
3365
+ if (typeof component.on_viewport_resize !== 'function')
3366
+ return;
3367
+ try {
3368
+ component.on_viewport_resize(viewport_width);
3369
+ }
3370
+ catch (error) {
3371
+ console.error(`[JQHTML] Error in on_viewport_resize() for ${component.component_name?.() || 'component'}:`, error);
3372
+ }
3373
+ });
3374
+ }
3375
+ /**
3376
+ * Install the single window resize listener. Idempotent - repeated init() calls
3377
+ * and non-browser environments are no-ops.
3378
+ */
3379
+ function init_viewport_resize(jQuery) {
3380
+ if (typeof window === 'undefined')
3381
+ return;
3382
+ if (listener_installed)
3383
+ return;
3384
+ listener_installed = true;
3385
+ jQuery(window).on('resize.jqhtml_viewport', function () {
3386
+ if (debounce_timer !== null)
3387
+ clearTimeout(debounce_timer);
3388
+ debounce_timer = setTimeout(function () {
3389
+ debounce_timer = null;
3390
+ dispatch_viewport_resize(jQuery);
3391
+ }, VIEWPORT_RESIZE_DEBOUNCE_MS);
3392
+ });
3393
+ }
3394
+
2148
3395
  /**
2149
3396
  * JQHTML v2 Component Base Class
2150
3397
  *
@@ -2175,6 +3422,7 @@ class Jqhtml_Component {
2175
3422
  this._data_on_last_render = null; // Data snapshot from last render (for refresh() comparison)
2176
3423
  this.__initial_data_snapshot = null; // Snapshot of this.data after on_create() for restoration before on_load()
2177
3424
  this.__data_frozen = false; // Track if this.data is currently frozen
3425
+ this._queue = new Component_Queue(); // Lifecycle operation queue (render/reload/refresh)
2178
3426
  this.next_reload_force_refresh = null; // State machine for reload()/refresh() debounce precedence
2179
3427
  this.__lifecycle_authorized = false; // Flag for lifecycle method protection
2180
3428
  // Cache mode properties
@@ -2188,12 +3436,17 @@ class Jqhtml_Component {
2188
3436
  this._on_render_complete = false; // True after on_render() has been called post-on_load
2189
3437
  // use_cached_data feature - skip on_load() when cache hit occurs
2190
3438
  this._use_cached_data_hit = false; // True if use_cached_data=true AND cache was used
2191
- // skip_render_and_ready feature - skip first render/on_render and on_ready entirely
2192
- // Component reports ready after on_load completes
2193
- this._skip_render_and_ready = false;
2194
- // skip_ready feature - skip on_ready only
2195
- // Component reports ready after on_render completes
2196
- this._skip_ready = false;
3439
+ // _load_only: create + load only. No render, no children, no on_render, no on_loaded, no on_ready.
3440
+ this._load_only = false;
3441
+ // _load_render_only: create + render + load + re-render. No on_render, no on_loaded, no on_ready.
3442
+ this._load_render_only = false;
3443
+ // Detached optimization: true when element is not in the DOM at boot time.
3444
+ // Skips initial render and cache read — just on_load then render.
3445
+ // Override with _force_initial_render to keep normal double-render behavior.
3446
+ this._is_detached = false;
3447
+ // _force_initial_render: override detached optimization — render even when not in DOM.
3448
+ // Use when you need the loading spinner visible immediately after appending.
3449
+ this._force_initial_render = false;
2197
3450
  // rendered event - fires once after the synchronous render chain completes
2198
3451
  // (after on_load's re-render if applicable, or after first render if no on_load)
2199
3452
  this._has_rendered = false;
@@ -2204,6 +3457,11 @@ class Jqhtml_Component {
2204
3457
  // Set in constructor (prototype chain is established before constructor runs)
2205
3458
  // Used to skip expensive cache/load operations for static components
2206
3459
  this.__has_custom_on_load = false;
3460
+ // gate_load() — "load gates" registered during on_create() that must settle
3461
+ // before the component's FIRST on_load() runs. See gate_load() / _await_load_gates().
3462
+ this.__load_gates = []; // Pending gates (cleared once the first load begins)
3463
+ this.__first_load_started = false; // Latch: true once the first load phase begins (enforces one-shot + throw-after)
3464
+ this.__gate_resume = null; // Resolver to release an in-progress gate wait early (reload/refresh/stop)
2207
3465
  // Detect custom on_load() override immediately
2208
3466
  // Prototype chain is set up before constructor runs, so this.on_load
2209
3467
  // correctly resolves to child class override if one exists
@@ -2245,84 +3503,27 @@ class Jqhtml_Component {
2245
3503
  // Merge in order: defineArgs (defaults from Define tag) < dataAttrs < args (invocation overrides)
2246
3504
  const defineArgs = template_for_args?.defineArgs || {};
2247
3505
  this.args = { ...defineArgs, ...dataAttrs, ...args };
2248
- // Set lifecycle skip flags from args
2249
- if (this.args.skip_render_and_ready === true) {
2250
- this._skip_render_and_ready = true;
3506
+ // Set lifecycle truncation flags from args
3507
+ if (this.args._load_only === true) {
3508
+ this._load_only = true;
2251
3509
  }
2252
- if (this.args.skip_ready === true) {
2253
- this._skip_ready = true;
2254
- }
2255
- // Attach component to element
2256
- this.$.data('_component', this);
2257
- // Apply CSS classes and attributes
2258
- this._apply_css_classes();
2259
- this._apply_default_attributes(); // Apply defaultAttributes from template
2260
- this._set_attributes();
2261
- // Find DOM parent component (for lifecycle coordination)
2262
- this._find_dom_parent();
2263
- // Setup data property with freeze enforcement using Proxy
2264
- let _data = {};
2265
- // Helper to create frozen proxy for data object
2266
- const createDataProxy = (obj) => {
2267
- return new Proxy(obj, {
2268
- set: (target, prop, value) => {
2269
- if (this.__data_frozen) {
2270
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to modify this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2271
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2272
- ` - on_create() (set initial defaults, synchronous only)\n` +
2273
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2274
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2275
- `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2276
- ` ❌ In on_ready(): this.data.${String(prop)} = ${JSON.stringify(value)};\n` +
2277
- ` ✅ In on_create(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Set default\n` +
2278
- ` ✅ In on_load(): this.data.${String(prop)} = ${JSON.stringify(value)}; // Fetch from API\n` +
2279
- ` ✅ For component state: this.args.${String(prop)} = ${JSON.stringify(value)}; (accessible in on_load)`);
2280
- throw new Error(`[JQHTML] Cannot modify this.data.${String(prop)} outside of on_create() or on_load(). ` +
2281
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2282
- }
2283
- target[prop] = value;
2284
- return true;
2285
- },
2286
- deleteProperty: (target, prop) => {
2287
- if (this.__data_frozen) {
2288
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to delete this.data.${String(prop)} outside of on_create() or on_load().\n\n` +
2289
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2290
- ` - on_create() (set initial defaults, synchronous only)\n` +
2291
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2292
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.`);
2293
- throw new Error(`[JQHTML] Cannot delete this.data.${String(prop)} outside of on_create() or on_load(). ` +
2294
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2295
- }
2296
- delete target[prop];
2297
- return true;
2298
- }
2299
- });
2300
- };
2301
- // Create initial proxied data object
2302
- _data = createDataProxy({});
2303
- Object.defineProperty(this, 'data', {
2304
- get: () => _data,
2305
- set: (value) => {
2306
- if (this.__data_frozen) {
2307
- console.error(`[JQHTML] ERROR: Component "${this.component_name()}" attempted to reassign this.data outside of on_create() or on_load().\n\n` +
2308
- `RESTRICTION: this.data can ONLY be modified in:\n` +
2309
- ` - on_create() (set initial defaults, synchronous only)\n` +
2310
- ` - on_load() (fetch data from APIs, can be async)\n\n` +
2311
- `WHY: this.data represents loaded state. Modifying it outside these methods bypasses the framework's render cycle.\n\n` +
2312
- `FIX: Modify this.data in on_create() (for defaults) or on_load() (for fetched data):\n` +
2313
- ` ❌ In on_ready(): this.data = {...};\n` +
2314
- ` ✅ In on_create(): this.data.count = 0; // Set default\n` +
2315
- ` ✅ In on_load(): this.data = await fetch(...); // Fetch from API\n` +
2316
- ` ✅ For component state: this.args.count = 5; (accessible in on_load)`);
2317
- throw new Error(`[JQHTML] Cannot reassign this.data outside of on_create() or on_load(). ` +
2318
- `this.data is frozen after on_create() and unfrozen only during on_load().`);
2319
- }
2320
- // When setting, wrap the new value in a proxy too
2321
- _data = createDataProxy(value);
2322
- },
2323
- enumerable: true,
2324
- configurable: false
2325
- });
3510
+ if (this.args._load_render_only === true) {
3511
+ this._load_render_only = true;
3512
+ }
3513
+ if (this.args._force_initial_render === true) {
3514
+ this._force_initial_render = true;
3515
+ }
3516
+ // Attach component to element
3517
+ this.$.data('_component', this);
3518
+ // Apply CSS classes and attributes
3519
+ this._apply_css_classes();
3520
+ this._apply_default_attributes(); // Apply defaultAttributes from template
3521
+ this._set_attributes();
3522
+ // Find DOM parent component (for lifecycle coordination)
3523
+ this._find_dom_parent();
3524
+ // Setup data property with freeze enforcement using Proxy
3525
+ // @see data-proxy.ts for full implementation
3526
+ setup_data_property(this);
2326
3527
  // Initialize this.state as an empty object (convention for arbitrary component state)
2327
3528
  // No special meaning to framework - mutable anywhere, not cached, not frozen
2328
3529
  this.state = {};
@@ -2385,6 +3586,21 @@ class Jqhtml_Component {
2385
3586
  // Call original directly - no flag needed since we bypass the wrapper
2386
3587
  return impl.call(this);
2387
3588
  }
3589
+ /**
3590
+ * Fire on_viewport_resize() with the current viewport width.
3591
+ * Called after every on_render() and on_ready(); the debounced window
3592
+ * listener in viewport.ts drives it from then on. Errors are isolated so a
3593
+ * bad handler cannot break the lifecycle.
3594
+ * @private
3595
+ */
3596
+ _fire_viewport_resize() {
3597
+ try {
3598
+ this.on_viewport_resize(get_viewport_width());
3599
+ }
3600
+ catch (error) {
3601
+ console.error(`[JQHTML] Error in on_viewport_resize() for ${this.component_name()}:`, error);
3602
+ }
3603
+ }
2388
3604
  /**
2389
3605
  * Check if on_load() is overridden in a subclass
2390
3606
  * Used to skip the load phase entirely for components that don't fetch data
@@ -2424,7 +3640,7 @@ class Jqhtml_Component {
2424
3640
  * @returns The current _render_count after incrementing (used to detect stale renders)
2425
3641
  * @private
2426
3642
  */
2427
- _render(id = null) {
3643
+ _render(id = null, options = {}) {
2428
3644
  // Increment render count to track this specific render
2429
3645
  this._render_count++;
2430
3646
  const current_render_id = this._render_count;
@@ -2445,7 +3661,7 @@ class Jqhtml_Component {
2445
3661
  `Element with $sid="${id}" exists but is not initialized as a component.\n` +
2446
3662
  `Add $redrawable attribute or make it a proper component.`);
2447
3663
  }
2448
- return child._render();
3664
+ return child._render(null, options);
2449
3665
  }
2450
3666
  this._log_lifecycle('render', 'start');
2451
3667
  // HTML CACHE MODE - If we have cached HTML, inject it directly and skip template rendering
@@ -2462,13 +3678,14 @@ class Jqhtml_Component {
2462
3678
  // Mark first render complete
2463
3679
  this._did_first_render = true;
2464
3680
  this._log_lifecycle('render', 'complete (cached HTML)');
2465
- // NEW ARCHITECTURE: Call on_render() even after cache inject
2466
- // This ensures consistent behavior - on_render() always runs after DOM update
2467
- // Note: this.data has defaults from on_create(), not fresh data yet
2468
- const cacheRenderResult = this._call_lifecycle_sync('on_render');
2469
- if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
2470
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
2471
- `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3681
+ // Call on_render() after cache inject (unless suppressed by _load_render_only)
3682
+ if (!options.skip_on_render) {
3683
+ const cacheRenderResult = this._call_lifecycle_sync('on_render');
3684
+ if (cacheRenderResult && typeof cacheRenderResult.then === 'function') {
3685
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
3686
+ `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3687
+ }
3688
+ this._fire_viewport_resize();
2472
3689
  }
2473
3690
  // Emit lifecycle event
2474
3691
  this.trigger('render');
@@ -2653,18 +3870,14 @@ class Jqhtml_Component {
2653
3870
  // Don't update ready state here - let phases complete in order
2654
3871
  this._update_debug_attrs();
2655
3872
  this._log_lifecycle('render', 'complete');
2656
- // Call on_render() with authorization (sync) immediately after render completes
2657
- // This ensures event handlers are always re-attached after DOM updates
2658
- //
2659
- // NEW ARCHITECTURE: on_render() can now access this.data normally
2660
- // The HTML cache mode now properly synchronizes - on_render() runs after both:
2661
- // 1. Cache inject (with on_create() defaults)
2662
- // 2. Second render (with fresh data from on_load())
2663
- // Since on_render() always runs with appropriate data, no proxy restriction needed
2664
- const renderResult = this._call_lifecycle_sync('on_render');
2665
- if (renderResult && typeof renderResult.then === 'function') {
2666
- console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
2667
- `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3873
+ // Call on_render() after render completes (unless suppressed by _load_render_only)
3874
+ if (!options.skip_on_render) {
3875
+ const renderResult = this._call_lifecycle_sync('on_render');
3876
+ if (renderResult && typeof renderResult.then === 'function') {
3877
+ console.warn(`[JQHTML] Component "${this.component_name()}" returned a Promise from on_render(). ` +
3878
+ `on_render() must be synchronous code. Remove 'async' from the function declaration.`);
3879
+ }
3880
+ this._fire_viewport_resize();
2668
3881
  }
2669
3882
  // Emit lifecycle event
2670
3883
  this.trigger('render');
@@ -2694,18 +3907,18 @@ class Jqhtml_Component {
2694
3907
  * Public render method - re-renders component and completes lifecycle
2695
3908
  * This is what users should call when they want to update a component.
2696
3909
  *
2697
- * Lifecycle sequence:
3910
+ * Lifecycle sequence (serialized via component queue):
2698
3911
  * 1. _render() - Updates DOM synchronously, calls on_render(), fires 'render' event
2699
- * 2. Async continuation (fire and forget):
2700
- * - _wait_for_children_ready() - Waits for all children to reach ready state
2701
- * - on_ready() - Calls user's ready hook
2702
- * - trigger('ready') - Fires ready event
3912
+ * 2. _wait_for_children_ready() - Waits for all children to reach ready state
3913
+ * 3. on_ready() - Calls user's ready hook
3914
+ * 4. trigger('ready') - Fires ready event
2703
3915
  *
2704
- * Returns immediately after _render() completes - does NOT wait for children
3916
+ * Goes through the component queue to prevent concurrent lifecycle operations.
3917
+ * Returns a Promise that resolves when the full render lifecycle completes.
2705
3918
  */
2706
3919
  render(id = null) {
2707
3920
  if (this._stopped)
2708
- return;
3921
+ return Promise.resolve();
2709
3922
  // Invalidate ready event so new handlers wait for this render cycle to complete
2710
3923
  // This prevents .on('ready') handlers from firing immediately based on previous lifecycle
2711
3924
  this.invalidate('ready');
@@ -2724,10 +3937,12 @@ class Jqhtml_Component {
2724
3937
  }
2725
3938
  return child.render();
2726
3939
  }
2727
- // Execute render phase synchronously and capture render ID
2728
- const render_id = this._render();
2729
- // Fire off async lifecycle completion in background (don't await)
2730
- (async () => {
3940
+ // Enqueue the full render lifecycle through the component queue
3941
+ // Return the queue promise so `await this.render()` resolves when the
3942
+ // full render lifecycle (DOM update, children ready, on_ready) completes
3943
+ return this._queue.enqueue('render', async () => {
3944
+ // Execute render phase synchronously and capture render ID
3945
+ const render_id = this._render();
2731
3946
  // Wait for all child components to be ready
2732
3947
  await this._wait_for_children_ready();
2733
3948
  // Check if this render is still current before calling on_ready
@@ -2737,9 +3952,10 @@ class Jqhtml_Component {
2737
3952
  }
2738
3953
  // Call on_ready hook with authorization
2739
3954
  await this._call_lifecycle('on_ready');
3955
+ this._fire_viewport_resize();
2740
3956
  // Trigger ready event
2741
- await this.trigger('ready');
2742
- })();
3957
+ this.trigger('ready');
3958
+ });
2743
3959
  }
2744
3960
  /**
2745
3961
  * Alias for render() - re-renders component with current data
@@ -2748,6 +3964,70 @@ class Jqhtml_Component {
2748
3964
  redraw(id = null) {
2749
3965
  return this.render(id);
2750
3966
  }
3967
+ /**
3968
+ * Re-fetch data by executing on_load() without triggering re-render or lifecycle.
3969
+ *
3970
+ * Runs on_load() on a detached proxy (same restrictions as during boot):
3971
+ * - this.data is restored to on_create() snapshot, then unfrozen for writing
3972
+ * - this.args is read-only
3973
+ * - All other properties (this.$, this.$sid, etc.) are blocked
3974
+ *
3975
+ * After on_load() completes, this.data is atomically updated and re-frozen.
3976
+ * The developer decides what to do next (e.g., call this.render()).
3977
+ *
3978
+ * Pattern: load() invokes on_load(), just as render() invokes on_render().
3979
+ *
3980
+ * @returns true if this.data changed, false if unchanged
3981
+ */
3982
+ async load() {
3983
+ if (this._stopped)
3984
+ return false;
3985
+ // Capture result through queue closure
3986
+ let data_changed = false;
3987
+ await this._queue.enqueue('load', async () => {
3988
+ // Snapshot current data for change detection
3989
+ const data_before = JSON.stringify(this.data);
3990
+ // Execute on_load() on detached proxy (restores data to on_create snapshot)
3991
+ const { data: result_data } = await this._execute_on_load_detached(false);
3992
+ // Atomically update this.data: unfreeze → assign → normalize → refreeze
3993
+ this.__data_frozen = false;
3994
+ this.data = result_data;
3995
+ const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
3996
+ if (cache_mode === 'data') {
3997
+ const normalized = Jqhtml_Local_Storage.normalize_for_cache(this.data);
3998
+ this.data = normalized;
3999
+ }
4000
+ this.__data_frozen = true;
4001
+ // Detect if data changed
4002
+ const data_after = JSON.stringify(this.data);
4003
+ data_changed = data_before !== data_after;
4004
+ // Update cache with fresh data if changed
4005
+ if (data_changed) {
4006
+ // Regenerate cache key (args may have changed since boot)
4007
+ let cache_key = null;
4008
+ if (typeof this.cache_id === 'function') {
4009
+ try {
4010
+ cache_key = `${this.component_name()}::${String(this.cache_id())}`;
4011
+ }
4012
+ catch { /* cache_id() threw - skip caching */ }
4013
+ }
4014
+ else {
4015
+ const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
4016
+ cache_key = result.key;
4017
+ }
4018
+ if (cache_key && cache_mode !== 'html') {
4019
+ Jqhtml_Local_Storage.set(cache_key, this.data);
4020
+ }
4021
+ }
4022
+ // Call on_loaded() on the real component (this.data frozen, full access to this.$, this.state)
4023
+ // Suppressed by _load_only and _load_render_only flags (preloading mode)
4024
+ if (!this._load_only && !this._load_render_only) {
4025
+ await this._call_lifecycle('on_loaded');
4026
+ this.trigger('loaded');
4027
+ }
4028
+ });
4029
+ return data_changed;
4030
+ }
2751
4031
  /**
2752
4032
  * Create phase - Quick setup, prepare UI
2753
4033
  * SYNCHRONOUS - no awaits, no yields
@@ -2763,97 +4043,17 @@ class Jqhtml_Component {
2763
4043
  `on_create() must be synchronous code. Remove 'async' from the function declaration.`);
2764
4044
  // Don't await - on_create MUST be sync. The warning is enough.
2765
4045
  }
4046
+ // Detect detached elements — skip cache and initial render for elements not in DOM
4047
+ // _force_initial_render overrides this optimization
4048
+ this._is_detached = !this.$[0].isConnected && !this._force_initial_render;
2766
4049
  // OPTIMIZATION: Skip cache operations and snapshot if no custom on_load()
2767
4050
  // Components without on_load() don't fetch data, so nothing to cache or restore
2768
4051
  if (this.__has_custom_on_load) {
2769
4052
  // CACHE CHECK - Read from cache based on cache mode ('data' or 'html')
2770
- // This happens after on_create() but before render, allowing instant first render
2771
- // Check if component implements cache_id() for custom cache key
2772
- let cache_key = null;
2773
- let uncacheable_property;
2774
- if (typeof this.cache_id === 'function') {
2775
- try {
2776
- const custom_cache_id = this.cache_id();
2777
- cache_key = `${this.component_name()}::${String(custom_cache_id)}`;
2778
- }
2779
- catch (error) {
2780
- // cache_id() threw error - disable caching
2781
- uncacheable_property = 'cache_id()';
2782
- }
2783
- }
2784
- else {
2785
- // Use standard args-based cache key generation
2786
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
2787
- cache_key = result.key;
2788
- uncacheable_property = result.uncacheable_property;
2789
- }
2790
- // If cache_key is null, caching disabled
2791
- if (cache_key === null) {
2792
- // Set data-nocache attribute for debugging (shows which property prevented caching)
2793
- if (uncacheable_property) {
2794
- this.$.attr('data-nocache', uncacheable_property);
2795
- }
2796
- if (window.jqhtml?.debug?.verbose) {
2797
- console.log(`[Cache] Component ${this._cid} (${this.component_name()}) has non-serializable args - caching disabled`, { uncacheable_property });
2798
- }
2799
- // Don't return - continue to snapshot this.data for on_load restoration
2800
- }
2801
- else {
2802
- // Store cache key for later use
2803
- this._cache_key = cache_key;
2804
- // Get cache mode
2805
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
2806
- if (window.jqhtml?.debug?.verbose) {
2807
- console.log(`[Cache ${cache_mode}] Component ${this._cid} (${this.component_name()}) checking cache in create()`, { cache_key, cache_mode, has_cache_key_set: Jqhtml_Local_Storage.has_cache_key() });
2808
- }
2809
- if (cache_mode === 'html') {
2810
- // HTML cache mode - check for cached HTML to inject on first render
2811
- const html_cache_key = `${cache_key}::html`;
2812
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
2813
- if (cached_html !== null && typeof cached_html === 'string') {
2814
- // Store cached HTML for injection in _render()
2815
- this._cached_html = cached_html;
2816
- if (window.jqhtml?.debug?.verbose) {
2817
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) found cached HTML`, { cache_key: html_cache_key, html_length: cached_html.length });
2818
- }
2819
- }
2820
- else {
2821
- if (window.jqhtml?.debug?.verbose) {
2822
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) cache miss`, { cache_key: html_cache_key });
2823
- }
2824
- }
2825
- // Warn if use_cached_data is set in html cache mode - it has no effect
2826
- if (this.args.use_cached_data === true) {
2827
- console.warn(`[JQHTML] Component "${this.component_name()}" has use_cached_data=true but cache mode is 'html'.\n` +
2828
- `use_cached_data only applies to 'data' cache mode. In 'html' mode, the entire rendered HTML is cached.\n` +
2829
- `The use_cached_data flag will be ignored.`);
2830
- }
2831
- }
2832
- else {
2833
- // Data cache mode (default) - check for cached data to hydrate this.data
2834
- const cached_data = Jqhtml_Local_Storage.get(cache_key);
2835
- if (cached_data !== null && typeof cached_data === 'object') {
2836
- // Hydrate this.data with cached data
2837
- this.data = cached_data;
2838
- // If use_cached_data=true, skip on_load() entirely - use cached data as final data
2839
- if (this.args.use_cached_data === true) {
2840
- this._use_cached_data_hit = true;
2841
- if (window.jqhtml?.debug?.verbose) {
2842
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) using cached data (use_cached_data=true, skipping on_load)`, { cache_key, data: cached_data });
2843
- }
2844
- }
2845
- else {
2846
- if (window.jqhtml?.debug?.verbose) {
2847
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) hydrated from cache`, { cache_key, data: cached_data });
2848
- }
2849
- }
2850
- }
2851
- else {
2852
- if (window.jqhtml?.debug?.verbose) {
2853
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) cache miss`, { cache_key });
2854
- }
2855
- }
2856
- }
4053
+ // Skip cache for detached elements — no point hydrating from cache when not in DOM
4054
+ // @see component-cache.ts for full implementation
4055
+ if (!this._is_detached) {
4056
+ read_cache_in_create(this);
2857
4057
  }
2858
4058
  // Snapshot this.data after on_create() completes
2859
4059
  // This will be restored before each on_load() execution to reset state
@@ -2867,6 +4067,90 @@ class Jqhtml_Component {
2867
4067
  // Emit lifecycle event
2868
4068
  this.trigger('create');
2869
4069
  }
4070
+ /**
4071
+ * Register a "load gate" — a promise that must settle before this component's
4072
+ * FIRST on_load() runs.
4073
+ *
4074
+ * Register gates during on_create(). Multiple calls accumulate; all gates are
4075
+ * awaited together (via Promise.allSettled) at the seam between create and the
4076
+ * first load. A REJECTED gate does NOT block or abort the load — it is an
4077
+ * ordering hint, not a data dependency, so loading proceeds after settlement
4078
+ * (rejections are logged through the debug channel).
4079
+ *
4080
+ * Gates are ONE-SHOT: they delay the first on_load() only. Once that load
4081
+ * begins the gate list is cleared, and reload()/refresh() never re-await gates.
4082
+ * Calling reload()/refresh() while a gate is still holding the first load
4083
+ * releases the wait immediately and resumes the lifecycle (a later gate
4084
+ * settlement then does nothing).
4085
+ *
4086
+ * Gates delay ONLY the on_load phase — never create(), the initial render,
4087
+ * on_render(), or the cached-content first paint (stale-while-revalidate is
4088
+ * preserved). Components with no custom on_load() ignore gates entirely.
4089
+ *
4090
+ * No-op during SSR (the server cannot await arbitrary client promises).
4091
+ *
4092
+ * jqhtml has no knowledge of WHAT is being awaited — the caller supplies the
4093
+ * promise, and policy such as timeouts is the caller's responsibility (bake it
4094
+ * into the promise you pass).
4095
+ *
4096
+ * @param promise The promise to await before the first on_load().
4097
+ * @throws If called after the component's first load has already started.
4098
+ */
4099
+ gate_load(promise) {
4100
+ if (this.__first_load_started) {
4101
+ throw new Error(`[JQHTML] gate_load() may only be called before the component's first load - ` +
4102
+ `register gates in on_create(). ` +
4103
+ `Component: ${this.component_name()} (_cid: ${this._cid})`);
4104
+ }
4105
+ this.__load_gates.push(promise);
4106
+ }
4107
+ /**
4108
+ * Await all registered load gates before the first on_load().
4109
+ *
4110
+ * Called exactly once, at the boot seam immediately before the load phase
4111
+ * (only for components with a custom on_load()). Latches "first load started"
4112
+ * so any later gate_load() throws and reload()/refresh() never re-await.
4113
+ *
4114
+ * Returns a promise to await when there are gates to wait on, or `null` when
4115
+ * there is nothing to wait for (no gates, or SSR). Returning `null` keeps the
4116
+ * common no-gate path free of an extra microtask hop, so it does not shift the
4117
+ * timing of ungated components.
4118
+ *
4119
+ * The returned promise resolves as soon as any of the following happens
4120
+ * (whichever is first — the rest become no-ops):
4121
+ * - all gates settle (Promise.allSettled),
4122
+ * - reload()/refresh() is called while gated (they resolve __gate_resume),
4123
+ * - the component is stopped (stop() resolves __gate_resume).
4124
+ *
4125
+ * @private
4126
+ */
4127
+ _await_load_gates() {
4128
+ // Latch (synchronous): from here on, gate_load() throws and this runs at
4129
+ // most once — set even when there are no gates so point 2 always holds.
4130
+ this.__first_load_started = true;
4131
+ const gates = this.__load_gates;
4132
+ this.__load_gates = [];
4133
+ // Nothing to gate, or SSR (cannot await arbitrary client promises) — proceed now.
4134
+ if (gates.length === 0 || is_capture_enabled())
4135
+ return null;
4136
+ // Promise.allSettled never rejects; rejected gates are logged (debug channel)
4137
+ // whenever they settle, independent of whether the wait was resumed early.
4138
+ const settled = Promise.allSettled(gates);
4139
+ settled.then((results) => {
4140
+ for (const result of results) {
4141
+ if (result.status === 'rejected' && window.jqhtml?.debug?.verbose) {
4142
+ console.log(`[JQHTML gate_load] Component ${this._cid} (${this.component_name()}) gate rejected (ignored, load proceeds)`, result.reason);
4143
+ }
4144
+ }
4145
+ });
4146
+ // Race gate settlement against an early-resume signal (reload/refresh/stop while gated).
4147
+ return new Promise((resolve) => {
4148
+ this.__gate_resume = resolve;
4149
+ settled.then(() => resolve());
4150
+ }).then(() => {
4151
+ this.__gate_resume = null;
4152
+ });
4153
+ }
2870
4154
  /**
2871
4155
  * Load phase - Fetch asynchronous data
2872
4156
  * Called bottom-up, fully parallel
@@ -2889,11 +4173,24 @@ class Jqhtml_Component {
2889
4173
  this._update_debug_attrs();
2890
4174
  this._log_lifecycle('load', 'complete (use_cached_data - skipped on_load)');
2891
4175
  this.trigger('load');
4176
+ if (!this._load_only && !this._load_render_only) {
4177
+ await this._call_lifecycle('on_loaded');
4178
+ this.trigger('loaded');
4179
+ }
2892
4180
  return;
2893
4181
  }
2894
- // Check if component implements cache_id() for custom cache key
4182
+ // TWO identities, deliberately computed separately.
4183
+ //
4184
+ // cache_key - may key a plain-data object arg by deterministic CONTENT, and may come
4185
+ // from the author's cache_id(). A wrong key here is corrected by
4186
+ // stale-while-revalidate.
4187
+ // dedup_key - args only, no content serialization, no cache_id(). A deduplicated
4188
+ // follower never runs on_load() and adopts the leader's data with NO
4189
+ // revalidation, so a wrong key here is permanently wrong data. Redundant
4190
+ // concurrent requests are the cheaper failure.
2895
4191
  let cache_key = null;
2896
4192
  let uncacheable_property;
4193
+ let uncacheable_reason;
2897
4194
  if (typeof this.cache_id === 'function') {
2898
4195
  try {
2899
4196
  const custom_cache_id = this.cache_id();
@@ -2902,33 +4199,49 @@ class Jqhtml_Component {
2902
4199
  catch (error) {
2903
4200
  // cache_id() threw error - disable caching
2904
4201
  uncacheable_property = 'cache_id()';
4202
+ uncacheable_reason = 'cache-id-threw';
2905
4203
  }
2906
4204
  }
2907
4205
  else {
2908
- // Use standard args-based cache key generation
2909
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
4206
+ const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args, { allow_content_serialization: true });
2910
4207
  cache_key = result.key;
2911
4208
  uncacheable_property = result.uncacheable_property;
4209
+ uncacheable_reason = result.uncacheable_reason;
4210
+ }
4211
+ const dedup_key = Load_Coordinator.generate_invocation_key(this.component_name(), this.args).key;
4212
+ // SSR preload check: if preloaded data exists for this component+args, use it
4213
+ if (cache_key !== null && has_preload_data()) {
4214
+ const preloaded_data = consume_preload_data(cache_key);
4215
+ if (preloaded_data !== null) {
4216
+ this._cache_key = cache_key;
4217
+ if (window.jqhtml?.debug?.verbose) {
4218
+ console.log(`[SSR Preload] Component ${this._cid} (${this.component_name()}) using preloaded data`, { cache_key });
4219
+ }
4220
+ const data_before_load = JSON.stringify(this.data);
4221
+ await this._apply_load_result(preloaded_data, data_before_load);
4222
+ return;
4223
+ }
2912
4224
  }
2913
4225
  // Store cache key for later use
2914
4226
  this._cache_key = cache_key;
2915
- // If cache_key is null, args are not serializable - skip load deduplication and caching
2916
- if (cache_key === null) {
2917
- // Set data-nocache attribute for debugging (shows which property prevented caching)
2918
- if (uncacheable_property) {
2919
- this.$.attr('data-nocache', uncacheable_property);
4227
+ // Caching disabled - mark the element with the offending arg AND why
4228
+ if (cache_key === null && uncacheable_property) {
4229
+ this.$.attr('data-nocache', uncacheable_reason ? `${uncacheable_property}:${uncacheable_reason}` : uncacheable_property);
4230
+ if (window.jqhtml?.debug?.verbose) {
4231
+ console.log(`[Cache] Component ${this._cid} (${this.component_name()}) has non-keyable args - caching disabled`, { uncacheable_property, uncacheable_reason });
2920
4232
  }
4233
+ }
4234
+ // Store "before" snapshot for comparison after on_load()
4235
+ const data_before_load = JSON.stringify(this.data);
4236
+ // No dedup identity - run on_load() alone rather than risk sharing a load
4237
+ if (dedup_key === null) {
2921
4238
  if (window.jqhtml?.debug?.verbose) {
2922
- console.log(`[Cache] Component ${this._cid} (${this.component_name()}) has non-serializable args - load deduplication and caching disabled`, { uncacheable_property });
4239
+ console.log(`[Load Deduplication] Component ${this._cid} (${this.component_name()}) has no dedup key - loading independently`);
2923
4240
  }
2924
- // Execute on_load on detached proxy without deduplication
2925
4241
  const { data: result_data } = await this._execute_on_load_detached();
2926
- // Apply result via sequential queue
2927
- await this._apply_load_result(result_data, null);
4242
+ await this._apply_load_result(result_data, data_before_load);
2928
4243
  return;
2929
4244
  }
2930
- // Store "before" snapshot for comparison after on_load()
2931
- const data_before_load = JSON.stringify(this.data);
2932
4245
  // Check if this component should execute on_load() or wait for existing request
2933
4246
  const should_execute = Load_Coordinator.should_execute_on_load(this);
2934
4247
  if (!should_execute) {
@@ -2965,6 +4278,10 @@ class Jqhtml_Component {
2965
4278
  this._update_debug_attrs();
2966
4279
  this._log_lifecycle('load', 'complete (follower)');
2967
4280
  this.trigger('load');
4281
+ if (!this._load_only && !this._load_render_only) {
4282
+ await this._call_lifecycle('on_loaded');
4283
+ this.trigger('loaded');
4284
+ }
2968
4285
  return;
2969
4286
  }
2970
4287
  // This component is a leader - execute on_load() on detached proxy
@@ -2983,143 +4300,11 @@ class Jqhtml_Component {
2983
4300
  }
2984
4301
  /**
2985
4302
  * Execute on_load() on a fully detached proxy.
2986
- *
2987
- * The proxy has:
2988
- * - A CLONE of this.data (from __initial_data_snapshot)
2989
- * - Read-only access to this.args
2990
- * - No access to anything else (this.$, this.sid, etc.)
2991
- *
2992
- * This ensures on_load runs completely isolated from the component instance.
2993
- *
2994
- * @param use_load_coordinator - If true, register with Load_Coordinator for deduplication
2995
- * @returns The resulting data from the proxy after on_load completes
4303
+ * @see data-proxy.ts for full implementation
2996
4304
  * @private
2997
4305
  */
2998
4306
  async _execute_on_load_detached(use_load_coordinator = false) {
2999
- // Clone this.data from the snapshot captured after on_create()
3000
- const data_clone = this.__initial_data_snapshot
3001
- ? JSON.parse(JSON.stringify(this.__initial_data_snapshot))
3002
- : {};
3003
- // Create a read-only proxy for args that blocks all modifications
3004
- // Can't use JSON clone because args may contain functions (_slots, callbacks)
3005
- const create_readonly_proxy = (obj, path = 'this.args') => {
3006
- if (obj === null || typeof obj !== 'object')
3007
- return obj;
3008
- return new Proxy(obj, {
3009
- get(target, prop) {
3010
- const value = target[prop];
3011
- // Recursively wrap nested objects (but not functions)
3012
- if (value !== null && typeof value === 'object' && typeof value !== 'function') {
3013
- return create_readonly_proxy(value, `${path}.${String(prop)}`);
3014
- }
3015
- return value;
3016
- },
3017
- set(target, prop, value) {
3018
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify ${path}.${String(prop)} during on_load().\n\n` +
3019
- `RESTRICTION: this.args is READ-ONLY during on_load().\n\n` +
3020
- `WHY: this.args configures what data to fetch. Modifying it during on_load() creates circular dependencies.\n\n` +
3021
- `FIX: Modify this.args BEFORE on_load() runs (in on_create() or before calling reload()):\n` +
3022
- ` ❌ Inside on_load(): ${path}.${String(prop)} = ${JSON.stringify(value)};\n` +
3023
- ` ✅ In on_create(): this.args.${String(prop)} = defaultValue;`);
3024
- throw new Error(`[JQHTML] Cannot modify ${path}.${String(prop)} during on_load(). ` +
3025
- `this.args is read-only in on_load().`);
3026
- },
3027
- deleteProperty(target, prop) {
3028
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to delete ${path}.${String(prop)} during on_load().\n\n` +
3029
- `RESTRICTION: this.args is READ-ONLY during on_load().`);
3030
- throw new Error(`[JQHTML] Cannot delete ${path}.${String(prop)} during on_load(). ` +
3031
- `this.args is read-only in on_load().`);
3032
- }
3033
- });
3034
- };
3035
- // Create a detached context object that on_load will operate on
3036
- const detached_context = {
3037
- args: create_readonly_proxy(this.args), // Read-only proxy wrapping real args
3038
- data: data_clone // Cloned data - modifications stay isolated
3039
- };
3040
- // Create restricted proxy that operates on the detached context
3041
- const component_name = this.component_name();
3042
- const restricted_this = new Proxy(detached_context, {
3043
- get(target, prop) {
3044
- // Only allow access to args and data
3045
- if (prop === 'args') {
3046
- return target.args;
3047
- }
3048
- if (prop === 'data') {
3049
- return target.data;
3050
- }
3051
- // Block everything else
3052
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to access this.${String(prop)} during on_load().\n\n` +
3053
- `RESTRICTION: on_load() may ONLY access:\n` +
3054
- ` - this.args (read-only)\n` +
3055
- ` - this.data (read/write)\n\n` +
3056
- `WHY: on_load() is for data fetching only. All other component functionality should happen in other lifecycle methods.\n\n` +
3057
- `FIX:\n` +
3058
- ` - DOM manipulation → use on_render() or on_ready()\n` +
3059
- ` - Component methods → call them before/after on_load(), not inside it\n` +
3060
- ` - Other properties → restructure code to only use this.args and this.data in on_load()`);
3061
- throw new Error(`[JQHTML] Cannot access this.${String(prop)} during on_load(). ` +
3062
- `on_load() may only access this.args and this.data.`);
3063
- },
3064
- set(target, prop, value) {
3065
- // Only allow setting data
3066
- if (prop === 'data') {
3067
- target.data = value;
3068
- return true;
3069
- }
3070
- // Block setting args
3071
- if (prop === 'args') {
3072
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.args during on_load().\n\n` +
3073
- `RESTRICTION: on_load() may ONLY modify:\n` +
3074
- ` - this.data (read/write)\n\n` +
3075
- `WHY: this.args is component state that on_load() depends on. Modifying it inside on_load() creates circular dependencies.\n\n` +
3076
- `FIX: Modify this.args BEFORE calling on_load() (in on_create() or other lifecycle methods), not inside on_load():\n` +
3077
- ` ❌ Inside on_load(): this.args.filter = 'new_value';\n` +
3078
- ` ✅ In on_create(): this.args.filter = this.args.initial_filter || 'default';`);
3079
- throw new Error(`[JQHTML] Cannot modify this.args during on_load(). ` +
3080
- `Modify this.args in other lifecycle methods, not inside on_load().`);
3081
- }
3082
- // Block setting any other properties
3083
- console.error(`[JQHTML] ERROR: Component "${component_name}" attempted to modify this.${String(prop)} during on_load().\n\n` +
3084
- `RESTRICTION: on_load() may ONLY modify:\n` +
3085
- ` - this.data (read/write)\n\n` +
3086
- `WHY: on_load() is for data fetching only. Setting properties on the component instance should happen in other lifecycle methods.\n\n` +
3087
- `FIX: Store your data in this.data instead:\n` +
3088
- ` ❌ this.${String(prop)} = value;\n` +
3089
- ` ✅ this.data.${String(prop)} = value;`);
3090
- throw new Error(`[JQHTML] Cannot modify this.${String(prop)} during on_load(). ` +
3091
- `Only this.data can be modified in on_load().`);
3092
- }
3093
- });
3094
- // Create promise for this on_load() call
3095
- const on_load_promise = (async () => {
3096
- try {
3097
- await this._call_lifecycle('on_load', restricted_this);
3098
- }
3099
- catch (error) {
3100
- if (use_load_coordinator) {
3101
- // Handle error and notify coordinator
3102
- Load_Coordinator.handle_leader_error(this, error);
3103
- }
3104
- throw error;
3105
- }
3106
- })();
3107
- // If using Load_Coordinator, register as leader
3108
- // Note: We store the completion function but DON'T call it here
3109
- // It will be called by _load() after _apply_load_result() updates this.data
3110
- let complete_coordination = null;
3111
- if (use_load_coordinator) {
3112
- complete_coordination = Load_Coordinator.register_leader(this, on_load_promise);
3113
- }
3114
- await on_load_promise;
3115
- // Note: We don't validate args changes here because external code (like parent
3116
- // components calling reload()) is allowed to modify component.args during on_load().
3117
- // The read-only proxy only prevents code INSIDE on_load() from modifying args.
3118
- // Return the data from the detached context AND the completion function
3119
- return {
3120
- data: detached_context.data,
3121
- complete_coordination
3122
- };
4307
+ return execute_on_load_detached(this, use_load_coordinator);
3123
4308
  }
3124
4309
  /**
3125
4310
  * Apply the result of on_load() to this.data via the sequential queue.
@@ -3157,34 +4342,30 @@ class Jqhtml_Component {
3157
4342
  }
3158
4343
  // Freeze this.data
3159
4344
  this.__data_frozen = true;
4345
+ // SSR data capture: record this component's data for preloading
4346
+ if (is_capture_enabled() && this._has_on_load()) {
4347
+ capture_component_data(this.component_name(), this.args, this.data, this._cache_key);
4348
+ }
3160
4349
  // Calculate if data changed
3161
4350
  const data_after_load = JSON.stringify(this.data);
3162
4351
  const data_changed = data_before_load !== null && data_after_load !== data_before_load;
3163
4352
  // Track if component is "dynamic" (this.data changed during on_load)
3164
4353
  // Used by HTML cache mode for synchronization - static parents don't block children
3165
4354
  this._is_dynamic = data_changed && data_after_load !== '{}';
3166
- // CACHE WRITE - If data changed during on_load(), write to cache based on mode
3167
- if (this._is_dynamic && this._cache_key) {
3168
- if (cache_mode === 'html') {
3169
- // HTML cache mode - flag to cache HTML after children ready in _ready()
3170
- this._should_cache_html_after_ready = true;
3171
- if (window.jqhtml?.debug?.verbose) {
3172
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) will cache HTML after ready`, { cache_key: this._cache_key });
3173
- }
3174
- }
3175
- else {
3176
- // Data cache mode (default) - write this.data to cache
3177
- Jqhtml_Local_Storage.set(this._cache_key, this.data);
3178
- if (window.jqhtml?.debug?.verbose) {
3179
- console.log(`[Cache data] Component ${this._cid} (${this.component_name()}) cached data after on_load()`, { cache_key: this._cache_key, data: this.data });
3180
- }
3181
- }
3182
- }
4355
+ // CACHE WRITE - @see component-cache.ts
4356
+ write_cache_on_loaded(this, this._is_dynamic);
3183
4357
  this._ready_state = 2;
3184
4358
  this._update_debug_attrs();
3185
4359
  this._log_lifecycle('load', 'complete');
3186
4360
  // Emit lifecycle event
3187
4361
  this.trigger('load');
4362
+ // Call on_loaded() - runs on the REAL component (not detached proxy)
4363
+ // this.data is frozen (read-only), but this.$, this.state, this.args are accessible
4364
+ // Suppressed by _load_only and _load_render_only flags (preloading mode)
4365
+ if (!this._load_only && !this._load_render_only) {
4366
+ await this._call_lifecycle('on_loaded');
4367
+ this.trigger('loaded');
4368
+ }
3188
4369
  }
3189
4370
  finally {
3190
4371
  // Signal next in queue
@@ -3200,36 +4381,16 @@ class Jqhtml_Component {
3200
4381
  if (this._stopped || this._ready_state >= 4)
3201
4382
  return;
3202
4383
  this._log_lifecycle('ready', 'start');
3203
- // HTML CACHE MODE - New synchronization architecture:
3204
- // 1. Wait for all children to complete on_render (post-on_load)
3205
- // 2. Take HTML snapshot BEFORE waiting for children ready
3206
- // 3. This ensures we capture the DOM after on_render but before on_ready manipulations
4384
+ // HTML CACHE MODE - Wait for children on_render, then snapshot
4385
+ // @see component-cache.ts for write_html_cache_snapshot implementation
3207
4386
  if (this._should_cache_html_after_ready && this._cache_key) {
3208
- // Wait for all children to complete their on_render
3209
4387
  await this._wait_for_children_on_render();
3210
- // Only cache if this component is dynamic (data changed during on_load)
3211
- // Static parents don't cache - they just let children proceed
3212
- if (this._is_dynamic) {
3213
- this._should_cache_html_after_ready = false;
3214
- // Cache the rendered HTML
3215
- const html = this.$.html();
3216
- const html_cache_key = `${this._cache_key}::html`;
3217
- Jqhtml_Local_Storage.set(html_cache_key, html);
3218
- if (window.jqhtml?.debug?.verbose) {
3219
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) cached HTML after children on_render complete`, { cache_key: html_cache_key, html_length: html.length });
3220
- }
3221
- }
3222
- else {
3223
- // Static component - just clear the flag, don't cache
3224
- this._should_cache_html_after_ready = false;
3225
- if (window.jqhtml?.debug?.verbose) {
3226
- console.log(`[Cache html] Component ${this._cid} (${this.component_name()}) is static (no data change) - skipping HTML cache`);
3227
- }
3228
- }
4388
+ write_html_cache_snapshot(this);
3229
4389
  }
3230
4390
  // Wait for all children to reach ready state (bottom-up execution)
3231
4391
  await this._wait_for_children_ready();
3232
4392
  await this._call_lifecycle('on_ready');
4393
+ this._fire_viewport_resize();
3233
4394
  this._ready_state = 4;
3234
4395
  this._update_debug_attrs();
3235
4396
  this._log_lifecycle('ready', 'complete');
@@ -3386,6 +4547,17 @@ class Jqhtml_Component {
3386
4547
  * If false, only re-render if data actually changed.
3387
4548
  */
3388
4549
  async reload(always_render) {
4550
+ // Load-gate short-circuit: if a gate is currently holding the first on_load,
4551
+ // reload()/refresh() resumes the paused boot lifecycle instead of running its
4552
+ // normal debounced re-fetch. The boot lifecycle then proceeds to run on_load
4553
+ // (the fresh fetch) exactly as reload() would want. Any later gate settlement
4554
+ // becomes a no-op. Return a promise that resolves when the component is ready.
4555
+ if (this.__gate_resume) {
4556
+ const resume = this.__gate_resume;
4557
+ this.__gate_resume = null;
4558
+ resume();
4559
+ return this.ready();
4560
+ }
3389
4561
  // Default to true if undefined
3390
4562
  const force_refresh = always_render !== undefined ? always_render : true;
3391
4563
  // State machine: reload(true) takes precedence over reload(false)
@@ -3398,11 +4570,9 @@ class Jqhtml_Component {
3398
4570
  this.next_reload_force_refresh = false;
3399
4571
  }
3400
4572
  }
3401
- // Lazy-create debounced _reload function on first use
3402
- if (!this._reload_debounced) {
3403
- this._reload_debounced = this._create_debounced_function(this._reload.bind(this), 0);
3404
- }
3405
- return this._reload_debounced();
4573
+ // Enqueue through component queue (replaces _create_debounced_function)
4574
+ // Same-type pending operations collapse (multiple reload() calls share one execution)
4575
+ return this._queue.enqueue('reload', () => this._reload());
3406
4576
  }
3407
4577
  /**
3408
4578
  * Refresh component - re-fetch data and re-render only if data changed (debounced)
@@ -3465,6 +4635,7 @@ class Jqhtml_Component {
3465
4635
  this._render();
3466
4636
  await this._wait_for_children_ready();
3467
4637
  await this._call_lifecycle('on_ready');
4638
+ this._fire_viewport_resize();
3468
4639
  this.trigger('ready');
3469
4640
  this._log_lifecycle('reload', 'complete (no on_load)');
3470
4641
  return;
@@ -3484,57 +4655,8 @@ class Jqhtml_Component {
3484
4655
  }
3485
4656
  }
3486
4657
  if (args_changed) {
3487
- // Check if component implements cache_id() for custom cache key
3488
- let cache_key = null;
3489
- if (typeof this.cache_id === 'function') {
3490
- try {
3491
- const custom_cache_id = this.cache_id();
3492
- cache_key = `${this.component_name()}::${String(custom_cache_id)}`;
3493
- }
3494
- catch (error) {
3495
- // cache_id() threw error - disable caching
3496
- cache_key = null;
3497
- }
3498
- }
3499
- else {
3500
- // Use standard args-based cache key generation
3501
- const result = Load_Coordinator.generate_invocation_key(this.component_name(), this.args);
3502
- cache_key = result.key;
3503
- }
3504
- // Check for cached data/html when args changed
3505
- if (cache_key !== null) {
3506
- const cache_mode = Jqhtml_Local_Storage.get_cache_mode();
3507
- this._cache_key = cache_key;
3508
- if (cache_mode === 'html') {
3509
- // HTML cache mode - check for cached HTML
3510
- const html_cache_key = `${cache_key}::html`;
3511
- const cached_html = Jqhtml_Local_Storage.get(html_cache_key);
3512
- if (cached_html !== null && typeof cached_html === 'string') {
3513
- if (window.jqhtml?.debug?.verbose) {
3514
- console.log(`[Cache html] reload() - Component ${this._cid} (${this.component_name()}) found cached HTML (args changed)`, { cache_key: html_cache_key, html_length: cached_html.length });
3515
- }
3516
- // Store cached HTML for injection in _render()
3517
- this._cached_html = cached_html;
3518
- this.render();
3519
- rendered_from_cache = true;
3520
- }
3521
- }
3522
- else {
3523
- // Data cache mode (default) - check for cached data
3524
- const cached_data = Jqhtml_Local_Storage.get(cache_key);
3525
- if (cached_data !== null && typeof cached_data === 'object' && JSON.stringify(cached_data) !== '{}') {
3526
- if (window.jqhtml?.debug?.verbose) {
3527
- console.log(`[Cache data] reload() - Component ${this._cid} (${this.component_name()}) hydrated from cache (args changed)`, { cache_key, data: cached_data });
3528
- }
3529
- // Hydrate this.data with cached data
3530
- this.__data_frozen = false;
3531
- this.data = cached_data;
3532
- this.__data_frozen = true;
3533
- this.render();
3534
- rendered_from_cache = true;
3535
- }
3536
- }
3537
- }
4658
+ // @see component-cache.ts for full implementation
4659
+ rendered_from_cache = check_cache_on_reload(this);
3538
4660
  }
3539
4661
  // Capture data state before on_load for comparison
3540
4662
  data_before_load = JSON.stringify(this.data);
@@ -3588,6 +4710,7 @@ class Jqhtml_Component {
3588
4710
  if (rendered_from_cache || should_render) {
3589
4711
  await this._wait_for_children_ready();
3590
4712
  await this._call_lifecycle('on_ready');
4713
+ this._fire_viewport_resize();
3591
4714
  // Trigger ready event so parent callbacks fire on subsequent reloads
3592
4715
  this.trigger('ready');
3593
4716
  }
@@ -3608,11 +4731,18 @@ class Jqhtml_Component {
3608
4731
  if (this._stopped)
3609
4732
  return;
3610
4733
  this._stopped = true;
4734
+ // If a load gate is holding the first on_load, release the wait so the boot
4735
+ // lifecycle unwinds cleanly (it will see _stopped and abandon the load).
4736
+ if (this.__gate_resume) {
4737
+ const resume = this.__gate_resume;
4738
+ this.__gate_resume = null;
4739
+ resume();
4740
+ }
3611
4741
  // Early bailout: skip expensive cleanup if no handlers registered
3612
4742
  // Only matters for aborting boot() lifecycle - minimal cleanup sufficient
3613
4743
  const has_custom_stop = this.on_stop !== Jqhtml_Component.prototype.on_stop;
3614
- const has_destroy_callbacks = this._on_registered('destroy');
3615
- if (!has_custom_stop && !has_destroy_callbacks) {
4744
+ const has_stop_callbacks = this._on_registered('stop');
4745
+ if (!has_custom_stop && !has_stop_callbacks) {
3616
4746
  // Fast path: no cleanup logic defined, just mark as stopped
3617
4747
  this._lifecycle_manager.unregister_component(this);
3618
4748
  this._ready_state = 99;
@@ -3660,8 +4790,19 @@ class Jqhtml_Component {
3660
4790
  on_render() { }
3661
4791
  on_create() { }
3662
4792
  on_load() { } // Override to fetch data asynchronously
4793
+ on_loaded() { } // Override to process loaded data (e.g., clone this.data to this.state)
3663
4794
  async on_ready() { }
3664
4795
  on_stop() { }
4796
+ /**
4797
+ * Called with the viewport width in CSS pixels:
4798
+ * - after every on_render()
4799
+ * - after every on_ready()
4800
+ * - on window resize, debounced 30ms, for every component in the document
4801
+ *
4802
+ * MUST be synchronous. Prefer CSS media/container queries for pure styling -
4803
+ * override this only when layout requires imperative measurement.
4804
+ */
4805
+ on_viewport_resize(viewport_width) { }
3665
4806
  /**
3666
4807
  * Should component re-render after load?
3667
4808
  * By default, only re-renders if data has changed
@@ -3705,85 +4846,39 @@ class Jqhtml_Component {
3705
4846
  return this.constructor.name;
3706
4847
  }
3707
4848
  /**
3708
- * Register event callback
3709
- * Supports lifecycle events ('render', 'create', 'load', 'ready', 'stop') and custom events
3710
- * Lifecycle event callbacks fire after the lifecycle method completes
3711
- * If a lifecycle event has already occurred, the callback fires immediately AND registers for future occurrences
3712
- * Custom events only fire when explicitly triggered via .trigger()
3713
- *
3714
- * Callback signature: (component, data?) => void
3715
- * - component: The component instance that triggered the event
3716
- * - data: Optional data passed as second parameter to trigger()
4849
+ * Register event callback - delegates to component-events.ts
4850
+ * @see component-events.ts for full documentation
3717
4851
  */
3718
4852
  on(event_name, callback) {
3719
- // Initialize callback array for this event if needed
3720
- if (!this._lifecycle_callbacks.has(event_name)) {
3721
- this._lifecycle_callbacks.set(event_name, []);
3722
- }
3723
- // Add callback to queue
3724
- this._lifecycle_callbacks.get(event_name).push(callback);
3725
- // If this lifecycle event has already occurred, fire the callback immediately
3726
- // with the stored data from when trigger() was called
3727
- if (this._lifecycle_states.has(event_name)) {
3728
- try {
3729
- const stored_data = this._lifecycle_states.get(event_name);
3730
- callback(this, stored_data);
3731
- }
3732
- catch (error) {
3733
- console.error(`[JQHTML] Error in ${event_name} callback:`, error);
3734
- }
3735
- }
3736
- return this;
4853
+ return event_on(this, event_name, callback);
3737
4854
  }
3738
4855
  /**
3739
- * Trigger a lifecycle event - fires all registered callbacks
3740
- * Marks event as occurred so future .on() calls fire immediately
3741
- *
3742
- * @param event_name - Name of the event to trigger
3743
- * @param data - Optional data to pass to callbacks as second parameter
4856
+ * Register a callback that fires exactly once - delegates to component-events.ts
4857
+ * If the event already occurred, fires immediately and does not register.
4858
+ * @see component-events.ts for full documentation
4859
+ */
4860
+ once(event_name, callback) {
4861
+ return event_once(this, event_name, callback);
4862
+ }
4863
+ /**
4864
+ * Trigger a lifecycle event - delegates to component-events.ts
4865
+ * @see component-events.ts for full documentation
3744
4866
  */
3745
4867
  trigger(event_name, data) {
3746
- // Mark this event as occurred and store the data for late subscribers
3747
- this._lifecycle_states.set(event_name, data);
3748
- // Fire all registered callbacks for this event
3749
- const callbacks = this._lifecycle_callbacks.get(event_name);
3750
- if (callbacks) {
3751
- for (const callback of callbacks) {
3752
- try {
3753
- callback.bind(this)(this, data);
3754
- }
3755
- catch (error) {
3756
- console.error(`[JQHTML] Error in ${event_name} callback:`, error);
3757
- }
3758
- }
3759
- }
4868
+ event_trigger(this, event_name, data);
3760
4869
  }
3761
4870
  /**
3762
4871
  * Check if any callbacks are registered for a given event
3763
- * Used to determine if cleanup logic needs to run
3764
4872
  */
3765
4873
  _on_registered(event_name) {
3766
- const callbacks = this._lifecycle_callbacks.get(event_name);
3767
- return !!(callbacks && callbacks.length > 0);
4874
+ return event_on_registered(this, event_name);
3768
4875
  }
3769
4876
  /**
3770
- * Invalidate a lifecycle event - removes the "already occurred" marker
3771
- *
3772
- * This is the opposite of trigger(). After invalidate() is called:
3773
- * - New .on() handlers will NOT fire immediately
3774
- * - The ready() promise will NOT resolve immediately
3775
- * - Handlers wait for the next trigger() call
3776
- *
3777
- * Existing registered callbacks are NOT removed - they'll fire on next trigger().
3778
- *
3779
- * Use case: Call invalidate('ready') at the start of reload() or render()
3780
- * so that any new .on('ready') handlers wait for the reload/render to complete
3781
- * rather than firing immediately based on the previous lifecycle's state.
3782
- *
3783
- * @param event_name - Name of the event to invalidate
4877
+ * Invalidate a lifecycle event - delegates to component-events.ts
4878
+ * @see component-events.ts for full documentation
3784
4879
  */
3785
4880
  invalidate(event_name) {
3786
- this._lifecycle_states.delete(event_name);
4881
+ event_invalidate(this, event_name);
3787
4882
  }
3788
4883
  /**
3789
4884
  * Find element by scoped ID
@@ -4082,8 +5177,13 @@ class Jqhtml_Component {
4082
5177
  }
4083
5178
  }
4084
5179
  _set_attributes() {
4085
- // Always set data-cid
4086
- this.$.attr('data-cid', this._cid);
5180
+ // data-cid on the rendered element is debug-only: it mirrors this._cid so component
5181
+ // boundaries are legible in DevTools. The runtime never reads it - scoping uses the
5182
+ // _cid property, and the transient data-cid placeholder the instruction processor
5183
+ // matches on is written and removed before this ever runs.
5184
+ if (debug_attributes_enabled()) {
5185
+ this.$.attr('data-cid', this._cid);
5186
+ }
4087
5187
  // Only set lifecycle state attribute if verbose mode enabled
4088
5188
  if (window.jqhtml?.debug?.verbose) {
4089
5189
  this.$.attr('data-_lifecycle-state', this._ready_state.toString());
@@ -4155,84 +5255,6 @@ class Jqhtml_Component {
4155
5255
  window.JQHTML_DEBUG.log(this.component_name(), 'debug', `${action}: ${args.map(a => JSON.stringify(a)).join(', ')}`);
4156
5256
  }
4157
5257
  }
4158
- /**
4159
- * Creates a debounced function with exclusivity and promise fan-in
4160
- *
4161
- * When invoked, immediately runs the callback exclusively.
4162
- * For subsequent invocations, applies a delay before running the callback exclusively again.
4163
- * The delay starts after the current asynchronous operation resolves.
4164
- *
4165
- * If delay is 0, the function only prevents enqueueing multiple executions,
4166
- * but will still run them immediately in an exclusive sequential manner.
4167
- *
4168
- * The most recent invocation's parameters are used when the function executes.
4169
- * Returns a promise that resolves when the next exclusive execution completes.
4170
- *
4171
- * @private
4172
- */
4173
- _create_debounced_function(callback, delay) {
4174
- let running = false;
4175
- let queued = false;
4176
- let last_end_time = 0; // timestamp of last completed run
4177
- let timer = null;
4178
- let next_args = [];
4179
- let resolve_queue = [];
4180
- let reject_queue = [];
4181
- const run_function = async () => {
4182
- const these_resolves = resolve_queue;
4183
- const these_rejects = reject_queue;
4184
- const args = next_args;
4185
- resolve_queue = [];
4186
- reject_queue = [];
4187
- next_args = [];
4188
- queued = false;
4189
- running = true;
4190
- try {
4191
- const result = await callback(...args);
4192
- for (const resolve of these_resolves)
4193
- resolve(result);
4194
- }
4195
- catch (err) {
4196
- for (const reject of these_rejects)
4197
- reject(err);
4198
- }
4199
- finally {
4200
- running = false;
4201
- last_end_time = Date.now();
4202
- if (queued) {
4203
- clearTimeout(timer);
4204
- timer = setTimeout(run_function, Math.max(delay, 0));
4205
- }
4206
- else {
4207
- timer = null;
4208
- }
4209
- }
4210
- };
4211
- return function (...args) {
4212
- next_args = args;
4213
- return new Promise((resolve, reject) => {
4214
- resolve_queue.push(resolve);
4215
- reject_queue.push(reject);
4216
- // Nothing running and nothing scheduled
4217
- if (!running && !timer) {
4218
- const first_call = last_end_time === 0;
4219
- const since = first_call ? Infinity : Date.now() - last_end_time;
4220
- if (since >= delay) {
4221
- run_function();
4222
- }
4223
- else {
4224
- const wait = Math.max(delay - since, 0);
4225
- clearTimeout(timer);
4226
- timer = setTimeout(run_function, wait);
4227
- }
4228
- return;
4229
- }
4230
- // If already running or timer exists, just mark queued
4231
- // The finally{} of run_function handles scheduling after full delay
4232
- queued = true;
4233
- });
4234
- };
4235
- }
4236
5258
  }
4237
5259
  // Static properties
4238
5260
  Jqhtml_Component.__jqhtml_component = true; // Marker for unified register() detection
@@ -4888,6 +5910,61 @@ function init_jquery_plugin(jQuery) {
4888
5910
  const originalEmpty = jQuery.fn.empty;
4889
5911
  const originalHtml = jQuery.fn.html;
4890
5912
  const originalText = jQuery.fn.text;
5913
+ // ---------------------------------------------------------------------------
5914
+ // Guard against hand-creating elements with data-sid via jQuery.
5915
+ //
5916
+ // $sid / data-sid is provisioned ONLY by the jqhtml template renderer, which
5917
+ // ALWAYS emits data-sid paired with a scoped id ("<sid>:<component_cid>").
5918
+ // That scoped id is what binds the element to its component; data-sid on its
5919
+ // own does nothing. So an element whose data-sid is NOT paired with such an id
5920
+ // was hand-written (e.g. .html('<div data-sid="x">')) and the framework never
5921
+ // provisioned it - this.$sid('x') can never find it. We detect exactly that.
5922
+ //
5923
+ // The framework's own rendering injects data-sid via native innerHTML, never
5924
+ // through these jQuery methods, and the one internal jQuery .html() copy
5925
+ // (the .component() tag-mismatch path) carries the provisioned id - so neither
5926
+ // trips this guard.
5927
+ // ---------------------------------------------------------------------------
5928
+ // Return the offending data-sid value if `html` contains a hand-written
5929
+ // data-sid element (data-sid without the scoped "<sid>:<cid>" id), else null.
5930
+ const find_manual_sid = (html) => {
5931
+ if (typeof html !== 'string' || html.indexOf('data-sid') === -1)
5932
+ return null;
5933
+ if (typeof document === 'undefined')
5934
+ return null; // no DOM to parse (SSR)
5935
+ const tpl = document.createElement('template');
5936
+ tpl.innerHTML = html; // native parse - does not route back through jQuery
5937
+ const candidates = tpl.content.querySelectorAll('[data-sid]');
5938
+ for (let i = 0; i < candidates.length; i++) {
5939
+ const el = candidates[i];
5940
+ const sid = el.getAttribute('data-sid') || '';
5941
+ const id = el.getAttribute('id') || '';
5942
+ // Provisioned elements have id="<sid>:<cid>". Anything else is hand-written.
5943
+ if (id.indexOf(sid + ':') !== 0)
5944
+ return sid;
5945
+ }
5946
+ return null;
5947
+ };
5948
+ const assert_no_manual_sid = (value, where) => {
5949
+ const sid = find_manual_sid(value);
5950
+ if (sid === null)
5951
+ return;
5952
+ throw new Error(`[JQHTML] Manually creating an element with data-sid="${sid}" via jQuery (${where}) is not allowed.\n\n` +
5953
+ `data-sid is NOT a normal attribute you can hand-write. It is provisioned by the jqhtml template\n` +
5954
+ `renderer, which scopes the element to its component by pairing data-sid with a unique id\n` +
5955
+ `("${sid}:<component_cid>"). An element you create yourself has no such scoped id, so\n` +
5956
+ `this.$sid('${sid}') / this.sid('${sid}') can never find it - scoping to a component is the entire\n` +
5957
+ `point of data-sid.\n\n` +
5958
+ `CORRECT USAGE:\n` +
5959
+ ` • Put the element in your component template with $sid:\n` +
5960
+ ` <div $sid="${sid}"></div>\n` +
5961
+ ` then access it from the component: this.$sid('${sid}')\n` +
5962
+ ` • Need it created dynamically? Use a child component or a $redrawable element in the template\n` +
5963
+ ` and render() it, instead of injecting raw HTML.\n\n` +
5964
+ `If you only need to select or mark a plain element, use a normal attribute or class instead:\n` +
5965
+ ` • <div data-role="${sid}"> → .find('[data-role="${sid}"]')\n` +
5966
+ ` • <div class="MyComponent__${sid}"> → .find('.MyComponent__${sid}')`);
5967
+ };
4891
5968
  /**
4892
5969
  * Override jQuery.fn.empty() to stop child components before clearing DOM
4893
5970
  * This ensures component cleanup hooks fire when DOM is cleared
@@ -4914,6 +5991,8 @@ function init_jquery_plugin(jQuery) {
4914
5991
  if (arguments.length === 0) {
4915
5992
  return originalHtml.call(this);
4916
5993
  }
5994
+ // Reject hand-written data-sid before mutating the DOM
5995
+ assert_no_manual_sid(value, '.html()');
4917
5996
  // Setter - empty first (which stops components), then set content
4918
5997
  return this.each(function () {
4919
5998
  jQuery(this).empty();
@@ -5016,6 +6095,36 @@ function init_jquery_plugin(jQuery) {
5016
6095
  // Pass through to original .find()
5017
6096
  return originalFind.call(this, selector);
5018
6097
  };
6098
+ // Guard the content-insertion methods that build elements from HTML strings,
6099
+ // plus $() construction. Wrapped once so repeated init() calls don't re-wrap.
6100
+ if (!jQuery.fn.__jqhtml_sid_guarded) {
6101
+ jQuery.fn.__jqhtml_sid_guarded = true;
6102
+ // .append('<div data-sid>'), .prepend, .before, .after, .replaceWith
6103
+ for (const name of ['append', 'prepend', 'before', 'after', 'replaceWith']) {
6104
+ const original = jQuery.fn[name];
6105
+ if (typeof original !== 'function')
6106
+ continue;
6107
+ jQuery.fn[name] = function (...args) {
6108
+ for (const arg of args)
6109
+ assert_no_manual_sid(arg, '.' + name + '()');
6110
+ return original.apply(this, args);
6111
+ };
6112
+ }
6113
+ // $('<div data-sid="x">') - catch the element at construction time. A
6114
+ // selector like $('[data-sid="x"]') parses to no data-sid element, so it is
6115
+ // not flagged here (selector misuse is handled by .find()/.on()).
6116
+ const originalInit = jQuery.fn.init;
6117
+ const PatchedInit = function (selector, context, root) {
6118
+ if (typeof selector === 'string')
6119
+ assert_no_manual_sid(selector, '$()');
6120
+ return new originalInit(selector, context, root);
6121
+ };
6122
+ PatchedInit.prototype = jQuery.fn;
6123
+ jQuery.fn.init = PatchedInit;
6124
+ }
6125
+ // Install the single debounced window resize listener that drives
6126
+ // on_viewport_resize() on every component. Idempotent.
6127
+ init_viewport_resize(jQuery);
5019
6128
  }
5020
6129
  // Try to auto-initialize if global jQuery exists
5021
6130
  if (typeof window !== 'undefined' && window.jQuery) {
@@ -5029,7 +6138,9 @@ if (typeof window !== 'undefined' && window.jQuery) {
5029
6138
  */
5030
6139
  // Core exports
5031
6140
  // Main initialization function
5032
- function init(jQuery) {
6141
+ function init(jQuery, config) {
6142
+ // Integration config first - it governs behaviour during the very first render
6143
+ configure(config);
5033
6144
  // If jQuery is provided, initialize the plugin
5034
6145
  if (jQuery) {
5035
6146
  init_jquery_plugin(jQuery);
@@ -5043,7 +6154,7 @@ function init(jQuery) {
5043
6154
  }
5044
6155
  }
5045
6156
  // Version - will be replaced during build with actual version from package.json
5046
- const version = '2.3.35';
6157
+ const version = '2.3.54';
5047
6158
  // Default export with all functionality
5048
6159
  const jqhtml = {
5049
6160
  // Core
@@ -5071,6 +6182,9 @@ const jqhtml = {
5071
6182
  __version: version,
5072
6183
  // state facts
5073
6184
  tombstone: 'pepperoni and cheese',
6185
+ // Integration configuration - see config.ts
6186
+ configure,
6187
+ get_config,
5074
6188
  // Debug settings
5075
6189
  debug: {
5076
6190
  enabled: false,
@@ -5140,7 +6254,13 @@ const jqhtml = {
5140
6254
  // Required for ES6 class instances to be stored and restored from localStorage
5141
6255
  register_cache_class,
5142
6256
  // Boot - hydrate server-rendered component placeholders
5143
- boot
6257
+ boot,
6258
+ // SSR Preload - capture data during SSR, replay on client to skip on_load()
6259
+ start_data_capture,
6260
+ get_captured_data,
6261
+ stop_data_capture,
6262
+ set_preload_data,
6263
+ clear_preload_data
5144
6264
  };
5145
6265
  // Auto-register on window for browser environments
5146
6266
  // This is REQUIRED for compiled templates which use window.jqhtml.register_template()
@@ -5177,14 +6297,18 @@ exports.LifecycleManager = LifecycleManager;
5177
6297
  exports.Load_Coordinator = Load_Coordinator;
5178
6298
  exports.applyDebugDelay = applyDebugDelay;
5179
6299
  exports.boot = boot;
6300
+ exports.clear_preload_data = clear_preload_data;
6301
+ exports.configure = configure;
5180
6302
  exports.create_component = create_component;
5181
6303
  exports.default = jqhtml;
5182
6304
  exports.devWarn = devWarn;
5183
6305
  exports.escape_html = escape_html;
5184
6306
  exports.escape_html_nl2br = escape_html_nl2br;
5185
6307
  exports.extract_slots = extract_slots;
6308
+ exports.get_captured_data = get_captured_data;
5186
6309
  exports.get_component_class = get_component_class;
5187
6310
  exports.get_component_names = get_component_names;
6311
+ exports.get_config = get_config;
5188
6312
  exports.get_registered_templates = get_registered_templates;
5189
6313
  exports.get_template = get_template;
5190
6314
  exports.get_template_by_class = get_template_by_class;
@@ -5204,5 +6328,8 @@ exports.register_cache_class = register_cache_class;
5204
6328
  exports.register_component = register_component;
5205
6329
  exports.register_template = register_template;
5206
6330
  exports.render_template = render_template;
6331
+ exports.set_preload_data = set_preload_data;
6332
+ exports.start_data_capture = start_data_capture;
6333
+ exports.stop_data_capture = stop_data_capture;
5207
6334
  exports.version = version;
5208
6335
  //# sourceMappingURL=index.cjs.map