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.
@@ -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
  */
@@ -8845,59 +8845,59 @@ function applyTransitionStyles() {
8845
8845
  return;
8846
8846
  const style = document.createElement('style');
8847
8847
  style.id = styleId;
8848
- style.textContent = `
8849
- /* Opacity utilities */
8848
+ style.textContent = `
8849
+ /* Opacity utilities */
8850
8850
  .gyos-t-opacity-0 { opacity: 0; }
8851
8851
  .gyos-t-opacity-100 { opacity: 1; }
8852
-
8853
- /* Transform - Translate Y */
8852
+
8853
+ /* Transform - Translate Y */
8854
8854
  .gyos-t-translate-y-0 { transform: translateY(0); }
8855
8855
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
8856
8856
  .gyos-t-translate-y-100 { transform: translateY(100%); }
8857
-
8858
- /* Transform - Translate X */
8857
+
8858
+ /* Transform - Translate X */
8859
8859
  .gyos-t-translate-x-0 { transform: translateX(0); }
8860
8860
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
8861
8861
  .gyos-t-translate-x-100 { transform: translateX(100%); }
8862
-
8863
- /* Transform - Scale */
8862
+
8863
+ /* Transform - Scale */
8864
8864
  .gyos-t-scale-0 { transform: scale(0); }
8865
8865
  .gyos-t-scale-50 { transform: scale(0.5); }
8866
8866
  .gyos-t-scale-100 { transform: scale(1); }
8867
-
8868
- /* Animation Keyframes */
8869
- @keyframes gyos-fade-in {
8870
- from { opacity: 0; }
8871
- to { opacity: 1; }
8872
- }
8873
-
8874
- @keyframes gyos-fade-out {
8875
- from { opacity: 1; }
8876
- to { opacity: 0; }
8877
- }
8878
-
8879
- @keyframes gyos-slide-down {
8880
- from { transform: translateY(-100%); opacity: 0; }
8881
- to { transform: translateY(0); opacity: 1; }
8882
- }
8883
-
8884
- @keyframes gyos-slide-up {
8885
- from { transform: translateY(100%); opacity: 0; }
8886
- to { transform: translateY(0); opacity: 1; }
8887
- }
8888
-
8889
- @keyframes gyos-scale-in {
8890
- from { transform: scale(0); opacity: 0; }
8891
- to { transform: scale(1); opacity: 1; }
8892
- }
8893
-
8894
- @keyframes gyos-scale-out {
8895
- from { transform: scale(1); opacity: 1; }
8896
- to { transform: scale(0); opacity: 0; }
8897
- }
8898
-
8899
- [g-cloak] {
8900
- display: none !important;
8867
+
8868
+ /* Animation Keyframes */
8869
+ @keyframes gyos-fade-in {
8870
+ from { opacity: 0; }
8871
+ to { opacity: 1; }
8872
+ }
8873
+
8874
+ @keyframes gyos-fade-out {
8875
+ from { opacity: 1; }
8876
+ to { opacity: 0; }
8877
+ }
8878
+
8879
+ @keyframes gyos-slide-down {
8880
+ from { transform: translateY(-100%); opacity: 0; }
8881
+ to { transform: translateY(0); opacity: 1; }
8882
+ }
8883
+
8884
+ @keyframes gyos-slide-up {
8885
+ from { transform: translateY(100%); opacity: 0; }
8886
+ to { transform: translateY(0); opacity: 1; }
8887
+ }
8888
+
8889
+ @keyframes gyos-scale-in {
8890
+ from { transform: scale(0); opacity: 0; }
8891
+ to { transform: scale(1); opacity: 1; }
8892
+ }
8893
+
8894
+ @keyframes gyos-scale-out {
8895
+ from { transform: scale(1); opacity: 1; }
8896
+ to { transform: scale(0); opacity: 0; }
8897
+ }
8898
+
8899
+ [g-cloak] {
8900
+ display: none !important;
8901
8901
  }`;
8902
8902
  document.head.appendChild(style);
8903
8903
  }
@@ -11832,6 +11832,10 @@ function processStructuralDirectives(elements, scope) {
11832
11832
  const structuralElements = [];
11833
11833
  const root = elements[0];
11834
11834
  elements.forEach(el => {
11835
+ // Await branches are detached and parsed only after their alias scope exists.
11836
+ // Do not evaluate nested structural expressions during the parent scan.
11837
+ if (isAwaitBranchDescendant(el))
11838
+ return;
11835
11839
  const hasIf = el.hasAttribute('*if');
11836
11840
  const hasFor = el.hasAttribute('*for');
11837
11841
  const hasSwitch = el.hasAttribute('*switch');
@@ -11876,6 +11880,20 @@ function processStructuralDirectives(elements, scope) {
11876
11880
  }
11877
11881
  });
11878
11882
  }
11883
+ function isAwaitBranchDescendant(element) {
11884
+ let child = element;
11885
+ let parent = element.parentElement;
11886
+ while (parent && parent !== document.body) {
11887
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
11888
+ child.hasAttribute('*then') ||
11889
+ child.hasAttribute('*catch'))) {
11890
+ return true;
11891
+ }
11892
+ child = parent;
11893
+ parent = parent.parentElement;
11894
+ }
11895
+ return false;
11896
+ }
11879
11897
  const elementBelongsToAnotherScope = (el, scope) => {
11880
11898
  const owner = getScopeFromElement(el);
11881
11899
  return Boolean(owner && owner !== scope);
@@ -13236,33 +13254,44 @@ class ProgressBar {
13236
13254
  getCurrentProgress() {
13237
13255
  return this.currentProgress;
13238
13256
  }
13257
+ reconnect() {
13258
+ if (!this.element || !this.progressBarEnabled || !document.body)
13259
+ return;
13260
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
13261
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
13262
+ if (node !== this.element)
13263
+ node.remove();
13264
+ });
13265
+ if (!this.element.isConnected)
13266
+ document.body.appendChild(this.element);
13267
+ }
13239
13268
  createBar() {
13240
13269
  if (typeof document === 'undefined')
13241
13270
  return;
13242
13271
  // Create progress bar element
13243
13272
  this.element = document.createElement('div');
13244
13273
  this.element.id = 'gyos-progress-bar';
13245
- this.element.style.cssText = `
13246
- position: fixed;
13247
- top: 0;
13248
- left: 0;
13249
- width: 0%;
13250
- height: 6px;
13251
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
13252
- z-index: 999999;
13253
- transition: width 0.3s linear, opacity 0.3s linear;
13254
- opacity: 0;
13255
- pointer-events: none;
13256
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
13274
+ this.element.style.cssText = `
13275
+ position: fixed;
13276
+ top: 0;
13277
+ left: 0;
13278
+ width: 0%;
13279
+ height: 6px;
13280
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
13281
+ z-index: 999999;
13282
+ transition: width 0.3s linear, opacity 0.3s linear;
13283
+ opacity: 0;
13284
+ pointer-events: none;
13285
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
13257
13286
  `;
13258
13287
  // Insert into DOM when ready
13259
13288
  if (document.readyState === 'loading') {
13260
13289
  document.addEventListener('DOMContentLoaded', () => {
13261
- document.body.insertAdjacentElement('beforeend', this.element);
13262
- });
13290
+ this.reconnect();
13291
+ }, { once: true });
13263
13292
  }
13264
13293
  else {
13265
- document.body.insertAdjacentElement('beforeend', this.element);
13294
+ this.reconnect();
13266
13295
  }
13267
13296
  }
13268
13297
  start() {
@@ -13286,6 +13315,7 @@ class ProgressBar {
13286
13315
  setProgress(percent) {
13287
13316
  if (!this.element || !this.progressBarEnabled)
13288
13317
  return;
13318
+ this.reconnect();
13289
13319
  // Clamp between 0-100
13290
13320
  percent = Math.min(100, Math.max(0, percent));
13291
13321
  this.currentProgress = percent;
@@ -13334,41 +13364,41 @@ class ProgressBar {
13334
13364
  function createTargetSpinner() {
13335
13365
  const spinner = document.createElement('div');
13336
13366
  spinner.className = 'gyos-target-spinner';
13337
- spinner.innerHTML = `
13338
- <div class="gyos-spinner-content">
13339
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
13340
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
13341
- </svg>
13342
- </div>
13367
+ spinner.innerHTML = `
13368
+ <div class="gyos-spinner-content">
13369
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
13370
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
13371
+ </svg>
13372
+ </div>
13343
13373
  `;
13344
13374
  // Inject styles if not already present
13345
13375
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
13346
13376
  const style = document.createElement('style');
13347
13377
  style.id = 'gyos-target-spinner-styles';
13348
- style.textContent = `
13349
- .gyos-target-spinner {
13350
- display: flex;
13351
- align-items: center;
13352
- justify-content: center;
13353
- padding: 20px;
13354
- min-height: 60px;
13355
- }
13356
- .gyos-spinner-content {
13357
- display: flex;
13358
- align-items: center;
13359
- gap: 10px;
13360
- color: var(--gyos-spinner-color, #667eea);
13361
- font-size: 14px;
13362
- }
13363
- .gyos-spinner-icon {
13364
- width: 24px;
13365
- height: 24px;
13366
- animation: gyos-spin 1s linear infinite;
13367
- }
13368
- @keyframes gyos-spin {
13369
- 0% { transform: rotate(0deg); }
13370
- 100% { transform: rotate(360deg); }
13371
- }
13378
+ style.textContent = `
13379
+ .gyos-target-spinner {
13380
+ display: flex;
13381
+ align-items: center;
13382
+ justify-content: center;
13383
+ padding: 20px;
13384
+ min-height: 60px;
13385
+ }
13386
+ .gyos-spinner-content {
13387
+ display: flex;
13388
+ align-items: center;
13389
+ gap: 10px;
13390
+ color: var(--gyos-spinner-color, #667eea);
13391
+ font-size: 14px;
13392
+ }
13393
+ .gyos-spinner-icon {
13394
+ width: 24px;
13395
+ height: 24px;
13396
+ animation: gyos-spin 1s linear infinite;
13397
+ }
13398
+ @keyframes gyos-spin {
13399
+ 0% { transform: rotate(0deg); }
13400
+ 100% { transform: rotate(360deg); }
13401
+ }
13372
13402
  `;
13373
13403
  document.head.appendChild(style);
13374
13404
  }
@@ -13728,8 +13758,8 @@ async function performSwap(target, src, mode, options = {}) {
13728
13758
  }
13729
13759
  result = target;
13730
13760
  }
13731
- await options.beforeScripts?.();
13732
13761
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
13762
+ await options.beforeScripts?.();
13733
13763
  // Additive swaps must not re-run scripts that already existed in the target.
13734
13764
  if (normalized === 'append' || normalized === 'prepend') {
13735
13765
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -13969,6 +13999,21 @@ function handleScroll(url, trigger, savedScroll) {
13969
13999
  window.scrollTo({ top: 0, behavior: 'smooth' });
13970
14000
  }
13971
14001
 
14002
+ // A retained relative URL still identifies the resource loaded on its original
14003
+ // page, even after pushState changes document.baseURI.
14004
+ const resourceUrls = new WeakMap();
14005
+ function rememberResourceUrls(root, baseUrl) {
14006
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
14007
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
14008
+ const source = node.getAttribute(attribute);
14009
+ if (resourceUrls.get(node)?.source === source)
14010
+ return;
14011
+ try {
14012
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
14013
+ }
14014
+ catch { /* Invalid resource URLs retain their literal identity. */ }
14015
+ });
14016
+ }
13972
14017
  function isNonceMeta(el) {
13973
14018
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
13974
14019
  }
@@ -13986,7 +14031,20 @@ function serializeAttributes(el, context) {
13986
14031
  return;
13987
14032
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
13988
14033
  return;
13989
- attributes.set(attr.name, attr.value);
14034
+ let value = attr.value;
14035
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
14036
+ const cached = resourceUrls.get(el);
14037
+ if (cached?.source === value)
14038
+ value = cached.url;
14039
+ else {
14040
+ try {
14041
+ value = new URL(value, context.baseUrl || el.baseURI).href;
14042
+ resourceUrls.set(el, { source: attr.value, url: value });
14043
+ }
14044
+ catch { /* Keep invalid URLs distinct. */ }
14045
+ }
14046
+ }
14047
+ attributes.set(attr.name, value);
13990
14048
  });
13991
14049
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
13992
14050
  attributes.set('nonce', context.activeNonce);
@@ -14053,19 +14111,21 @@ function warnSkippedNode(node) {
14053
14111
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
14054
14112
  }
14055
14113
  }
14056
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
14114
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
14057
14115
  const csp = expressionRuntimeMode() === 'csp';
14058
14116
  const context = {
14059
14117
  csp,
14060
14118
  activeNonce: csp ? resolveCspNonce() : undefined
14061
14119
  };
14062
- const current = keyedNodes(currentNodes, context);
14120
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
14063
14121
  const next = keyedNodes(nextNodes, context);
14122
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
14123
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
14064
14124
  const currentKeys = new Set(current.map(item => item.key));
14065
14125
  const nextKeys = new Set(next.map(item => item.key));
14066
14126
  // Remove nodes that are not in the new head
14067
14127
  current.forEach(({ key, node }) => {
14068
- if (!nextKeys.has(key)) {
14128
+ if (!nextKeys.has(key) && !persistentKey(node)) {
14069
14129
  node.remove();
14070
14130
  }
14071
14131
  });
@@ -14073,6 +14133,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
14073
14133
  for (const { key, node } of next) {
14074
14134
  if (signal?.aborted)
14075
14135
  return;
14136
+ if (persistent.has(persistentKey(node)))
14137
+ continue;
14076
14138
  if (!currentKeys.has(key)) {
14077
14139
  if (!canInsertNode(node, context)) {
14078
14140
  warnSkippedNode(node);
@@ -14275,6 +14337,7 @@ function prepareNavigationHtml(html) {
14275
14337
  * MPA boost navigation inspired by Turbo Drive.
14276
14338
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
14277
14339
  */
14340
+ const submittingForms = new WeakSet();
14278
14341
  const snapshots = new Map();
14279
14342
  const preloadCache = new Map();
14280
14343
  const preloadControllers = new Map();
@@ -14291,12 +14354,30 @@ let activeNavigation = null;
14291
14354
  let progressBar = null;
14292
14355
  const beforeNavigate = [];
14293
14356
  const afterNavigate = [];
14357
+ const beforeSwap = [];
14358
+ const navigationEnd = [];
14359
+ function registerNavigationHook(hooks, callback) {
14360
+ // A wrapper gives each registration its own unsubscribe identity.
14361
+ const entry = (url, context) => callback(url, context);
14362
+ hooks.push(entry);
14363
+ return () => {
14364
+ const index = hooks.indexOf(entry);
14365
+ if (index !== -1)
14366
+ hooks.splice(index, 1);
14367
+ };
14368
+ }
14294
14369
  // Expose hooks to register before/after navigation callbacks
14295
14370
  function onBeforeNavigate(callback) {
14296
- beforeNavigate.push(callback);
14371
+ return registerNavigationHook(beforeNavigate, callback);
14297
14372
  }
14298
14373
  function onAfterNavigate(callback) {
14299
- afterNavigate.push(callback);
14374
+ return registerNavigationHook(afterNavigate, callback);
14375
+ }
14376
+ function onBeforeSwap(callback) {
14377
+ return registerNavigationHook(beforeSwap, callback);
14378
+ }
14379
+ function onNavigationEnd(callback) {
14380
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
14300
14381
  }
14301
14382
  function startRouter(options) {
14302
14383
  // If not has g-boost attribute, do not start router
@@ -14320,6 +14401,7 @@ function startRouter(options) {
14320
14401
  }
14321
14402
  // Cache scripts from initial page to prevent re-execution on first navigation back
14322
14403
  cacheInitialPageScripts();
14404
+ rememberResourceUrls(document, document.baseURI);
14323
14405
  routerStarted = true;
14324
14406
  log('[GyosRouter] started');
14325
14407
  }
@@ -14376,9 +14458,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
14376
14458
  const outlet = findGlobalOutlet();
14377
14459
  return outlet instanceof HTMLElement ? outlet : null;
14378
14460
  }
14461
+ function isFullDocument(html) {
14462
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
14463
+ }
14379
14464
  function saveSnapshot(url, html) {
14380
14465
  // create HTMLElement by html string to remove scripts and get clean snapshot
14381
14466
  const doc = parseNavigationDocument(html);
14467
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
14382
14468
  // Ignore hash for snapshot keys
14383
14469
  if (url.includes('#'))
14384
14470
  url = url.split('#')[0];
@@ -14387,7 +14473,7 @@ function saveSnapshot(url, html) {
14387
14473
  if (s.hasAttribute('g-script-once'))
14388
14474
  s.textContent = '';
14389
14475
  });
14390
- snapshots.set(url, { html: doc.documentElement.outerHTML });
14476
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
14391
14477
  log('[GyosRouter] snapshot saved for', url);
14392
14478
  }
14393
14479
  function getOutletIndex(root, target) {
@@ -14499,10 +14585,10 @@ function consumeViewTransitionRejection(promise) {
14499
14585
  // update callback remains the navigation source of truth and is awaited below.
14500
14586
  void promise?.catch(() => undefined);
14501
14587
  }
14502
- function runNavigationHooks(callbacks, url) {
14503
- callbacks.forEach(callback => {
14588
+ function runNavigationHooks(callbacks, url, context) {
14589
+ [...callbacks].forEach(callback => {
14504
14590
  try {
14505
- callback(url);
14591
+ callback(url, { ...context });
14506
14592
  }
14507
14593
  catch (error) {
14508
14594
  console.error('[GyosRouter] navigation hook error', error);
@@ -14540,7 +14626,13 @@ function buildRequest(opts) {
14540
14626
  url = mergeFormDataIntoUrl(url, opts.formData);
14541
14627
  }
14542
14628
  else {
14543
- init.body = opts.formData;
14629
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
14630
+ const encoded = new URLSearchParams();
14631
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
14632
+ init.body = encoded;
14633
+ }
14634
+ else
14635
+ init.body = opts.formData;
14544
14636
  }
14545
14637
  }
14546
14638
  else if (opts.jsonData) {
@@ -14583,25 +14675,26 @@ function preload(url) {
14583
14675
  preloadControllers.delete(cacheKey);
14584
14676
  });
14585
14677
  }
14586
- async function updateHead(fromDoc, signal) {
14678
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
14587
14679
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
14588
14680
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
14589
14681
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
14590
- await diffNodes(currentNodes, nextNodes, document.head, signal);
14682
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
14591
14683
  }
14592
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
14684
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
14593
14685
  // scripts in current document and it not in target outlet
14594
14686
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
14595
14687
  // scripts in fromDoc and it not in source outlet
14596
14688
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
14597
14689
  // Diff and update scripts not in outlet/target
14598
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
14690
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
14599
14691
  }
14600
14692
  function resolveIncomingScriptUrls(root, baseUrl) {
14601
- root.querySelectorAll('script[src]').forEach(script => {
14602
- const source = script.getAttribute('src');
14693
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
14694
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
14695
+ const source = node.getAttribute(attribute);
14603
14696
  if (source)
14604
- script.src = new URL(source, baseUrl).href;
14697
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
14605
14698
  });
14606
14699
  }
14607
14700
  function isNavigableHtmlResponse(response) {
@@ -14655,6 +14748,22 @@ async function navigate(opts) {
14655
14748
  resolveDone
14656
14749
  };
14657
14750
  activeNavigation = transaction;
14751
+ const currentBaseUrl = document.baseURI;
14752
+ rememberResourceUrls(document, currentBaseUrl);
14753
+ const context = {
14754
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
14755
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
14756
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
14757
+ status: null, committed: false, fallback: false, outcome: null
14758
+ };
14759
+ const formEvent = opts.form
14760
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
14761
+ : null;
14762
+ const fallback = (url, requestSent) => {
14763
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
14764
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
14765
+ fallbackFromBoost(opts, url, requestSent);
14766
+ };
14658
14767
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
14659
14768
  const setRand = () => {
14660
14769
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -14662,7 +14771,10 @@ async function navigate(opts) {
14662
14771
  }
14663
14772
  };
14664
14773
  try {
14665
- runNavigationHooks(beforeNavigate, opts.url);
14774
+ if (formEvent)
14775
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
14776
+ runNavigationHooks(beforeNavigate, opts.url, context);
14777
+ assertActiveNavigation(transaction);
14666
14778
  progressBar?.start();
14667
14779
  // popstate already points history at the destination entry. Keep the visible
14668
14780
  // page's position under currentUrl without overwriting that destination state.
@@ -14671,9 +14783,10 @@ async function navigate(opts) {
14671
14783
  saveScrollPosition();
14672
14784
  // Pick target element to swap
14673
14785
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
14786
+ context.target = target;
14674
14787
  if (!target) {
14675
14788
  if (isActiveNavigation(transaction))
14676
- fallbackFromBoost(opts, opts.url, false);
14789
+ fallback(opts.url, false);
14677
14790
  return;
14678
14791
  }
14679
14792
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -14698,6 +14811,7 @@ async function navigate(opts) {
14698
14811
  if (hasTargetSpinner)
14699
14812
  transaction.spinner = showTargetSpinner(target, swapMode);
14700
14813
  const { finalUrl, init } = buildRequest(opts);
14814
+ context.url = finalUrl;
14701
14815
  // Add abort signal to request
14702
14816
  init.signal = transaction.controller.signal;
14703
14817
  let html;
@@ -14725,7 +14839,8 @@ async function navigate(opts) {
14725
14839
  if (error.name === 'AbortError')
14726
14840
  throw error;
14727
14841
  assertActiveNavigation(transaction);
14728
- window.location.href = finalUrl;
14842
+ context.outcome = 'network-error';
14843
+ fallback(finalUrl, true);
14729
14844
  return;
14730
14845
  }
14731
14846
  preloadCache.delete(preloadKey); // consume cache
@@ -14750,28 +14865,46 @@ async function navigate(opts) {
14750
14865
  log('[GyosRouter] Navigation cancelled');
14751
14866
  return;
14752
14867
  }
14868
+ context.outcome = 'network-error';
14753
14869
  if (isActiveNavigation(transaction))
14754
- fallbackFromBoost(opts, finalUrl, true);
14870
+ fallback(finalUrl, true);
14755
14871
  return;
14756
14872
  }
14757
14873
  }
14758
14874
  assertActiveNavigation(transaction);
14759
- // If response not ok, fallback to full navigation
14760
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
14875
+ context.status = response?.status ?? null;
14876
+ context.url = response?.url || finalUrl;
14877
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
14878
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
14879
+ && acceptedErrors.includes(String(response.status));
14880
+ if (response && !response.ok)
14881
+ context.outcome = 'http-error';
14882
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
14883
+ context.outcome ?? (context.outcome = 'invalid-response');
14761
14884
  if (isActiveNavigation(transaction))
14762
- fallbackFromBoost(opts, finalUrl, true);
14885
+ fallback(finalUrl, true);
14763
14886
  return;
14764
14887
  }
14765
14888
  html = await response.text();
14766
14889
  assertActiveNavigation(transaction);
14767
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
14768
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
14769
- }
14770
14890
  }
14771
14891
  // Parse HTML
14772
14892
  const doc = html
14773
14893
  ? parseNavigationDocument(html)
14774
14894
  : document.implementation.createHTMLDocument();
14895
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
14896
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
14897
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
14898
+ context.outcome = 'invalid-response';
14899
+ fallback(response?.url || finalUrl, true);
14900
+ return;
14901
+ }
14902
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
14903
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
14904
+ }
14905
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
14906
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
14907
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
14775
14908
  // Pick source fragment
14776
14909
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
14777
14910
  stripInertFallbackContent(src);
@@ -14783,15 +14916,18 @@ async function navigate(opts) {
14783
14916
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
14784
14917
  }
14785
14918
  resolveIncomingScriptUrls(doc, targetUrl);
14919
+ context.url = targetUrl;
14786
14920
  if (opts.historyFragment)
14787
14921
  resolveIncomingScriptUrls(src, targetUrl);
14788
14922
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
14789
14923
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
14790
14924
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
14791
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
14925
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
14792
14926
  const performUpdate = async () => {
14793
14927
  assertActiveNavigation(transaction);
14794
14928
  transaction.committing = true;
14929
+ runNavigationHooks(beforeSwap, targetUrl, context);
14930
+ assertActiveNavigation(transaction);
14795
14931
  // Update progress to rand 80 - 90% before swap
14796
14932
  progressBar?.setProgress(Math.random() * 10 + 80);
14797
14933
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -14862,21 +14998,34 @@ async function navigate(opts) {
14862
14998
  beforeScripts: async () => {
14863
14999
  if (!isFullOutletNavigation || currentHead)
14864
15000
  return;
15001
+ if (syncDocumentAttributes) {
15002
+ for (const name of ['lang', 'dir']) {
15003
+ const value = doc.documentElement.getAttribute(name);
15004
+ if (value === null)
15005
+ document.documentElement.removeAttribute(name);
15006
+ else
15007
+ document.documentElement.setAttribute(name, value);
15008
+ }
15009
+ }
14865
15010
  const incomingTitle = doc.querySelector('title');
14866
15011
  if (incomingTitle) {
14867
15012
  document.title = incomingTitle.textContent || document.title;
14868
15013
  }
14869
- await updateHead(doc, transaction.controller.signal);
15014
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
14870
15015
  assertActiveNavigation(transaction);
14871
15016
  },
14872
15017
  onCommitted: (committedTarget, roots) => {
14873
15018
  target = committedTarget;
15019
+ context.target = committedTarget;
15020
+ context.committed = true;
15021
+ progressBar?.reconnect();
14874
15022
  committedRoots = roots;
14875
15023
  }
14876
15024
  });
15025
+ context.committed = true;
14877
15026
  assertActiveNavigation(transaction);
14878
15027
  if (isFullOutletNavigation) {
14879
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
15028
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
14880
15029
  assertActiveNavigation(transaction);
14881
15030
  }
14882
15031
  }
@@ -14910,14 +15059,15 @@ async function navigate(opts) {
14910
15059
  await performUpdate();
14911
15060
  }
14912
15061
  assertActiveNavigation(transaction);
14913
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
15062
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
14914
15063
  disposeEffects(opts.trigger);
14915
15064
  opts.trigger.remove();
14916
15065
  }
14917
15066
  if (hasTargetSpinner)
14918
15067
  hideTargetSpinner(transaction.spinner);
14919
15068
  transaction.spinner = null;
14920
- runNavigationHooks(afterNavigate, targetUrl);
15069
+ context.outcome ?? (context.outcome = 'success');
15070
+ runNavigationHooks(afterNavigate, targetUrl, context);
14921
15071
  log('[GyosRouter] navigated to', targetUrl);
14922
15072
  currentUrl = changesState
14923
15073
  ? canonicalUrl(targetUrl, true)
@@ -14933,11 +15083,15 @@ async function navigate(opts) {
14933
15083
  return;
14934
15084
  }
14935
15085
  if (isActiveNavigation(transaction)) {
15086
+ context.outcome ?? (context.outcome = 'error');
14936
15087
  console.error('[GyosRouter] navigation error', error);
14937
- fallbackFromBoost(opts, opts.url, true);
15088
+ fallback(opts.url, true);
14938
15089
  }
14939
15090
  }
14940
15091
  finally {
15092
+ if (transaction.controller.signal.aborted)
15093
+ context.outcome = 'aborted';
15094
+ context.outcome ?? (context.outcome = 'aborted');
14941
15095
  if (transaction.interval)
14942
15096
  clearInterval(transaction.interval);
14943
15097
  if (transaction.spinner)
@@ -14947,6 +15101,15 @@ async function navigate(opts) {
14947
15101
  progressBar?.complete();
14948
15102
  }
14949
15103
  transaction.resolveDone();
15104
+ if (formEvent)
15105
+ submittingForms.delete(formEvent.form);
15106
+ runNavigationHooks(navigationEnd, context.url, context);
15107
+ if (formEvent) {
15108
+ const { url, status, outcome, committed, fallback } = context;
15109
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
15110
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
15111
+ }));
15112
+ }
14950
15113
  }
14951
15114
  }
14952
15115
  function shouldBoost(el) {
@@ -15055,16 +15218,34 @@ function onSubmit(event) {
15055
15218
  return;
15056
15219
  if (shouldDeferToFormValidation(form))
15057
15220
  return;
15058
- event.preventDefault();
15059
- const action = form.action || window.location.href;
15060
- const method = (form.method || 'GET').toUpperCase();
15061
- const url = new URL(action, window.location.href);
15062
- if (url.origin !== window.location.origin) {
15063
- window.location.href = url.toString();
15221
+ const submitter = event.submitter;
15222
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
15223
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
15224
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
15225
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
15226
+ const formEncoding = override('enctype')?.toLowerCase();
15227
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
15228
+ return;
15229
+ if (!resolveTarget(form))
15230
+ return;
15231
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
15232
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
15233
+ return;
15234
+ let url;
15235
+ try {
15236
+ url = new URL(override('action') || window.location.href, document.baseURI);
15237
+ }
15238
+ catch {
15064
15239
  return;
15065
15240
  }
15066
- const formData = new FormData(form);
15067
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
15241
+ if (url.origin !== window.location.origin)
15242
+ return;
15243
+ event.preventDefault();
15244
+ if (submittingForms.has(form))
15245
+ return;
15246
+ const formData = new FormData(form, submitter);
15247
+ submittingForms.add(form);
15248
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15068
15249
  }
15069
15250
  function onPopState(event) {
15070
15251
  const url = window.location.href;
@@ -15169,13 +15350,15 @@ const Gyos = {
15169
15350
  startRouter,
15170
15351
  onBeforeNavigate,
15171
15352
  onAfterNavigate,
15353
+ onBeforeSwap,
15354
+ onNavigationEnd,
15172
15355
  portalCreate,
15173
15356
  portalDestroy,
15174
15357
  setCspNonce,
15175
- version: '0.3.1'
15358
+ version: '0.4.0'
15176
15359
  };
15177
15360
 
15178
15361
  setExpressionRuntime(cspExpressionRuntime);
15179
15362
 
15180
- export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
15363
+ export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, onBeforeSwap, onNavigationEnd, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
15181
15364
  //# sourceMappingURL=gyos.csp.esm.js.map