gyosjs 0.3.2 → 0.4.1

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/gyos.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.2
2
+ * GyosJS v0.4.1
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -235,10 +235,35 @@
235
235
  * count.value++; // Triggers effect
236
236
  * ```
237
237
  */
238
- /**
239
- * Current effect being tracked
240
- */
241
238
  let currentEffect = null;
239
+ function track(source) {
240
+ if (!currentEffect)
241
+ return;
242
+ source.subscribers.add(currentEffect);
243
+ currentEffect.__dependencies?.add(source.subscribers);
244
+ currentEffect.__versions?.set(source, source.version);
245
+ }
246
+ function dependenciesChanged(versions) {
247
+ return untrack(() => {
248
+ for (const [source, version] of versions) {
249
+ source.refresh?.();
250
+ if (source.version !== version)
251
+ return true;
252
+ }
253
+ return false;
254
+ });
255
+ }
256
+ // Invalidate derived caches synchronously; only user effects are deferred.
257
+ function notifySubscribers(subscribers) {
258
+ for (const sub of Array.from(subscribers)) {
259
+ if (sub.__invalidate)
260
+ sub();
261
+ else if (isBatching)
262
+ batchedEffects.add(sub);
263
+ else
264
+ queueEffect(sub);
265
+ }
266
+ }
242
267
  // Simple counter for debug-friendly IDs
243
268
  let signalIdCounter = 0;
244
269
  const WARN_SUBSCRIBERS = () => typeof window !== 'undefined' && window.GYOS_DEBUG_WARN_SUBSCRIBERS;
@@ -276,6 +301,9 @@
276
301
  }
277
302
  });
278
303
  isFlushingQueue = false;
304
+ // A plain subscribe callback can enqueue more work without entering effect().
305
+ if (effectQueue.size > 0)
306
+ queueMicrotask(flushEffectQueue);
279
307
  }
280
308
  /**
281
309
  * Queue an effect for execution in next microtask
@@ -334,17 +362,14 @@
334
362
  const debugId = ++signalIdCounter;
335
363
  let value = initialValue;
336
364
  const subscribers = new Set();
365
+ const source = { subscribers, version: 0 };
337
366
  let warnedSubscribers = false;
338
367
  const read = () => {
339
368
  // Track dependency
340
369
  if (currentEffect) {
341
- // IMPORTANT: Only add if not already subscribed (prevent duplicates)
342
- if (!subscribers.has(currentEffect)) {
343
- subscribers.add(currentEffect);
344
- // Store the subscribers Set in the effect's dependencies for cleanup
345
- if (currentEffect.__dependencies) {
346
- currentEffect.__dependencies.add(subscribers);
347
- }
370
+ const wasSubscribed = subscribers.has(currentEffect);
371
+ track(source);
372
+ if (!wasSubscribed) {
348
373
  if (DEBUG_VERBOSE()) {
349
374
  console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Added subscriber, total:', subscribers.size);
350
375
  }
@@ -363,18 +388,13 @@
363
388
  // For objects/arrays, check if it's actually the same reference
364
389
  // Deep equality is expensive, let user handle it
365
390
  value = newValue;
391
+ source.version++;
366
392
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Value changed to:', newValue);
367
393
  notify();
368
394
  };
369
395
  const notify = () => {
370
396
  DEBUG_VERBOSE() && console.log('[Signal]', formatDebugLabel(debugId, debugLabel), 'Notifying', subscribers.size, 'subscribers');
371
- if (isBatching) {
372
- subscribers.forEach(sub => batchedEffects.add(sub));
373
- }
374
- else {
375
- // Always queue effects to prevent cascading updates
376
- subscribers.forEach(sub => queueEffect(sub));
377
- }
397
+ notifySubscribers(subscribers);
378
398
  };
379
399
  // Create callable signal (like Angular/SolidJS)
380
400
  // Call without args = read, call with arg = write
@@ -409,8 +429,16 @@
409
429
  },
410
430
  subscribe: {
411
431
  value: function (fn) {
412
- subscribers.add(fn);
413
- return () => subscribers.delete(fn);
432
+ let active = true;
433
+ const callback = () => { if (active)
434
+ untrack(fn); };
435
+ subscribers.add(callback);
436
+ return () => {
437
+ active = false;
438
+ subscribers.delete(callback);
439
+ effectQueue.delete(callback);
440
+ batchedEffects.delete(callback);
441
+ };
414
442
  },
415
443
  enumerable: true,
416
444
  configurable: true
@@ -470,49 +498,60 @@
470
498
  let value;
471
499
  let isDirty = true;
472
500
  let isFirstRun = true;
501
+ let computing = false;
473
502
  const subscribers = new Set();
474
- let cleanup;
503
+ const dependencies = new Set();
504
+ const versions = new Map();
505
+ const source = { subscribers, version: 0, refresh: () => compute() };
506
+ const invalidate = () => {
507
+ // A later batched write must also move already queued consumers into
508
+ // the batch, even when an earlier ordinary write dirtied this cache.
509
+ if (isDirty && !isBatching)
510
+ return;
511
+ isDirty = true;
512
+ notifySubscribers(subscribers);
513
+ };
514
+ invalidate.__invalidate = true;
515
+ invalidate.__dependencies = dependencies;
516
+ invalidate.__versions = versions;
475
517
  const compute = () => {
476
518
  if (!isDirty && !isFirstRun)
477
519
  return;
478
- // Cleanup previous dependencies
479
- if (cleanup)
480
- cleanup();
481
- // Track dependencies in an effect
482
- cleanup = effect(() => {
483
- try {
484
- const newValue = fn();
485
- // Only update if changed
486
- if (isFirstRun || value !== newValue) {
487
- value = newValue;
488
- isFirstRun = false;
489
- isDirty = false;
490
- // Notify subscribers
491
- if (!isBatching) {
492
- subscribers.forEach(sub => queueEffect(sub));
493
- }
494
- else {
495
- subscribers.forEach(sub => batchedEffects.add(sub));
496
- }
497
- }
520
+ if (computing)
521
+ throw new Error('[Computed] Circular dependency');
522
+ computing = true;
523
+ const previousEffect = currentEffect;
524
+ try {
525
+ // A dirty upstream computed may still resolve to its previous value.
526
+ if (!isFirstRun && !dependenciesChanged(versions)) {
527
+ isDirty = false;
528
+ return;
498
529
  }
499
- catch (error) {
500
- console.error('[Computed] Error in computation:', error);
501
- throw error;
530
+ dependencies.forEach(dependency => dependency.delete(invalidate));
531
+ dependencies.clear();
532
+ versions.clear();
533
+ currentEffect = invalidate;
534
+ const nextValue = fn();
535
+ if (isFirstRun || !Object.is(value, nextValue)) {
536
+ value = nextValue;
537
+ source.version++;
502
538
  }
503
- });
504
- isDirty = false;
539
+ isFirstRun = false;
540
+ isDirty = false;
541
+ }
542
+ catch (error) {
543
+ // Preserve error isolation and the last successful value.
544
+ console.error('[Computed] Error in computation:', error);
545
+ isDirty = false;
546
+ }
547
+ finally {
548
+ currentEffect = previousEffect;
549
+ computing = false;
550
+ }
505
551
  };
506
552
  const read = () => {
507
- if (isDirty || isFirstRun)
508
- compute();
509
- // Track dependency
510
- if (currentEffect && !subscribers.has(currentEffect)) {
511
- subscribers.add(currentEffect);
512
- if (currentEffect.__dependencies) {
513
- currentEffect.__dependencies.add(subscribers);
514
- }
515
- }
553
+ compute();
554
+ track(source);
516
555
  return value;
517
556
  };
518
557
  // Create callable computed (read-only)
@@ -537,8 +576,14 @@
537
576
  },
538
577
  subscribe: {
539
578
  value: function (fn) {
540
- subscribers.add(fn);
541
- return () => subscribers.delete(fn);
579
+ // Establish dependencies even if subscribe() is the first access.
580
+ let first = true;
581
+ return effect(() => {
582
+ read();
583
+ if (!first)
584
+ untrack(fn);
585
+ first = false;
586
+ });
542
587
  },
543
588
  enumerable: true,
544
589
  configurable: true
@@ -589,11 +634,15 @@
589
634
  */
590
635
  function effect(fn) {
591
636
  let cleanup;
592
- let dependencies = new Set();
637
+ const dependencies = new Set();
638
+ const versions = new Map();
593
639
  let active = true;
640
+ let initialized = false;
594
641
  const execute = () => {
595
642
  if (!active)
596
643
  return;
644
+ if (initialized && !dependenciesChanged(versions))
645
+ return;
597
646
  // Prevent recursive execution - if already running, skip
598
647
  if (runningEffects.has(execute)) {
599
648
  DEBUG() && console.warn('[Effect] Skipped recursive execution');
@@ -608,10 +657,13 @@
608
657
  });
609
658
  DEBUG() && console.log('[Effect] Cleaned up dependencies, count:', dependencies.size);
610
659
  dependencies.clear();
660
+ versions.clear();
611
661
  // Clean up previous run
612
662
  if (cleanup) {
663
+ const previousCleanup = cleanup;
664
+ cleanup = undefined;
613
665
  try {
614
- cleanup();
666
+ untrack(previousCleanup);
615
667
  }
616
668
  catch (error) {
617
669
  console.error('[Effect] Error in cleanup:', error);
@@ -622,6 +674,7 @@
622
674
  currentEffect = execute;
623
675
  // Store dependencies for cleanup
624
676
  execute.__dependencies = dependencies;
677
+ execute.__versions = versions;
625
678
  try {
626
679
  const nextCleanup = fn();
627
680
  cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
@@ -631,6 +684,7 @@
631
684
  // Don't throw - allow other effects to continue
632
685
  }
633
686
  finally {
687
+ initialized = true;
634
688
  currentEffect = prevEffect;
635
689
  effectDepth--;
636
690
  runningEffects.delete(execute);
@@ -647,14 +701,17 @@
647
701
  if (!active)
648
702
  return;
649
703
  active = false;
704
+ effectQueue.delete(execute);
705
+ batchedEffects.delete(execute);
650
706
  // Remove from all dependencies
651
707
  dependencies.forEach(depSet => {
652
708
  depSet.delete(execute);
653
709
  });
654
710
  dependencies.clear();
711
+ versions.clear();
655
712
  if (cleanup) {
656
713
  try {
657
- cleanup();
714
+ untrack(cleanup);
658
715
  }
659
716
  catch (error) {
660
717
  console.error('[Effect] Error in final cleanup:', error);
@@ -714,6 +771,8 @@
714
771
  const effects = Array.from(batchedEffects);
715
772
  batchedEffects.clear();
716
773
  effects.forEach(effect => {
774
+ // This batch also settles any earlier queued write to this observer.
775
+ effectQueue.delete(effect);
717
776
  try {
718
777
  effect();
719
778
  }
@@ -2234,59 +2293,59 @@
2234
2293
  return;
2235
2294
  const style = document.createElement('style');
2236
2295
  style.id = styleId;
2237
- style.textContent = `
2238
- /* Opacity utilities */
2296
+ style.textContent = `
2297
+ /* Opacity utilities */
2239
2298
  .gyos-t-opacity-0 { opacity: 0; }
2240
2299
  .gyos-t-opacity-100 { opacity: 1; }
2241
-
2242
- /* Transform - Translate Y */
2300
+
2301
+ /* Transform - Translate Y */
2243
2302
  .gyos-t-translate-y-0 { transform: translateY(0); }
2244
2303
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2245
2304
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2246
-
2247
- /* Transform - Translate X */
2305
+
2306
+ /* Transform - Translate X */
2248
2307
  .gyos-t-translate-x-0 { transform: translateX(0); }
2249
2308
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2250
2309
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2251
-
2252
- /* Transform - Scale */
2310
+
2311
+ /* Transform - Scale */
2253
2312
  .gyos-t-scale-0 { transform: scale(0); }
2254
2313
  .gyos-t-scale-50 { transform: scale(0.5); }
2255
2314
  .gyos-t-scale-100 { transform: scale(1); }
2256
-
2257
- /* Animation Keyframes */
2258
- @keyframes gyos-fade-in {
2259
- from { opacity: 0; }
2260
- to { opacity: 1; }
2261
- }
2262
-
2263
- @keyframes gyos-fade-out {
2264
- from { opacity: 1; }
2265
- to { opacity: 0; }
2266
- }
2267
-
2268
- @keyframes gyos-slide-down {
2269
- from { transform: translateY(-100%); opacity: 0; }
2270
- to { transform: translateY(0); opacity: 1; }
2271
- }
2272
-
2273
- @keyframes gyos-slide-up {
2274
- from { transform: translateY(100%); opacity: 0; }
2275
- to { transform: translateY(0); opacity: 1; }
2276
- }
2277
-
2278
- @keyframes gyos-scale-in {
2279
- from { transform: scale(0); opacity: 0; }
2280
- to { transform: scale(1); opacity: 1; }
2281
- }
2282
-
2283
- @keyframes gyos-scale-out {
2284
- from { transform: scale(1); opacity: 1; }
2285
- to { transform: scale(0); opacity: 0; }
2286
- }
2287
-
2288
- [g-cloak] {
2289
- display: none !important;
2315
+
2316
+ /* Animation Keyframes */
2317
+ @keyframes gyos-fade-in {
2318
+ from { opacity: 0; }
2319
+ to { opacity: 1; }
2320
+ }
2321
+
2322
+ @keyframes gyos-fade-out {
2323
+ from { opacity: 1; }
2324
+ to { opacity: 0; }
2325
+ }
2326
+
2327
+ @keyframes gyos-slide-down {
2328
+ from { transform: translateY(-100%); opacity: 0; }
2329
+ to { transform: translateY(0); opacity: 1; }
2330
+ }
2331
+
2332
+ @keyframes gyos-slide-up {
2333
+ from { transform: translateY(100%); opacity: 0; }
2334
+ to { transform: translateY(0); opacity: 1; }
2335
+ }
2336
+
2337
+ @keyframes gyos-scale-in {
2338
+ from { transform: scale(0); opacity: 0; }
2339
+ to { transform: scale(1); opacity: 1; }
2340
+ }
2341
+
2342
+ @keyframes gyos-scale-out {
2343
+ from { transform: scale(1); opacity: 1; }
2344
+ to { transform: scale(0); opacity: 0; }
2345
+ }
2346
+
2347
+ [g-cloak] {
2348
+ display: none !important;
2290
2349
  }`;
2291
2350
  document.head.appendChild(style);
2292
2351
  }
@@ -6643,33 +6702,44 @@
6643
6702
  getCurrentProgress() {
6644
6703
  return this.currentProgress;
6645
6704
  }
6705
+ reconnect() {
6706
+ if (!this.element || !this.progressBarEnabled || !document.body)
6707
+ return;
6708
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6709
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6710
+ if (node !== this.element)
6711
+ node.remove();
6712
+ });
6713
+ if (!this.element.isConnected)
6714
+ document.body.appendChild(this.element);
6715
+ }
6646
6716
  createBar() {
6647
6717
  if (typeof document === 'undefined')
6648
6718
  return;
6649
6719
  // Create progress bar element
6650
6720
  this.element = document.createElement('div');
6651
6721
  this.element.id = 'gyos-progress-bar';
6652
- this.element.style.cssText = `
6653
- position: fixed;
6654
- top: 0;
6655
- left: 0;
6656
- width: 0%;
6657
- height: 6px;
6658
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6659
- z-index: 999999;
6660
- transition: width 0.3s linear, opacity 0.3s linear;
6661
- opacity: 0;
6662
- pointer-events: none;
6663
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6722
+ this.element.style.cssText = `
6723
+ position: fixed;
6724
+ top: 0;
6725
+ left: 0;
6726
+ width: 0%;
6727
+ height: 6px;
6728
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6729
+ z-index: 999999;
6730
+ transition: width 0.3s linear, opacity 0.3s linear;
6731
+ opacity: 0;
6732
+ pointer-events: none;
6733
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6664
6734
  `;
6665
6735
  // Insert into DOM when ready
6666
6736
  if (document.readyState === 'loading') {
6667
6737
  document.addEventListener('DOMContentLoaded', () => {
6668
- document.body.insertAdjacentElement('beforeend', this.element);
6669
- });
6738
+ this.reconnect();
6739
+ }, { once: true });
6670
6740
  }
6671
6741
  else {
6672
- document.body.insertAdjacentElement('beforeend', this.element);
6742
+ this.reconnect();
6673
6743
  }
6674
6744
  }
6675
6745
  start() {
@@ -6693,6 +6763,7 @@
6693
6763
  setProgress(percent) {
6694
6764
  if (!this.element || !this.progressBarEnabled)
6695
6765
  return;
6766
+ this.reconnect();
6696
6767
  // Clamp between 0-100
6697
6768
  percent = Math.min(100, Math.max(0, percent));
6698
6769
  this.currentProgress = percent;
@@ -6741,41 +6812,41 @@
6741
6812
  function createTargetSpinner() {
6742
6813
  const spinner = document.createElement('div');
6743
6814
  spinner.className = 'gyos-target-spinner';
6744
- spinner.innerHTML = `
6745
- <div class="gyos-spinner-content">
6746
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6747
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6748
- </svg>
6749
- </div>
6815
+ spinner.innerHTML = `
6816
+ <div class="gyos-spinner-content">
6817
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6818
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6819
+ </svg>
6820
+ </div>
6750
6821
  `;
6751
6822
  // Inject styles if not already present
6752
6823
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6753
6824
  const style = document.createElement('style');
6754
6825
  style.id = 'gyos-target-spinner-styles';
6755
- style.textContent = `
6756
- .gyos-target-spinner {
6757
- display: flex;
6758
- align-items: center;
6759
- justify-content: center;
6760
- padding: 20px;
6761
- min-height: 60px;
6762
- }
6763
- .gyos-spinner-content {
6764
- display: flex;
6765
- align-items: center;
6766
- gap: 10px;
6767
- color: var(--gyos-spinner-color, #667eea);
6768
- font-size: 14px;
6769
- }
6770
- .gyos-spinner-icon {
6771
- width: 24px;
6772
- height: 24px;
6773
- animation: gyos-spin 1s linear infinite;
6774
- }
6775
- @keyframes gyos-spin {
6776
- 0% { transform: rotate(0deg); }
6777
- 100% { transform: rotate(360deg); }
6778
- }
6826
+ style.textContent = `
6827
+ .gyos-target-spinner {
6828
+ display: flex;
6829
+ align-items: center;
6830
+ justify-content: center;
6831
+ padding: 20px;
6832
+ min-height: 60px;
6833
+ }
6834
+ .gyos-spinner-content {
6835
+ display: flex;
6836
+ align-items: center;
6837
+ gap: 10px;
6838
+ color: var(--gyos-spinner-color, #667eea);
6839
+ font-size: 14px;
6840
+ }
6841
+ .gyos-spinner-icon {
6842
+ width: 24px;
6843
+ height: 24px;
6844
+ animation: gyos-spin 1s linear infinite;
6845
+ }
6846
+ @keyframes gyos-spin {
6847
+ 0% { transform: rotate(0deg); }
6848
+ 100% { transform: rotate(360deg); }
6849
+ }
6779
6850
  `;
6780
6851
  document.head.appendChild(style);
6781
6852
  }
@@ -7135,8 +7206,8 @@
7135
7206
  }
7136
7207
  result = target;
7137
7208
  }
7138
- await options.beforeScripts?.();
7139
7209
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7210
+ await options.beforeScripts?.();
7140
7211
  // Additive swaps must not re-run scripts that already existed in the target.
7141
7212
  if (normalized === 'append' || normalized === 'prepend') {
7142
7213
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7376,6 +7447,21 @@
7376
7447
  window.scrollTo({ top: 0, behavior: 'smooth' });
7377
7448
  }
7378
7449
 
7450
+ // A retained relative URL still identifies the resource loaded on its original
7451
+ // page, even after pushState changes document.baseURI.
7452
+ const resourceUrls = new WeakMap();
7453
+ function rememberResourceUrls(root, baseUrl) {
7454
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7455
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7456
+ const source = node.getAttribute(attribute);
7457
+ if (resourceUrls.get(node)?.source === source)
7458
+ return;
7459
+ try {
7460
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7461
+ }
7462
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7463
+ });
7464
+ }
7379
7465
  function isNonceMeta(el) {
7380
7466
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7381
7467
  }
@@ -7393,7 +7479,20 @@
7393
7479
  return;
7394
7480
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7395
7481
  return;
7396
- attributes.set(attr.name, attr.value);
7482
+ let value = attr.value;
7483
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7484
+ const cached = resourceUrls.get(el);
7485
+ if (cached?.source === value)
7486
+ value = cached.url;
7487
+ else {
7488
+ try {
7489
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7490
+ resourceUrls.set(el, { source: attr.value, url: value });
7491
+ }
7492
+ catch { /* Keep invalid URLs distinct. */ }
7493
+ }
7494
+ }
7495
+ attributes.set(attr.name, value);
7397
7496
  });
7398
7497
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7399
7498
  attributes.set('nonce', context.activeNonce);
@@ -7460,19 +7559,21 @@
7460
7559
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7461
7560
  }
7462
7561
  }
7463
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7562
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7464
7563
  const csp = expressionRuntimeMode() === 'csp';
7465
7564
  const context = {
7466
7565
  csp,
7467
7566
  activeNonce: csp ? resolveCspNonce() : undefined
7468
7567
  };
7469
- const current = keyedNodes(currentNodes, context);
7568
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7470
7569
  const next = keyedNodes(nextNodes, context);
7570
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7571
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7471
7572
  const currentKeys = new Set(current.map(item => item.key));
7472
7573
  const nextKeys = new Set(next.map(item => item.key));
7473
7574
  // Remove nodes that are not in the new head
7474
7575
  current.forEach(({ key, node }) => {
7475
- if (!nextKeys.has(key)) {
7576
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7476
7577
  node.remove();
7477
7578
  }
7478
7579
  });
@@ -7480,6 +7581,8 @@
7480
7581
  for (const { key, node } of next) {
7481
7582
  if (signal?.aborted)
7482
7583
  return;
7584
+ if (persistent.has(persistentKey(node)))
7585
+ continue;
7483
7586
  if (!currentKeys.has(key)) {
7484
7587
  if (!canInsertNode(node, context)) {
7485
7588
  warnSkippedNode(node);
@@ -7682,6 +7785,7 @@
7682
7785
  * MPA boost navigation inspired by Turbo Drive.
7683
7786
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7684
7787
  */
7788
+ const submittingForms = new WeakSet();
7685
7789
  const snapshots = new Map();
7686
7790
  const preloadCache = new Map();
7687
7791
  const preloadControllers = new Map();
@@ -7698,12 +7802,30 @@
7698
7802
  let progressBar = null;
7699
7803
  const beforeNavigate = [];
7700
7804
  const afterNavigate = [];
7805
+ const beforeSwap = [];
7806
+ const navigationEnd = [];
7807
+ function registerNavigationHook(hooks, callback) {
7808
+ // A wrapper gives each registration its own unsubscribe identity.
7809
+ const entry = (url, context) => callback(url, context);
7810
+ hooks.push(entry);
7811
+ return () => {
7812
+ const index = hooks.indexOf(entry);
7813
+ if (index !== -1)
7814
+ hooks.splice(index, 1);
7815
+ };
7816
+ }
7701
7817
  // Expose hooks to register before/after navigation callbacks
7702
7818
  function onBeforeNavigate(callback) {
7703
- beforeNavigate.push(callback);
7819
+ return registerNavigationHook(beforeNavigate, callback);
7704
7820
  }
7705
7821
  function onAfterNavigate(callback) {
7706
- afterNavigate.push(callback);
7822
+ return registerNavigationHook(afterNavigate, callback);
7823
+ }
7824
+ function onBeforeSwap(callback) {
7825
+ return registerNavigationHook(beforeSwap, callback);
7826
+ }
7827
+ function onNavigationEnd(callback) {
7828
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7707
7829
  }
7708
7830
  function startRouter(options) {
7709
7831
  // If not has g-boost attribute, do not start router
@@ -7727,6 +7849,7 @@
7727
7849
  }
7728
7850
  // Cache scripts from initial page to prevent re-execution on first navigation back
7729
7851
  cacheInitialPageScripts();
7852
+ rememberResourceUrls(document, document.baseURI);
7730
7853
  routerStarted = true;
7731
7854
  log('[GyosRouter] started');
7732
7855
  }
@@ -7783,9 +7906,13 @@
7783
7906
  const outlet = findGlobalOutlet();
7784
7907
  return outlet instanceof HTMLElement ? outlet : null;
7785
7908
  }
7909
+ function isFullDocument(html) {
7910
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7911
+ }
7786
7912
  function saveSnapshot(url, html) {
7787
7913
  // create HTMLElement by html string to remove scripts and get clean snapshot
7788
7914
  const doc = parseNavigationDocument(html);
7915
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7789
7916
  // Ignore hash for snapshot keys
7790
7917
  if (url.includes('#'))
7791
7918
  url = url.split('#')[0];
@@ -7794,7 +7921,7 @@
7794
7921
  if (s.hasAttribute('g-script-once'))
7795
7922
  s.textContent = '';
7796
7923
  });
7797
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7924
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7798
7925
  log('[GyosRouter] snapshot saved for', url);
7799
7926
  }
7800
7927
  function getOutletIndex(root, target) {
@@ -7906,10 +8033,10 @@
7906
8033
  // update callback remains the navigation source of truth and is awaited below.
7907
8034
  void promise?.catch(() => undefined);
7908
8035
  }
7909
- function runNavigationHooks(callbacks, url) {
7910
- callbacks.forEach(callback => {
8036
+ function runNavigationHooks(callbacks, url, context) {
8037
+ [...callbacks].forEach(callback => {
7911
8038
  try {
7912
- callback(url);
8039
+ callback(url, { ...context });
7913
8040
  }
7914
8041
  catch (error) {
7915
8042
  console.error('[GyosRouter] navigation hook error', error);
@@ -7947,7 +8074,13 @@
7947
8074
  url = mergeFormDataIntoUrl(url, opts.formData);
7948
8075
  }
7949
8076
  else {
7950
- init.body = opts.formData;
8077
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8078
+ const encoded = new URLSearchParams();
8079
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8080
+ init.body = encoded;
8081
+ }
8082
+ else
8083
+ init.body = opts.formData;
7951
8084
  }
7952
8085
  }
7953
8086
  else if (opts.jsonData) {
@@ -7990,25 +8123,26 @@
7990
8123
  preloadControllers.delete(cacheKey);
7991
8124
  });
7992
8125
  }
7993
- async function updateHead(fromDoc, signal) {
8126
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7994
8127
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7995
8128
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7996
8129
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7997
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8130
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7998
8131
  }
7999
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8132
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
8000
8133
  // scripts in current document and it not in target outlet
8001
8134
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
8002
8135
  // scripts in fromDoc and it not in source outlet
8003
8136
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
8004
8137
  // Diff and update scripts not in outlet/target
8005
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8138
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
8006
8139
  }
8007
8140
  function resolveIncomingScriptUrls(root, baseUrl) {
8008
- root.querySelectorAll('script[src]').forEach(script => {
8009
- const source = script.getAttribute('src');
8141
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8142
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8143
+ const source = node.getAttribute(attribute);
8010
8144
  if (source)
8011
- script.src = new URL(source, baseUrl).href;
8145
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
8012
8146
  });
8013
8147
  }
8014
8148
  function isNavigableHtmlResponse(response) {
@@ -8062,6 +8196,22 @@
8062
8196
  resolveDone
8063
8197
  };
8064
8198
  activeNavigation = transaction;
8199
+ const currentBaseUrl = document.baseURI;
8200
+ rememberResourceUrls(document, currentBaseUrl);
8201
+ const context = {
8202
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8203
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8204
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8205
+ status: null, committed: false, fallback: false, outcome: null
8206
+ };
8207
+ const formEvent = opts.form
8208
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8209
+ : null;
8210
+ const fallback = (url, requestSent) => {
8211
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8212
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8213
+ fallbackFromBoost(opts, url, requestSent);
8214
+ };
8065
8215
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8066
8216
  const setRand = () => {
8067
8217
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8069,7 +8219,10 @@
8069
8219
  }
8070
8220
  };
8071
8221
  try {
8072
- runNavigationHooks(beforeNavigate, opts.url);
8222
+ if (formEvent)
8223
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8224
+ runNavigationHooks(beforeNavigate, opts.url, context);
8225
+ assertActiveNavigation(transaction);
8073
8226
  progressBar?.start();
8074
8227
  // popstate already points history at the destination entry. Keep the visible
8075
8228
  // page's position under currentUrl without overwriting that destination state.
@@ -8078,9 +8231,10 @@
8078
8231
  saveScrollPosition();
8079
8232
  // Pick target element to swap
8080
8233
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8234
+ context.target = target;
8081
8235
  if (!target) {
8082
8236
  if (isActiveNavigation(transaction))
8083
- fallbackFromBoost(opts, opts.url, false);
8237
+ fallback(opts.url, false);
8084
8238
  return;
8085
8239
  }
8086
8240
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8105,6 +8259,7 @@
8105
8259
  if (hasTargetSpinner)
8106
8260
  transaction.spinner = showTargetSpinner(target, swapMode);
8107
8261
  const { finalUrl, init } = buildRequest(opts);
8262
+ context.url = finalUrl;
8108
8263
  // Add abort signal to request
8109
8264
  init.signal = transaction.controller.signal;
8110
8265
  let html;
@@ -8132,7 +8287,8 @@
8132
8287
  if (error.name === 'AbortError')
8133
8288
  throw error;
8134
8289
  assertActiveNavigation(transaction);
8135
- window.location.href = finalUrl;
8290
+ context.outcome = 'network-error';
8291
+ fallback(finalUrl, true);
8136
8292
  return;
8137
8293
  }
8138
8294
  preloadCache.delete(preloadKey); // consume cache
@@ -8157,28 +8313,46 @@
8157
8313
  log('[GyosRouter] Navigation cancelled');
8158
8314
  return;
8159
8315
  }
8316
+ context.outcome = 'network-error';
8160
8317
  if (isActiveNavigation(transaction))
8161
- fallbackFromBoost(opts, finalUrl, true);
8318
+ fallback(finalUrl, true);
8162
8319
  return;
8163
8320
  }
8164
8321
  }
8165
8322
  assertActiveNavigation(transaction);
8166
- // If response not ok, fallback to full navigation
8167
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8323
+ context.status = response?.status ?? null;
8324
+ context.url = response?.url || finalUrl;
8325
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8326
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8327
+ && acceptedErrors.includes(String(response.status));
8328
+ if (response && !response.ok)
8329
+ context.outcome = 'http-error';
8330
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8331
+ context.outcome ?? (context.outcome = 'invalid-response');
8168
8332
  if (isActiveNavigation(transaction))
8169
- fallbackFromBoost(opts, finalUrl, true);
8333
+ fallback(finalUrl, true);
8170
8334
  return;
8171
8335
  }
8172
8336
  html = await response.text();
8173
8337
  assertActiveNavigation(transaction);
8174
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8175
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8176
- }
8177
8338
  }
8178
8339
  // Parse HTML
8179
8340
  const doc = html
8180
8341
  ? parseNavigationDocument(html)
8181
8342
  : document.implementation.createHTMLDocument();
8343
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8344
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8345
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8346
+ context.outcome = 'invalid-response';
8347
+ fallback(response?.url || finalUrl, true);
8348
+ return;
8349
+ }
8350
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8351
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8352
+ }
8353
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8354
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8355
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8182
8356
  // Pick source fragment
8183
8357
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8184
8358
  stripInertFallbackContent(src);
@@ -8190,15 +8364,18 @@
8190
8364
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8191
8365
  }
8192
8366
  resolveIncomingScriptUrls(doc, targetUrl);
8367
+ context.url = targetUrl;
8193
8368
  if (opts.historyFragment)
8194
8369
  resolveIncomingScriptUrls(src, targetUrl);
8195
8370
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8196
8371
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8197
8372
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8198
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8373
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8199
8374
  const performUpdate = async () => {
8200
8375
  assertActiveNavigation(transaction);
8201
8376
  transaction.committing = true;
8377
+ runNavigationHooks(beforeSwap, targetUrl, context);
8378
+ assertActiveNavigation(transaction);
8202
8379
  // Update progress to rand 80 - 90% before swap
8203
8380
  progressBar?.setProgress(Math.random() * 10 + 80);
8204
8381
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8269,21 +8446,34 @@
8269
8446
  beforeScripts: async () => {
8270
8447
  if (!isFullOutletNavigation || currentHead)
8271
8448
  return;
8449
+ if (syncDocumentAttributes) {
8450
+ for (const name of ['lang', 'dir']) {
8451
+ const value = doc.documentElement.getAttribute(name);
8452
+ if (value === null)
8453
+ document.documentElement.removeAttribute(name);
8454
+ else
8455
+ document.documentElement.setAttribute(name, value);
8456
+ }
8457
+ }
8272
8458
  const incomingTitle = doc.querySelector('title');
8273
8459
  if (incomingTitle) {
8274
8460
  document.title = incomingTitle.textContent || document.title;
8275
8461
  }
8276
- await updateHead(doc, transaction.controller.signal);
8462
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8277
8463
  assertActiveNavigation(transaction);
8278
8464
  },
8279
8465
  onCommitted: (committedTarget, roots) => {
8280
8466
  target = committedTarget;
8467
+ context.target = committedTarget;
8468
+ context.committed = true;
8469
+ progressBar?.reconnect();
8281
8470
  committedRoots = roots;
8282
8471
  }
8283
8472
  });
8473
+ context.committed = true;
8284
8474
  assertActiveNavigation(transaction);
8285
8475
  if (isFullOutletNavigation) {
8286
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8476
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8287
8477
  assertActiveNavigation(transaction);
8288
8478
  }
8289
8479
  }
@@ -8317,14 +8507,15 @@
8317
8507
  await performUpdate();
8318
8508
  }
8319
8509
  assertActiveNavigation(transaction);
8320
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8510
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8321
8511
  disposeEffects(opts.trigger);
8322
8512
  opts.trigger.remove();
8323
8513
  }
8324
8514
  if (hasTargetSpinner)
8325
8515
  hideTargetSpinner(transaction.spinner);
8326
8516
  transaction.spinner = null;
8327
- runNavigationHooks(afterNavigate, targetUrl);
8517
+ context.outcome ?? (context.outcome = 'success');
8518
+ runNavigationHooks(afterNavigate, targetUrl, context);
8328
8519
  log('[GyosRouter] navigated to', targetUrl);
8329
8520
  currentUrl = changesState
8330
8521
  ? canonicalUrl(targetUrl, true)
@@ -8340,11 +8531,15 @@
8340
8531
  return;
8341
8532
  }
8342
8533
  if (isActiveNavigation(transaction)) {
8534
+ context.outcome ?? (context.outcome = 'error');
8343
8535
  console.error('[GyosRouter] navigation error', error);
8344
- fallbackFromBoost(opts, opts.url, true);
8536
+ fallback(opts.url, true);
8345
8537
  }
8346
8538
  }
8347
8539
  finally {
8540
+ if (transaction.controller.signal.aborted)
8541
+ context.outcome = 'aborted';
8542
+ context.outcome ?? (context.outcome = 'aborted');
8348
8543
  if (transaction.interval)
8349
8544
  clearInterval(transaction.interval);
8350
8545
  if (transaction.spinner)
@@ -8354,6 +8549,15 @@
8354
8549
  progressBar?.complete();
8355
8550
  }
8356
8551
  transaction.resolveDone();
8552
+ if (formEvent)
8553
+ submittingForms.delete(formEvent.form);
8554
+ runNavigationHooks(navigationEnd, context.url, context);
8555
+ if (formEvent) {
8556
+ const { url, status, outcome, committed, fallback } = context;
8557
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8558
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8559
+ }));
8560
+ }
8357
8561
  }
8358
8562
  }
8359
8563
  function shouldBoost(el) {
@@ -8462,16 +8666,34 @@
8462
8666
  return;
8463
8667
  if (shouldDeferToFormValidation(form))
8464
8668
  return;
8465
- event.preventDefault();
8466
- const action = form.action || window.location.href;
8467
- const method = (form.method || 'GET').toUpperCase();
8468
- const url = new URL(action, window.location.href);
8469
- if (url.origin !== window.location.origin) {
8470
- window.location.href = url.toString();
8669
+ const submitter = event.submitter;
8670
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8671
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8672
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8673
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8674
+ const formEncoding = override('enctype')?.toLowerCase();
8675
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8676
+ return;
8677
+ if (!resolveTarget(form))
8678
+ return;
8679
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8680
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8471
8681
  return;
8682
+ let url;
8683
+ try {
8684
+ url = new URL(override('action') || window.location.href, document.baseURI);
8472
8685
  }
8473
- const formData = new FormData(form);
8474
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8686
+ catch {
8687
+ return;
8688
+ }
8689
+ if (url.origin !== window.location.origin)
8690
+ return;
8691
+ event.preventDefault();
8692
+ if (submittingForms.has(form))
8693
+ return;
8694
+ const formData = new FormData(form, submitter);
8695
+ submittingForms.add(form);
8696
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8475
8697
  }
8476
8698
  function onPopState(event) {
8477
8699
  const url = window.location.href;
@@ -8576,10 +8798,12 @@
8576
8798
  startRouter,
8577
8799
  onBeforeNavigate,
8578
8800
  onAfterNavigate,
8801
+ onBeforeSwap,
8802
+ onNavigationEnd,
8579
8803
  portalCreate,
8580
8804
  portalDestroy,
8581
8805
  setCspNonce,
8582
- version: '0.3.2'
8806
+ version: '0.4.1'
8583
8807
  };
8584
8808
 
8585
8809
  setExpressionRuntime(standardExpressionRuntime);
@@ -8615,6 +8839,8 @@
8615
8839
  exports.on = on;
8616
8840
  exports.onAfterNavigate = onAfterNavigate;
8617
8841
  exports.onBeforeNavigate = onBeforeNavigate;
8842
+ exports.onBeforeSwap = onBeforeSwap;
8843
+ exports.onNavigationEnd = onNavigationEnd;
8618
8844
  exports.once = once;
8619
8845
  exports.pipe = pipe;
8620
8846
  exports.portalCreate = portalCreate;