gyosjs 0.3.0 → 0.3.2

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.0
2
+ * GyosJS v0.3.2
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -2300,32 +2300,24 @@
2300
2300
  * Handles:
2301
2301
  * 1. Literal string: "fade" or "slide-down"
2302
2302
  * 2. Expression with {}: "{transition}"
2303
- * 3. Expression without {}: "transition" (evaluate as variable)
2303
+ * 3. Quoted literal kept for backwards compatibility: "'fade'"
2304
2304
  *
2305
2305
  * @param attrValue - The g-transition attribute value
2306
2306
  * @param scope - Current scope for expression evaluation
2307
2307
  * @returns The transition name (string)
2308
2308
  */
2309
2309
  function parseTransitionName(attrValue, scope) {
2310
- if (attrValue.includes('{') && attrValue.includes('}')) {
2311
- // Extract expression from {} and evaluate it
2312
- const match = attrValue.match(/\{([^}]+)\}/);
2313
- if (match) {
2314
- return evaluateExpression(match[1].trim(), scope);
2315
- }
2316
- }
2317
- // Try to evaluate as expression first (variable name)
2318
- // If it fails or returns undefined, use as literal string
2319
- try {
2320
- const evaluated = evaluateExpression(attrValue, scope);
2321
- if (evaluated !== undefined && evaluated !== null) {
2322
- return evaluated;
2323
- }
2310
+ const value = attrValue.trim();
2311
+ const expression = /^\{([\s\S]+)\}$/.exec(value);
2312
+ if (expression) {
2313
+ const evaluated = evaluateExpression(expression[1].trim(), scope);
2314
+ return evaluated == null ? '' : String(evaluated);
2324
2315
  }
2325
- catch (e) {
2326
- // If evaluation fails, use value as literal string (built-in transition name)
2316
+ if (value.length >= 2 && ((value.startsWith("'") && value.endsWith("'"))
2317
+ || (value.startsWith('"') && value.endsWith('"')))) {
2318
+ return value.slice(1, -1);
2327
2319
  }
2328
- return attrValue;
2320
+ return value;
2329
2321
  }
2330
2322
  /**
2331
2323
  * Parse transition config from element's g-transition attribute
@@ -5229,6 +5221,10 @@
5229
5221
  const structuralElements = [];
5230
5222
  const root = elements[0];
5231
5223
  elements.forEach(el => {
5224
+ // Await branches are detached and parsed only after their alias scope exists.
5225
+ // Do not evaluate nested structural expressions during the parent scan.
5226
+ if (isAwaitBranchDescendant(el))
5227
+ return;
5232
5228
  const hasIf = el.hasAttribute('*if');
5233
5229
  const hasFor = el.hasAttribute('*for');
5234
5230
  const hasSwitch = el.hasAttribute('*switch');
@@ -5273,6 +5269,20 @@
5273
5269
  }
5274
5270
  });
5275
5271
  }
5272
+ function isAwaitBranchDescendant(element) {
5273
+ let child = element;
5274
+ let parent = element.parentElement;
5275
+ while (parent && parent !== document.body) {
5276
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5277
+ child.hasAttribute('*then') ||
5278
+ child.hasAttribute('*catch'))) {
5279
+ return true;
5280
+ }
5281
+ child = parent;
5282
+ parent = parent.parentElement;
5283
+ }
5284
+ return false;
5285
+ }
5276
5286
  const elementBelongsToAnotherScope = (el, scope) => {
5277
5287
  const owner = getScopeFromElement(el);
5278
5288
  return Boolean(owner && owner !== scope);
@@ -6794,7 +6804,7 @@
6794
6804
  }
6795
6805
 
6796
6806
  let nonceSource;
6797
- /** Configure the nonce used when Gyos recreates scripts during MPA navigation. */
6807
+ /** Configure the active document nonce used for scripts and styles during MPA navigation. */
6798
6808
  function setCspNonce(source) {
6799
6809
  nonceSource = source;
6800
6810
  }
@@ -7366,9 +7376,33 @@
7366
7376
  window.scrollTo({ top: 0, behavior: 'smooth' });
7367
7377
  }
7368
7378
 
7369
- function serializeAttributes(el) {
7370
- return Array.from(el.attributes)
7371
- .map(attr => `${attr.name}=${attr.value}`)
7379
+ function isNonceMeta(el) {
7380
+ return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7381
+ }
7382
+ function isStylesheetLink(el) {
7383
+ return el.tagName === 'LINK'
7384
+ && (el.getAttribute('rel') || '').toLowerCase().split(/\s+/).includes('stylesheet');
7385
+ }
7386
+ function usesCspNonce(el) {
7387
+ return el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || isStylesheetLink(el);
7388
+ }
7389
+ function serializeAttributes(el, context) {
7390
+ const attributes = new Map();
7391
+ Array.from(el.attributes).forEach(attr => {
7392
+ if (context.csp && usesCspNonce(el) && attr.name.toLowerCase() === 'nonce')
7393
+ return;
7394
+ if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7395
+ return;
7396
+ attributes.set(attr.name, attr.value);
7397
+ });
7398
+ if (context.csp && usesCspNonce(el) && context.activeNonce) {
7399
+ attributes.set('nonce', context.activeNonce);
7400
+ }
7401
+ if (context.csp && isNonceMeta(el) && context.activeNonce) {
7402
+ attributes.set('content', context.activeNonce);
7403
+ }
7404
+ return Array.from(attributes)
7405
+ .map(([name, value]) => `${name}=${value}`)
7372
7406
  .sort()
7373
7407
  .join('|');
7374
7408
  }
@@ -7379,23 +7413,61 @@
7379
7413
  }
7380
7414
  return String(hash);
7381
7415
  }
7382
- function elementKey(el) {
7416
+ function elementKey(el, context) {
7383
7417
  const tag = el.tagName.toLowerCase();
7384
7418
  const content = tag === 'script' || tag === 'style' ? hashContent(el.textContent || '') : '';
7385
- return `${tag}|${serializeAttributes(el)}|${content}`;
7419
+ return `${tag}|${serializeAttributes(el, context)}|${content}`;
7386
7420
  }
7387
- function keyedNodes(nodes) {
7421
+ function keyedNodes(nodes, context) {
7388
7422
  const occurrences = new Map();
7389
7423
  return nodes.map(node => {
7390
- const baseKey = elementKey(node);
7424
+ const baseKey = elementKey(node, context);
7391
7425
  const occurrence = occurrences.get(baseKey) || 0;
7392
7426
  occurrences.set(baseKey, occurrence + 1);
7393
7427
  return { key: `${baseKey}|${occurrence}`, node };
7394
7428
  });
7395
7429
  }
7430
+ function canInsertNode(node, context) {
7431
+ if (!context.csp)
7432
+ return true;
7433
+ if (isNonceMeta(node))
7434
+ return Boolean(context.activeNonce);
7435
+ if (node.tagName === 'STYLE')
7436
+ return Boolean(context.activeNonce);
7437
+ if (node.tagName === 'SCRIPT' && !node.hasAttribute('src'))
7438
+ return Boolean(context.activeNonce);
7439
+ return true;
7440
+ }
7441
+ function reconcileCspAttributes(node, context) {
7442
+ if (!context.csp)
7443
+ return;
7444
+ if (isNonceMeta(node)) {
7445
+ if (context.activeNonce)
7446
+ node.setAttribute('content', context.activeNonce);
7447
+ return;
7448
+ }
7449
+ if (!usesCspNonce(node))
7450
+ return;
7451
+ node.removeAttribute('nonce');
7452
+ if (context.activeNonce)
7453
+ node.setAttribute('nonce', context.activeNonce);
7454
+ }
7455
+ function warnSkippedNode(node) {
7456
+ if (node.tagName === 'STYLE') {
7457
+ console.warn('[GyosJS CSP] Skipped an inline MPA style because no active document nonce is configured.');
7458
+ }
7459
+ else if (node.tagName === 'SCRIPT' && !node.hasAttribute('src')) {
7460
+ console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7461
+ }
7462
+ }
7396
7463
  async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7397
- const current = keyedNodes(currentNodes);
7398
- const next = keyedNodes(nextNodes);
7464
+ const csp = expressionRuntimeMode() === 'csp';
7465
+ const context = {
7466
+ csp,
7467
+ activeNonce: csp ? resolveCspNonce() : undefined
7468
+ };
7469
+ const current = keyedNodes(currentNodes, context);
7470
+ const next = keyedNodes(nextNodes, context);
7399
7471
  const currentKeys = new Set(current.map(item => item.key));
7400
7472
  const nextKeys = new Set(next.map(item => item.key));
7401
7473
  // Remove nodes that are not in the new head
@@ -7409,6 +7481,20 @@
7409
7481
  if (signal?.aborted)
7410
7482
  return;
7411
7483
  if (!currentKeys.has(key)) {
7484
+ if (!canInsertNode(node, context)) {
7485
+ warnSkippedNode(node);
7486
+ continue;
7487
+ }
7488
+ if (node.tagName === 'STYLE') {
7489
+ const style = document.createElement('style');
7490
+ Array.from(node.attributes).forEach(attr => style.setAttribute(attr.name, attr.value));
7491
+ reconcileCspAttributes(style, context);
7492
+ // CSP checks inline styles as their CSS text is attached. Set the active
7493
+ // nonce first so a response nonce never produces a transient violation.
7494
+ style.textContent = node.textContent || '';
7495
+ container.appendChild(style);
7496
+ continue;
7497
+ }
7412
7498
  if (node.tagName === 'SCRIPT') {
7413
7499
  const originalScript = node;
7414
7500
  const executionKey = getScriptExecutionKey(originalScript);
@@ -7419,6 +7505,7 @@
7419
7505
  }
7420
7506
  const script = document.createElement('script');
7421
7507
  Array.from(node.attributes).forEach(attr => script.setAttribute(attr.name, attr.value));
7508
+ reconcileCspAttributes(script, context);
7422
7509
  script.textContent = node.hasAttribute('g-script-wrap')
7423
7510
  ? wrapScriptExecution(node.textContent || '')
7424
7511
  : node.textContent || '';
@@ -7428,9 +7515,166 @@
7428
7515
  await completion;
7429
7516
  continue;
7430
7517
  }
7431
- container.appendChild(document.importNode(node, true));
7518
+ const imported = document.importNode(node, true);
7519
+ reconcileCspAttributes(imported, context);
7520
+ container.appendChild(imported);
7521
+ }
7522
+ }
7523
+ }
7524
+
7525
+ const RAW_TEXT_ELEMENTS = new Set(['iframe', 'noembed', 'noframes', 'plaintext', 'script', 'textarea', 'title', 'xmp']);
7526
+ function escapeAttribute(value) {
7527
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
7528
+ }
7529
+ function findTagEnd(html, start) {
7530
+ let quote = '';
7531
+ for (let index = start; index < html.length; index += 1) {
7532
+ const character = html[index];
7533
+ if (quote) {
7534
+ if (character === quote)
7535
+ quote = '';
7536
+ continue;
7537
+ }
7538
+ if (character === '"' || character === "'") {
7539
+ quote = character;
7540
+ continue;
7541
+ }
7542
+ if (character === '>')
7543
+ return index + 1;
7544
+ }
7545
+ return html.length;
7546
+ }
7547
+ function findClosingTag(html, lowerHtml, name, start) {
7548
+ const needle = `</${name}`;
7549
+ let position = lowerHtml.indexOf(needle, start);
7550
+ while (position !== -1) {
7551
+ const boundary = lowerHtml[position + needle.length];
7552
+ if (boundary === '>' || /\s/.test(boundary || '')) {
7553
+ return {
7554
+ start: position,
7555
+ end: findTagEnd(html, position + needle.length)
7556
+ };
7557
+ }
7558
+ position = lowerHtml.indexOf(needle, position + needle.length);
7559
+ }
7560
+ return null;
7561
+ }
7562
+ function removeNonceAttribute(openingTag) {
7563
+ const prefix = /^<\s*style\b/i.exec(openingTag);
7564
+ if (!prefix)
7565
+ return openingTag;
7566
+ let output = prefix[0];
7567
+ let cursor = prefix[0].length;
7568
+ const limit = openingTag.length - 1;
7569
+ while (cursor < limit) {
7570
+ const attributeStart = cursor;
7571
+ while (cursor < limit && /\s/.test(openingTag[cursor]))
7572
+ cursor += 1;
7573
+ if (cursor >= limit || openingTag[cursor] === '>') {
7574
+ output += openingTag.slice(attributeStart, cursor);
7575
+ break;
7576
+ }
7577
+ const nameStart = cursor;
7578
+ while (cursor < limit && !/[\s=/>]/.test(openingTag[cursor]))
7579
+ cursor += 1;
7580
+ if (cursor === nameStart) {
7581
+ output += openingTag.slice(attributeStart, cursor + 1);
7582
+ cursor += 1;
7583
+ continue;
7584
+ }
7585
+ const name = openingTag.slice(nameStart, cursor).toLowerCase();
7586
+ while (cursor < limit && /\s/.test(openingTag[cursor]))
7587
+ cursor += 1;
7588
+ if (openingTag[cursor] === '=') {
7589
+ cursor += 1;
7590
+ while (cursor < limit && /\s/.test(openingTag[cursor]))
7591
+ cursor += 1;
7592
+ const quote = openingTag[cursor] === '"' || openingTag[cursor] === "'" ? openingTag[cursor] : '';
7593
+ if (quote) {
7594
+ cursor += 1;
7595
+ while (cursor < limit && openingTag[cursor] !== quote)
7596
+ cursor += 1;
7597
+ if (openingTag[cursor] === quote)
7598
+ cursor += 1;
7599
+ }
7600
+ else {
7601
+ while (cursor < limit && !/[\s>]/.test(openingTag[cursor]))
7602
+ cursor += 1;
7603
+ }
7604
+ }
7605
+ if (name !== 'nonce')
7606
+ output += openingTag.slice(attributeStart, cursor);
7607
+ }
7608
+ return output + openingTag.slice(limit);
7609
+ }
7610
+ function withNonce(openingTag, nonce) {
7611
+ const withoutNonce = removeNonceAttribute(openingTag);
7612
+ return `${withoutNonce.slice(0, -1)} nonce="${escapeAttribute(nonce)}">`;
7613
+ }
7614
+ function prepareNavigationHtml(html) {
7615
+ if (expressionRuntimeMode() !== 'csp')
7616
+ return html;
7617
+ const activeNonce = resolveCspNonce();
7618
+ const lowerHtml = html.toLowerCase();
7619
+ let output = '';
7620
+ let cursor = 0;
7621
+ let skippedStyles = 0;
7622
+ while (cursor < html.length) {
7623
+ const tagStart = html.indexOf('<', cursor);
7624
+ if (tagStart === -1) {
7625
+ output += html.slice(cursor);
7626
+ break;
7627
+ }
7628
+ output += html.slice(cursor, tagStart);
7629
+ if (html.startsWith('<!--', tagStart)) {
7630
+ const commentEnd = html.indexOf('-->', tagStart + 4);
7631
+ const end = commentEnd === -1 ? html.length : commentEnd + 3;
7632
+ output += html.slice(tagStart, end);
7633
+ cursor = end;
7634
+ continue;
7635
+ }
7636
+ const tagEnd = findTagEnd(html, tagStart + 1);
7637
+ const openingTag = html.slice(tagStart, tagEnd);
7638
+ const match = /^<\s*(\/?)\s*([a-z][\w:-]*)/i.exec(openingTag);
7639
+ if (!match || match[1]) {
7640
+ output += openingTag;
7641
+ cursor = tagEnd;
7642
+ continue;
7643
+ }
7644
+ const name = match[2].toLowerCase();
7645
+ if (name === 'plaintext') {
7646
+ output += html.slice(tagStart);
7647
+ break;
7648
+ }
7649
+ if (name === 'style' || name === 'noscript' || RAW_TEXT_ELEMENTS.has(name)) {
7650
+ const closingTag = findClosingTag(html, lowerHtml, name, tagEnd);
7651
+ const blockEnd = closingTag?.end ?? html.length;
7652
+ if (name === 'noscript') {
7653
+ cursor = blockEnd;
7654
+ continue;
7655
+ }
7656
+ if (name === 'style') {
7657
+ if (!activeNonce) {
7658
+ skippedStyles += 1;
7659
+ cursor = blockEnd;
7660
+ continue;
7661
+ }
7662
+ output += withNonce(openingTag, activeNonce);
7663
+ output += html.slice(tagEnd, blockEnd);
7664
+ cursor = blockEnd;
7665
+ continue;
7666
+ }
7667
+ output += html.slice(tagStart, blockEnd);
7668
+ cursor = blockEnd;
7669
+ continue;
7432
7670
  }
7671
+ output += openingTag;
7672
+ cursor = tagEnd;
7673
+ }
7674
+ if (skippedStyles > 0) {
7675
+ console.warn(`[GyosJS CSP] Skipped ${skippedStyles} inline MPA style${skippedStyles === 1 ? '' : 's'} because no active document nonce is configured.`);
7433
7676
  }
7677
+ return output;
7434
7678
  }
7435
7679
 
7436
7680
  /**
@@ -7496,7 +7740,10 @@
7496
7740
  root.querySelectorAll('noscript').forEach(element => element.remove());
7497
7741
  }
7498
7742
  function parseNavigationDocument(html) {
7499
- const doc = new DOMParser().parseFromString(html, 'text/html');
7743
+ // Chromium applies the active page CSP while DOMParser creates response
7744
+ // styles. Reconcile their nonce before parsing to avoid transient violations;
7745
+ // diffNodes repeats the check before insertion into the live document.
7746
+ const doc = new DOMParser().parseFromString(prepareNavigationHtml(html), 'text/html');
7500
7747
  // DOMParser disables scripting and parses noscript children as active markup.
7501
7748
  // A boosted page runs with scripting enabled, so those fallbacks must stay inert.
7502
7749
  stripInertFallbackContent(doc);
@@ -8332,7 +8579,7 @@
8332
8579
  portalCreate,
8333
8580
  portalDestroy,
8334
8581
  setCspNonce,
8335
- version: '0.3.0'
8582
+ version: '0.3.2'
8336
8583
  };
8337
8584
 
8338
8585
  setExpressionRuntime(standardExpressionRuntime);