gyosjs 0.3.1 → 0.4.0

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.auto.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.1
2
+ * GyosJS v0.4.0
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -2202,59 +2202,59 @@
2202
2202
  return;
2203
2203
  const style = document.createElement('style');
2204
2204
  style.id = styleId;
2205
- style.textContent = `
2206
- /* Opacity utilities */
2205
+ style.textContent = `
2206
+ /* Opacity utilities */
2207
2207
  .gyos-t-opacity-0 { opacity: 0; }
2208
2208
  .gyos-t-opacity-100 { opacity: 1; }
2209
-
2210
- /* Transform - Translate Y */
2209
+
2210
+ /* Transform - Translate Y */
2211
2211
  .gyos-t-translate-y-0 { transform: translateY(0); }
2212
2212
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2213
2213
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2214
-
2215
- /* Transform - Translate X */
2214
+
2215
+ /* Transform - Translate X */
2216
2216
  .gyos-t-translate-x-0 { transform: translateX(0); }
2217
2217
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2218
2218
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2219
-
2220
- /* Transform - Scale */
2219
+
2220
+ /* Transform - Scale */
2221
2221
  .gyos-t-scale-0 { transform: scale(0); }
2222
2222
  .gyos-t-scale-50 { transform: scale(0.5); }
2223
2223
  .gyos-t-scale-100 { transform: scale(1); }
2224
-
2225
- /* Animation Keyframes */
2226
- @keyframes gyos-fade-in {
2227
- from { opacity: 0; }
2228
- to { opacity: 1; }
2229
- }
2230
-
2231
- @keyframes gyos-fade-out {
2232
- from { opacity: 1; }
2233
- to { opacity: 0; }
2234
- }
2235
-
2236
- @keyframes gyos-slide-down {
2237
- from { transform: translateY(-100%); opacity: 0; }
2238
- to { transform: translateY(0); opacity: 1; }
2239
- }
2240
-
2241
- @keyframes gyos-slide-up {
2242
- from { transform: translateY(100%); opacity: 0; }
2243
- to { transform: translateY(0); opacity: 1; }
2244
- }
2245
-
2246
- @keyframes gyos-scale-in {
2247
- from { transform: scale(0); opacity: 0; }
2248
- to { transform: scale(1); opacity: 1; }
2249
- }
2250
-
2251
- @keyframes gyos-scale-out {
2252
- from { transform: scale(1); opacity: 1; }
2253
- to { transform: scale(0); opacity: 0; }
2254
- }
2255
-
2256
- [g-cloak] {
2257
- display: none !important;
2224
+
2225
+ /* Animation Keyframes */
2226
+ @keyframes gyos-fade-in {
2227
+ from { opacity: 0; }
2228
+ to { opacity: 1; }
2229
+ }
2230
+
2231
+ @keyframes gyos-fade-out {
2232
+ from { opacity: 1; }
2233
+ to { opacity: 0; }
2234
+ }
2235
+
2236
+ @keyframes gyos-slide-down {
2237
+ from { transform: translateY(-100%); opacity: 0; }
2238
+ to { transform: translateY(0); opacity: 1; }
2239
+ }
2240
+
2241
+ @keyframes gyos-slide-up {
2242
+ from { transform: translateY(100%); opacity: 0; }
2243
+ to { transform: translateY(0); opacity: 1; }
2244
+ }
2245
+
2246
+ @keyframes gyos-scale-in {
2247
+ from { transform: scale(0); opacity: 0; }
2248
+ to { transform: scale(1); opacity: 1; }
2249
+ }
2250
+
2251
+ @keyframes gyos-scale-out {
2252
+ from { transform: scale(1); opacity: 1; }
2253
+ to { transform: scale(0); opacity: 0; }
2254
+ }
2255
+
2256
+ [g-cloak] {
2257
+ display: none !important;
2258
2258
  }`;
2259
2259
  document.head.appendChild(style);
2260
2260
  }
@@ -5189,6 +5189,10 @@
5189
5189
  const structuralElements = [];
5190
5190
  const root = elements[0];
5191
5191
  elements.forEach(el => {
5192
+ // Await branches are detached and parsed only after their alias scope exists.
5193
+ // Do not evaluate nested structural expressions during the parent scan.
5194
+ if (isAwaitBranchDescendant(el))
5195
+ return;
5192
5196
  const hasIf = el.hasAttribute('*if');
5193
5197
  const hasFor = el.hasAttribute('*for');
5194
5198
  const hasSwitch = el.hasAttribute('*switch');
@@ -5233,6 +5237,20 @@
5233
5237
  }
5234
5238
  });
5235
5239
  }
5240
+ function isAwaitBranchDescendant(element) {
5241
+ let child = element;
5242
+ let parent = element.parentElement;
5243
+ while (parent && parent !== document.body) {
5244
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5245
+ child.hasAttribute('*then') ||
5246
+ child.hasAttribute('*catch'))) {
5247
+ return true;
5248
+ }
5249
+ child = parent;
5250
+ parent = parent.parentElement;
5251
+ }
5252
+ return false;
5253
+ }
5236
5254
  const elementBelongsToAnotherScope = (el, scope) => {
5237
5255
  const owner = getScopeFromElement(el);
5238
5256
  return Boolean(owner && owner !== scope);
@@ -6593,33 +6611,44 @@
6593
6611
  getCurrentProgress() {
6594
6612
  return this.currentProgress;
6595
6613
  }
6614
+ reconnect() {
6615
+ if (!this.element || !this.progressBarEnabled || !document.body)
6616
+ return;
6617
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6618
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6619
+ if (node !== this.element)
6620
+ node.remove();
6621
+ });
6622
+ if (!this.element.isConnected)
6623
+ document.body.appendChild(this.element);
6624
+ }
6596
6625
  createBar() {
6597
6626
  if (typeof document === 'undefined')
6598
6627
  return;
6599
6628
  // Create progress bar element
6600
6629
  this.element = document.createElement('div');
6601
6630
  this.element.id = 'gyos-progress-bar';
6602
- this.element.style.cssText = `
6603
- position: fixed;
6604
- top: 0;
6605
- left: 0;
6606
- width: 0%;
6607
- height: 6px;
6608
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6609
- z-index: 999999;
6610
- transition: width 0.3s linear, opacity 0.3s linear;
6611
- opacity: 0;
6612
- pointer-events: none;
6613
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6631
+ this.element.style.cssText = `
6632
+ position: fixed;
6633
+ top: 0;
6634
+ left: 0;
6635
+ width: 0%;
6636
+ height: 6px;
6637
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6638
+ z-index: 999999;
6639
+ transition: width 0.3s linear, opacity 0.3s linear;
6640
+ opacity: 0;
6641
+ pointer-events: none;
6642
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6614
6643
  `;
6615
6644
  // Insert into DOM when ready
6616
6645
  if (document.readyState === 'loading') {
6617
6646
  document.addEventListener('DOMContentLoaded', () => {
6618
- document.body.insertAdjacentElement('beforeend', this.element);
6619
- });
6647
+ this.reconnect();
6648
+ }, { once: true });
6620
6649
  }
6621
6650
  else {
6622
- document.body.insertAdjacentElement('beforeend', this.element);
6651
+ this.reconnect();
6623
6652
  }
6624
6653
  }
6625
6654
  start() {
@@ -6643,6 +6672,7 @@
6643
6672
  setProgress(percent) {
6644
6673
  if (!this.element || !this.progressBarEnabled)
6645
6674
  return;
6675
+ this.reconnect();
6646
6676
  // Clamp between 0-100
6647
6677
  percent = Math.min(100, Math.max(0, percent));
6648
6678
  this.currentProgress = percent;
@@ -6691,41 +6721,41 @@
6691
6721
  function createTargetSpinner() {
6692
6722
  const spinner = document.createElement('div');
6693
6723
  spinner.className = 'gyos-target-spinner';
6694
- spinner.innerHTML = `
6695
- <div class="gyos-spinner-content">
6696
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6697
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6698
- </svg>
6699
- </div>
6724
+ spinner.innerHTML = `
6725
+ <div class="gyos-spinner-content">
6726
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6727
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6728
+ </svg>
6729
+ </div>
6700
6730
  `;
6701
6731
  // Inject styles if not already present
6702
6732
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6703
6733
  const style = document.createElement('style');
6704
6734
  style.id = 'gyos-target-spinner-styles';
6705
- style.textContent = `
6706
- .gyos-target-spinner {
6707
- display: flex;
6708
- align-items: center;
6709
- justify-content: center;
6710
- padding: 20px;
6711
- min-height: 60px;
6712
- }
6713
- .gyos-spinner-content {
6714
- display: flex;
6715
- align-items: center;
6716
- gap: 10px;
6717
- color: var(--gyos-spinner-color, #667eea);
6718
- font-size: 14px;
6719
- }
6720
- .gyos-spinner-icon {
6721
- width: 24px;
6722
- height: 24px;
6723
- animation: gyos-spin 1s linear infinite;
6724
- }
6725
- @keyframes gyos-spin {
6726
- 0% { transform: rotate(0deg); }
6727
- 100% { transform: rotate(360deg); }
6728
- }
6735
+ style.textContent = `
6736
+ .gyos-target-spinner {
6737
+ display: flex;
6738
+ align-items: center;
6739
+ justify-content: center;
6740
+ padding: 20px;
6741
+ min-height: 60px;
6742
+ }
6743
+ .gyos-spinner-content {
6744
+ display: flex;
6745
+ align-items: center;
6746
+ gap: 10px;
6747
+ color: var(--gyos-spinner-color, #667eea);
6748
+ font-size: 14px;
6749
+ }
6750
+ .gyos-spinner-icon {
6751
+ width: 24px;
6752
+ height: 24px;
6753
+ animation: gyos-spin 1s linear infinite;
6754
+ }
6755
+ @keyframes gyos-spin {
6756
+ 0% { transform: rotate(0deg); }
6757
+ 100% { transform: rotate(360deg); }
6758
+ }
6729
6759
  `;
6730
6760
  document.head.appendChild(style);
6731
6761
  }
@@ -7085,8 +7115,8 @@
7085
7115
  }
7086
7116
  result = target;
7087
7117
  }
7088
- await options.beforeScripts?.();
7089
7118
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7119
+ await options.beforeScripts?.();
7090
7120
  // Additive swaps must not re-run scripts that already existed in the target.
7091
7121
  if (normalized === 'append' || normalized === 'prepend') {
7092
7122
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7326,6 +7356,21 @@
7326
7356
  window.scrollTo({ top: 0, behavior: 'smooth' });
7327
7357
  }
7328
7358
 
7359
+ // A retained relative URL still identifies the resource loaded on its original
7360
+ // page, even after pushState changes document.baseURI.
7361
+ const resourceUrls = new WeakMap();
7362
+ function rememberResourceUrls(root, baseUrl) {
7363
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7364
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7365
+ const source = node.getAttribute(attribute);
7366
+ if (resourceUrls.get(node)?.source === source)
7367
+ return;
7368
+ try {
7369
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7370
+ }
7371
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7372
+ });
7373
+ }
7329
7374
  function isNonceMeta(el) {
7330
7375
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7331
7376
  }
@@ -7343,7 +7388,20 @@
7343
7388
  return;
7344
7389
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7345
7390
  return;
7346
- attributes.set(attr.name, attr.value);
7391
+ let value = attr.value;
7392
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7393
+ const cached = resourceUrls.get(el);
7394
+ if (cached?.source === value)
7395
+ value = cached.url;
7396
+ else {
7397
+ try {
7398
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7399
+ resourceUrls.set(el, { source: attr.value, url: value });
7400
+ }
7401
+ catch { /* Keep invalid URLs distinct. */ }
7402
+ }
7403
+ }
7404
+ attributes.set(attr.name, value);
7347
7405
  });
7348
7406
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7349
7407
  attributes.set('nonce', context.activeNonce);
@@ -7410,19 +7468,21 @@
7410
7468
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7411
7469
  }
7412
7470
  }
7413
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7471
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7414
7472
  const csp = expressionRuntimeMode() === 'csp';
7415
7473
  const context = {
7416
7474
  csp,
7417
7475
  activeNonce: csp ? resolveCspNonce() : undefined
7418
7476
  };
7419
- const current = keyedNodes(currentNodes, context);
7477
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7420
7478
  const next = keyedNodes(nextNodes, context);
7479
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7480
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7421
7481
  const currentKeys = new Set(current.map(item => item.key));
7422
7482
  const nextKeys = new Set(next.map(item => item.key));
7423
7483
  // Remove nodes that are not in the new head
7424
7484
  current.forEach(({ key, node }) => {
7425
- if (!nextKeys.has(key)) {
7485
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7426
7486
  node.remove();
7427
7487
  }
7428
7488
  });
@@ -7430,6 +7490,8 @@
7430
7490
  for (const { key, node } of next) {
7431
7491
  if (signal?.aborted)
7432
7492
  return;
7493
+ if (persistent.has(persistentKey(node)))
7494
+ continue;
7433
7495
  if (!currentKeys.has(key)) {
7434
7496
  if (!canInsertNode(node, context)) {
7435
7497
  warnSkippedNode(node);
@@ -7632,6 +7694,7 @@
7632
7694
  * MPA boost navigation inspired by Turbo Drive.
7633
7695
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7634
7696
  */
7697
+ const submittingForms = new WeakSet();
7635
7698
  const snapshots = new Map();
7636
7699
  const preloadCache = new Map();
7637
7700
  const preloadControllers = new Map();
@@ -7648,12 +7711,30 @@
7648
7711
  let progressBar = null;
7649
7712
  const beforeNavigate = [];
7650
7713
  const afterNavigate = [];
7714
+ const beforeSwap = [];
7715
+ const navigationEnd = [];
7716
+ function registerNavigationHook(hooks, callback) {
7717
+ // A wrapper gives each registration its own unsubscribe identity.
7718
+ const entry = (url, context) => callback(url, context);
7719
+ hooks.push(entry);
7720
+ return () => {
7721
+ const index = hooks.indexOf(entry);
7722
+ if (index !== -1)
7723
+ hooks.splice(index, 1);
7724
+ };
7725
+ }
7651
7726
  // Expose hooks to register before/after navigation callbacks
7652
7727
  function onBeforeNavigate(callback) {
7653
- beforeNavigate.push(callback);
7728
+ return registerNavigationHook(beforeNavigate, callback);
7654
7729
  }
7655
7730
  function onAfterNavigate(callback) {
7656
- afterNavigate.push(callback);
7731
+ return registerNavigationHook(afterNavigate, callback);
7732
+ }
7733
+ function onBeforeSwap(callback) {
7734
+ return registerNavigationHook(beforeSwap, callback);
7735
+ }
7736
+ function onNavigationEnd(callback) {
7737
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7657
7738
  }
7658
7739
  function startRouter(options) {
7659
7740
  // If not has g-boost attribute, do not start router
@@ -7677,6 +7758,7 @@
7677
7758
  }
7678
7759
  // Cache scripts from initial page to prevent re-execution on first navigation back
7679
7760
  cacheInitialPageScripts();
7761
+ rememberResourceUrls(document, document.baseURI);
7680
7762
  routerStarted = true;
7681
7763
  log('[GyosRouter] started');
7682
7764
  }
@@ -7733,9 +7815,13 @@
7733
7815
  const outlet = findGlobalOutlet();
7734
7816
  return outlet instanceof HTMLElement ? outlet : null;
7735
7817
  }
7818
+ function isFullDocument(html) {
7819
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7820
+ }
7736
7821
  function saveSnapshot(url, html) {
7737
7822
  // create HTMLElement by html string to remove scripts and get clean snapshot
7738
7823
  const doc = parseNavigationDocument(html);
7824
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7739
7825
  // Ignore hash for snapshot keys
7740
7826
  if (url.includes('#'))
7741
7827
  url = url.split('#')[0];
@@ -7744,7 +7830,7 @@
7744
7830
  if (s.hasAttribute('g-script-once'))
7745
7831
  s.textContent = '';
7746
7832
  });
7747
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7833
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7748
7834
  log('[GyosRouter] snapshot saved for', url);
7749
7835
  }
7750
7836
  function getOutletIndex(root, target) {
@@ -7856,10 +7942,10 @@
7856
7942
  // update callback remains the navigation source of truth and is awaited below.
7857
7943
  void promise?.catch(() => undefined);
7858
7944
  }
7859
- function runNavigationHooks(callbacks, url) {
7860
- callbacks.forEach(callback => {
7945
+ function runNavigationHooks(callbacks, url, context) {
7946
+ [...callbacks].forEach(callback => {
7861
7947
  try {
7862
- callback(url);
7948
+ callback(url, { ...context });
7863
7949
  }
7864
7950
  catch (error) {
7865
7951
  console.error('[GyosRouter] navigation hook error', error);
@@ -7897,7 +7983,13 @@
7897
7983
  url = mergeFormDataIntoUrl(url, opts.formData);
7898
7984
  }
7899
7985
  else {
7900
- init.body = opts.formData;
7986
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
7987
+ const encoded = new URLSearchParams();
7988
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
7989
+ init.body = encoded;
7990
+ }
7991
+ else
7992
+ init.body = opts.formData;
7901
7993
  }
7902
7994
  }
7903
7995
  else if (opts.jsonData) {
@@ -7940,25 +8032,26 @@
7940
8032
  preloadControllers.delete(cacheKey);
7941
8033
  });
7942
8034
  }
7943
- async function updateHead(fromDoc, signal) {
8035
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7944
8036
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7945
8037
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7946
8038
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7947
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8039
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7948
8040
  }
7949
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8041
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7950
8042
  // scripts in current document and it not in target outlet
7951
8043
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7952
8044
  // scripts in fromDoc and it not in source outlet
7953
8045
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7954
8046
  // Diff and update scripts not in outlet/target
7955
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8047
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7956
8048
  }
7957
8049
  function resolveIncomingScriptUrls(root, baseUrl) {
7958
- root.querySelectorAll('script[src]').forEach(script => {
7959
- const source = script.getAttribute('src');
8050
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8051
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8052
+ const source = node.getAttribute(attribute);
7960
8053
  if (source)
7961
- script.src = new URL(source, baseUrl).href;
8054
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7962
8055
  });
7963
8056
  }
7964
8057
  function isNavigableHtmlResponse(response) {
@@ -8012,6 +8105,22 @@
8012
8105
  resolveDone
8013
8106
  };
8014
8107
  activeNavigation = transaction;
8108
+ const currentBaseUrl = document.baseURI;
8109
+ rememberResourceUrls(document, currentBaseUrl);
8110
+ const context = {
8111
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8112
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8113
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8114
+ status: null, committed: false, fallback: false, outcome: null
8115
+ };
8116
+ const formEvent = opts.form
8117
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8118
+ : null;
8119
+ const fallback = (url, requestSent) => {
8120
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8121
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8122
+ fallbackFromBoost(opts, url, requestSent);
8123
+ };
8015
8124
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8016
8125
  const setRand = () => {
8017
8126
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8019,7 +8128,10 @@
8019
8128
  }
8020
8129
  };
8021
8130
  try {
8022
- runNavigationHooks(beforeNavigate, opts.url);
8131
+ if (formEvent)
8132
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8133
+ runNavigationHooks(beforeNavigate, opts.url, context);
8134
+ assertActiveNavigation(transaction);
8023
8135
  progressBar?.start();
8024
8136
  // popstate already points history at the destination entry. Keep the visible
8025
8137
  // page's position under currentUrl without overwriting that destination state.
@@ -8028,9 +8140,10 @@
8028
8140
  saveScrollPosition();
8029
8141
  // Pick target element to swap
8030
8142
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8143
+ context.target = target;
8031
8144
  if (!target) {
8032
8145
  if (isActiveNavigation(transaction))
8033
- fallbackFromBoost(opts, opts.url, false);
8146
+ fallback(opts.url, false);
8034
8147
  return;
8035
8148
  }
8036
8149
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8055,6 +8168,7 @@
8055
8168
  if (hasTargetSpinner)
8056
8169
  transaction.spinner = showTargetSpinner(target, swapMode);
8057
8170
  const { finalUrl, init } = buildRequest(opts);
8171
+ context.url = finalUrl;
8058
8172
  // Add abort signal to request
8059
8173
  init.signal = transaction.controller.signal;
8060
8174
  let html;
@@ -8082,7 +8196,8 @@
8082
8196
  if (error.name === 'AbortError')
8083
8197
  throw error;
8084
8198
  assertActiveNavigation(transaction);
8085
- window.location.href = finalUrl;
8199
+ context.outcome = 'network-error';
8200
+ fallback(finalUrl, true);
8086
8201
  return;
8087
8202
  }
8088
8203
  preloadCache.delete(preloadKey); // consume cache
@@ -8107,28 +8222,46 @@
8107
8222
  log('[GyosRouter] Navigation cancelled');
8108
8223
  return;
8109
8224
  }
8225
+ context.outcome = 'network-error';
8110
8226
  if (isActiveNavigation(transaction))
8111
- fallbackFromBoost(opts, finalUrl, true);
8227
+ fallback(finalUrl, true);
8112
8228
  return;
8113
8229
  }
8114
8230
  }
8115
8231
  assertActiveNavigation(transaction);
8116
- // If response not ok, fallback to full navigation
8117
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8232
+ context.status = response?.status ?? null;
8233
+ context.url = response?.url || finalUrl;
8234
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8235
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8236
+ && acceptedErrors.includes(String(response.status));
8237
+ if (response && !response.ok)
8238
+ context.outcome = 'http-error';
8239
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8240
+ context.outcome ?? (context.outcome = 'invalid-response');
8118
8241
  if (isActiveNavigation(transaction))
8119
- fallbackFromBoost(opts, finalUrl, true);
8242
+ fallback(finalUrl, true);
8120
8243
  return;
8121
8244
  }
8122
8245
  html = await response.text();
8123
8246
  assertActiveNavigation(transaction);
8124
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8125
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8126
- }
8127
8247
  }
8128
8248
  // Parse HTML
8129
8249
  const doc = html
8130
8250
  ? parseNavigationDocument(html)
8131
8251
  : document.implementation.createHTMLDocument();
8252
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8253
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8254
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8255
+ context.outcome = 'invalid-response';
8256
+ fallback(response?.url || finalUrl, true);
8257
+ return;
8258
+ }
8259
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8260
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8261
+ }
8262
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8263
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8264
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8132
8265
  // Pick source fragment
8133
8266
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8134
8267
  stripInertFallbackContent(src);
@@ -8140,15 +8273,18 @@
8140
8273
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8141
8274
  }
8142
8275
  resolveIncomingScriptUrls(doc, targetUrl);
8276
+ context.url = targetUrl;
8143
8277
  if (opts.historyFragment)
8144
8278
  resolveIncomingScriptUrls(src, targetUrl);
8145
8279
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8146
8280
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8147
8281
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8148
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8282
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8149
8283
  const performUpdate = async () => {
8150
8284
  assertActiveNavigation(transaction);
8151
8285
  transaction.committing = true;
8286
+ runNavigationHooks(beforeSwap, targetUrl, context);
8287
+ assertActiveNavigation(transaction);
8152
8288
  // Update progress to rand 80 - 90% before swap
8153
8289
  progressBar?.setProgress(Math.random() * 10 + 80);
8154
8290
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8219,21 +8355,34 @@
8219
8355
  beforeScripts: async () => {
8220
8356
  if (!isFullOutletNavigation || currentHead)
8221
8357
  return;
8358
+ if (syncDocumentAttributes) {
8359
+ for (const name of ['lang', 'dir']) {
8360
+ const value = doc.documentElement.getAttribute(name);
8361
+ if (value === null)
8362
+ document.documentElement.removeAttribute(name);
8363
+ else
8364
+ document.documentElement.setAttribute(name, value);
8365
+ }
8366
+ }
8222
8367
  const incomingTitle = doc.querySelector('title');
8223
8368
  if (incomingTitle) {
8224
8369
  document.title = incomingTitle.textContent || document.title;
8225
8370
  }
8226
- await updateHead(doc, transaction.controller.signal);
8371
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8227
8372
  assertActiveNavigation(transaction);
8228
8373
  },
8229
8374
  onCommitted: (committedTarget, roots) => {
8230
8375
  target = committedTarget;
8376
+ context.target = committedTarget;
8377
+ context.committed = true;
8378
+ progressBar?.reconnect();
8231
8379
  committedRoots = roots;
8232
8380
  }
8233
8381
  });
8382
+ context.committed = true;
8234
8383
  assertActiveNavigation(transaction);
8235
8384
  if (isFullOutletNavigation) {
8236
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8385
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8237
8386
  assertActiveNavigation(transaction);
8238
8387
  }
8239
8388
  }
@@ -8267,14 +8416,15 @@
8267
8416
  await performUpdate();
8268
8417
  }
8269
8418
  assertActiveNavigation(transaction);
8270
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8419
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8271
8420
  disposeEffects(opts.trigger);
8272
8421
  opts.trigger.remove();
8273
8422
  }
8274
8423
  if (hasTargetSpinner)
8275
8424
  hideTargetSpinner(transaction.spinner);
8276
8425
  transaction.spinner = null;
8277
- runNavigationHooks(afterNavigate, targetUrl);
8426
+ context.outcome ?? (context.outcome = 'success');
8427
+ runNavigationHooks(afterNavigate, targetUrl, context);
8278
8428
  log('[GyosRouter] navigated to', targetUrl);
8279
8429
  currentUrl = changesState
8280
8430
  ? canonicalUrl(targetUrl, true)
@@ -8290,11 +8440,15 @@
8290
8440
  return;
8291
8441
  }
8292
8442
  if (isActiveNavigation(transaction)) {
8443
+ context.outcome ?? (context.outcome = 'error');
8293
8444
  console.error('[GyosRouter] navigation error', error);
8294
- fallbackFromBoost(opts, opts.url, true);
8445
+ fallback(opts.url, true);
8295
8446
  }
8296
8447
  }
8297
8448
  finally {
8449
+ if (transaction.controller.signal.aborted)
8450
+ context.outcome = 'aborted';
8451
+ context.outcome ?? (context.outcome = 'aborted');
8298
8452
  if (transaction.interval)
8299
8453
  clearInterval(transaction.interval);
8300
8454
  if (transaction.spinner)
@@ -8304,6 +8458,15 @@
8304
8458
  progressBar?.complete();
8305
8459
  }
8306
8460
  transaction.resolveDone();
8461
+ if (formEvent)
8462
+ submittingForms.delete(formEvent.form);
8463
+ runNavigationHooks(navigationEnd, context.url, context);
8464
+ if (formEvent) {
8465
+ const { url, status, outcome, committed, fallback } = context;
8466
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8467
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8468
+ }));
8469
+ }
8307
8470
  }
8308
8471
  }
8309
8472
  function shouldBoost(el) {
@@ -8412,16 +8575,34 @@
8412
8575
  return;
8413
8576
  if (shouldDeferToFormValidation(form))
8414
8577
  return;
8415
- event.preventDefault();
8416
- const action = form.action || window.location.href;
8417
- const method = (form.method || 'GET').toUpperCase();
8418
- const url = new URL(action, window.location.href);
8419
- if (url.origin !== window.location.origin) {
8420
- window.location.href = url.toString();
8578
+ const submitter = event.submitter;
8579
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8580
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8581
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8582
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8583
+ const formEncoding = override('enctype')?.toLowerCase();
8584
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8585
+ return;
8586
+ if (!resolveTarget(form))
8587
+ return;
8588
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8589
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8590
+ return;
8591
+ let url;
8592
+ try {
8593
+ url = new URL(override('action') || window.location.href, document.baseURI);
8594
+ }
8595
+ catch {
8421
8596
  return;
8422
8597
  }
8423
- const formData = new FormData(form);
8424
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8598
+ if (url.origin !== window.location.origin)
8599
+ return;
8600
+ event.preventDefault();
8601
+ if (submittingForms.has(form))
8602
+ return;
8603
+ const formData = new FormData(form, submitter);
8604
+ submittingForms.add(form);
8605
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8425
8606
  }
8426
8607
  function onPopState(event) {
8427
8608
  const url = window.location.href;
@@ -8526,10 +8707,12 @@
8526
8707
  startRouter,
8527
8708
  onBeforeNavigate,
8528
8709
  onAfterNavigate,
8710
+ onBeforeSwap,
8711
+ onNavigationEnd,
8529
8712
  portalCreate,
8530
8713
  portalDestroy,
8531
8714
  setCspNonce,
8532
- version: '0.3.1'
8715
+ version: '0.4.0'
8533
8716
  };
8534
8717
 
8535
8718
  const standardExpressionRuntime = {