@nac3/runtime 2.4.0 → 2.5.0-alpha.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.
@@ -323,6 +323,791 @@
323
323
  return e;
324
324
  }
325
325
 
326
+ /* ================================================================
327
+ v2.5 / RFC V24-01: Plugin slug uniqueness gate (spec sec 7.4)
328
+ ================================================================
329
+
330
+ When a plugin slug appears on more than one DOM root
331
+ simultaneously, every root MUST carry a unique
332
+ data-nac-plugin-id attribute. The runtime enforces via three
333
+ mechanisms:
334
+
335
+ NAC.register -> synchronous throw on the registered slug
336
+ boot-time pass -> nac:fatal + visible red banner at first
337
+ cross-slug violation, then refuse further
338
+ dispatches
339
+ validate_global -> structured finding for CI (non-fatal)
340
+
341
+ Gated by NAC.HARD_DEDUP (default true; set false for migration). */
342
+
343
+ /* _scanPluginInstances() walks the live DOM and groups every
344
+ [data-nac-plugin] root by its slug. For each group of >1 root,
345
+ it requires every root to carry a non-empty data-nac-plugin-id
346
+ AND for those ids to be pairwise unique. Returns a structured
347
+ findings array; never throws. */
348
+ function _scanPluginInstances() {
349
+ if (typeof document === 'undefined') return [];
350
+ const findings = [];
351
+ const bySlug = {};
352
+ const all = document.querySelectorAll('[data-nac-plugin]');
353
+ for (let i = 0; i < all.length; i++) {
354
+ const el = all[i];
355
+ const slug = el.getAttribute('data-nac-plugin') || '';
356
+ if (!slug) continue;
357
+ (bySlug[slug] = bySlug[slug] || []).push(el);
358
+ }
359
+ for (const slug in bySlug) {
360
+ if (!Object.prototype.hasOwnProperty.call(bySlug, slug)) continue;
361
+ const roots = bySlug[slug];
362
+ if (roots.length < 2) continue;
363
+ const ids = [];
364
+ const missing = [];
365
+ for (let r = 0; r < roots.length; r++) {
366
+ const id = roots[r].getAttribute('data-nac-plugin-id') || '';
367
+ if (!id) missing.push(roots[r]); else ids.push(id);
368
+ }
369
+ const dupIds = [];
370
+ const seen = {};
371
+ for (let j = 0; j < ids.length; j++) {
372
+ if (seen[ids[j]]) dupIds.push(ids[j]);
373
+ else seen[ids[j]] = 1;
374
+ }
375
+ if (missing.length > 0 || dupIds.length > 0) {
376
+ findings.push({
377
+ code: 'duplicate_plugin_no_instance_id',
378
+ severity: 'error',
379
+ slug: slug,
380
+ instance_count: roots.length,
381
+ missing_instance_id_count: missing.length,
382
+ duplicate_instance_ids: dupIds,
383
+ message: roots.length + ' DOM roots carry data-nac-plugin="'
384
+ + slug + '" but '
385
+ + (missing.length
386
+ ? missing.length + ' lack data-nac-plugin-id'
387
+ : 'two share data-nac-plugin-id "' + dupIds[0] + '"')
388
+ + '. Per SPEC sec 7.4, every root sharing a slug MUST '
389
+ + 'carry a unique data-nac-plugin-id.',
390
+ });
391
+ }
392
+ }
393
+ return findings;
394
+ }
395
+
396
+ /* _checkPluginSlugUniqueOrThrow(slug) is the synchronous gate used
397
+ by NAC.register(). Throws the first finding for the registered
398
+ slug; other-slug findings are ignored here -- the DOM-ready pass
399
+ below catches them globally. */
400
+ function _checkPluginSlugUniqueOrThrow(slug) {
401
+ const all = _scanPluginInstances();
402
+ for (let i = 0; i < all.length; i++) {
403
+ if (all[i].slug !== slug) continue;
404
+ throw NacError('duplicate_plugin_no_instance_id', all[i].message, {
405
+ slug: slug,
406
+ instance_count: all[i].instance_count,
407
+ missing_instance_id_count: all[i].missing_instance_id_count,
408
+ duplicate_instance_ids: all[i].duplicate_instance_ids,
409
+ });
410
+ }
411
+ }
412
+
413
+ /* _installPluginDedupBootGate() runs once at DOMContentLoaded and
414
+ enforces the same contract across every slug. On first violation
415
+ it dispatches nac:fatal, paints a red banner, and re-throws
416
+ asynchronously so test harnesses + browsers catch the error
417
+ instead of silently swallowing. */
418
+ let _bootDedupFatal = null;
419
+ function _installPluginDedupBootGate() {
420
+ if (typeof document === 'undefined') return;
421
+ const run = function () {
422
+ if (typeof global !== 'undefined' && global.NAC &&
423
+ global.NAC.HARD_DEDUP === false) return;
424
+ if (typeof window !== 'undefined' && window.NAC &&
425
+ window.NAC.HARD_DEDUP === false) return;
426
+ const findings = _scanPluginInstances();
427
+ if (findings.length === 0) return;
428
+ const f = findings[0];
429
+ const err = NacError('duplicate_plugin_no_instance_id', f.message, {
430
+ slug: f.slug,
431
+ instance_count: f.instance_count,
432
+ missing_instance_id_count: f.missing_instance_id_count,
433
+ duplicate_instance_ids: f.duplicate_instance_ids,
434
+ all_findings: findings,
435
+ });
436
+ _bootDedupFatal = err;
437
+ try {
438
+ document.dispatchEvent(new CustomEvent('nac:fatal', {
439
+ detail: { code: 'duplicate_plugin_no_instance_id',
440
+ slug: f.slug, message: f.message,
441
+ findings: findings },
442
+ }));
443
+ } catch (_) {}
444
+ try { _paintFatalBanner(err); } catch (_) {}
445
+ setTimeout(function () { throw err; }, 0);
446
+ };
447
+ if (document.readyState === 'loading') {
448
+ document.addEventListener('DOMContentLoaded', run, { once: true });
449
+ } else {
450
+ run();
451
+ }
452
+ }
453
+
454
+ function _paintFatalBanner(err) {
455
+ if (typeof document === 'undefined' || !document.body) return;
456
+ if (document.getElementById('__nac_fatal_banner__')) return;
457
+ const div = document.createElement('div');
458
+ div.id = '__nac_fatal_banner__';
459
+ div.setAttribute('role', 'alert');
460
+ div.style = 'position:fixed;top:0;left:0;right:0;z-index:2147483647;'
461
+ + 'background:#DC2626;color:#fff;font:600 14px/1.4 system-ui,sans-serif;'
462
+ + 'padding:12px 16px;box-shadow:0 2px 8px rgba(0,0,0,.25);';
463
+ div.textContent = '[NAC3 FATAL] ' + err.code + ': ' + err.message;
464
+ if (document.body.firstChild) {
465
+ document.body.insertBefore(div, document.body.firstChild);
466
+ } else {
467
+ document.body.appendChild(div);
468
+ }
469
+ }
470
+ /* /end V24-01 */
471
+
472
+ /* ==================================================================
473
+ v2.4 / RFC V24-04: Snapshot versioning + optimistic concurrency
474
+ ==================================================================
475
+
476
+ Promotes NAC3 from a decoration-and-verb contract to a real
477
+ agentic concurrency protocol. See docs/RFC_V24-04.md for the
478
+ full design + Appendix C for agent best practices. Three
479
+ primitives, in order an agent should typically use them:
480
+
481
+ plugin_version primary; per-plugin monotonic; ignores noise
482
+ outside the targeted plugin.
483
+ element_state_hash content-aware; 128-bit SHA-256 truncated.
484
+ tree_version escape hatch; global monotonic.
485
+
486
+ All three are returned by describe(); all three are honored as
487
+ expected_* parameters on every mutating API; mismatches reject
488
+ with NacError('snapshot_stale', { reason, ... }) and the side
489
+ effect does not occur.
490
+ */
491
+
492
+ /* ---- Internal state ---- */
493
+
494
+ let _tree_version = 0;
495
+ const _plugin_versions = new Map(); /* key: `${slug}|${instance_id||''}` */
496
+ const _version_history = []; /* circular buffer, max 500 */
497
+ const _plugin_scope_cache = (typeof WeakMap !== 'undefined')
498
+ ? new WeakMap() /* Element -> { slug, instance_id } */
499
+ : null;
500
+ let _hydration_complete = false;
501
+ let _hydration_fallback_timer = null;
502
+ let _mutation_observer = null;
503
+
504
+ /* STRICT_VERSIONING + eager_hashing + HARD_DEDUP are exposed via
505
+ the NAC export (bottom of the module) so hosts can flip them
506
+ before / after install. Internal mirrors keep hot-path checks
507
+ property-access-free in the most common cases. */
508
+ function _strictVersioningOn() {
509
+ return (typeof window !== 'undefined' && window.NAC &&
510
+ window.NAC.STRICT_VERSIONING === true);
511
+ }
512
+ function _eagerHashingOn() {
513
+ return (typeof window !== 'undefined' && window.NAC &&
514
+ window.NAC.eager_hashing === true);
515
+ }
516
+
517
+ /* ---- Plugin scope resolver (RFC sec 5.1.1) ----
518
+
519
+ "Plugin scope is logical, not physical." An element belongs to
520
+ the plugin declared by its nearest [data-nac-plugin] ancestor.
521
+ Portals/teleports that carry the attribute on their portaled
522
+ root inherit the right scope regardless of DOM hierarchy.
523
+
524
+ Cached per element via WeakMap to avoid O(depth) walks on every
525
+ mutation in high-rate paths (drag-drop, autocomplete filtering).
526
+ Cache entries invalidate naturally when the element is GC'd; we
527
+ also clear them on attribute mutations of data-nac-plugin* in
528
+ the observer below. */
529
+ function _resolvePluginScope(el) {
530
+ if (!el || el.nodeType !== 1) return null;
531
+ if (_plugin_scope_cache && _plugin_scope_cache.has(el)) {
532
+ return _plugin_scope_cache.get(el);
533
+ }
534
+ let cur = el;
535
+ while (cur && cur.nodeType === 1) {
536
+ if (cur.hasAttribute && cur.hasAttribute('data-nac-plugin')) {
537
+ const scope = {
538
+ slug: cur.getAttribute('data-nac-plugin') || '',
539
+ instance_id: cur.getAttribute('data-nac-plugin-id') || null,
540
+ };
541
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, scope);
542
+ return scope;
543
+ }
544
+ cur = cur.parentElement;
545
+ }
546
+ if (_plugin_scope_cache) _plugin_scope_cache.set(el, null);
547
+ return null;
548
+ }
549
+
550
+ function _pluginKey(slug, instance_id) {
551
+ return slug + '|' + (instance_id || '');
552
+ }
553
+ function _pluginVersionFor(slug, instance_id) {
554
+ return 'v_' + (_plugin_versions.get(_pluginKey(slug, instance_id)) || 0);
555
+ }
556
+ function _treeVersionStr() { return 'v_' + _tree_version; }
557
+
558
+ /* ---- Bump functions (RFC sec 8.1) ---- */
559
+
560
+ function _bumpTreeVersion(trigger, affected_plugins) {
561
+ _tree_version += 1;
562
+ _version_history.push({
563
+ at: Date.now(),
564
+ tree_version: _treeVersionStr(),
565
+ trigger: trigger,
566
+ affected_plugins: affected_plugins || [],
567
+ });
568
+ while (_version_history.length > 500) _version_history.shift();
569
+ if (typeof document !== 'undefined') {
570
+ document.dispatchEvent(new CustomEvent('nac:tree:invalidated', {
571
+ detail: {
572
+ from_version: 'v_' + (_tree_version - 1),
573
+ to_version: _treeVersionStr(),
574
+ trigger: trigger,
575
+ affected_plugins: affected_plugins || [],
576
+ },
577
+ }));
578
+ }
579
+ }
580
+
581
+ function _bumpPluginVersion(slug, instance_id, trigger) {
582
+ if (!slug) return;
583
+ const key = _pluginKey(slug, instance_id);
584
+ const prev = _plugin_versions.get(key) || 0;
585
+ const next = prev + 1;
586
+ _plugin_versions.set(key, next);
587
+ /* Tree version bumps along with every plugin version bump. */
588
+ _bumpTreeVersion(trigger, [{ slug: slug, instance_id: instance_id || null }]);
589
+ if (typeof document !== 'undefined') {
590
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
591
+ detail: {
592
+ plugin_slug: slug,
593
+ plugin_instance_id: instance_id || null,
594
+ from_version: 'v_' + prev,
595
+ to_version: 'v_' + next,
596
+ trigger: trigger,
597
+ },
598
+ }));
599
+ }
600
+ }
601
+
602
+ /* Helper invoked from data-table primitives + syncPlugin to bump
603
+ versions without needing a mutation observer round-trip. */
604
+ function _markStructuralChange(slug, instance_id, trigger) {
605
+ _bumpPluginVersion(slug, instance_id, trigger || 'syncPlugin');
606
+ }
607
+
608
+ /* ---- Mutation observer (RFC sec 8.2) ----
609
+
610
+ Single observer rooted at document.body, filters mutations to
611
+ elements inside any [data-nac-plugin] subtree, coalesces all
612
+ mutations in a single microtask into one bump per affected
613
+ plugin. Structural changes (add/remove [data-nac-*] elements,
614
+ attribute changes to data-nac-id/role/action/plugin*, visibility
615
+ transitions) bump; pure state changes (value/textContent/focus)
616
+ do not. */
617
+ const _NAC_ATTRS_STRUCTURAL = new Set([
618
+ 'data-nac-id', 'data-nac-role', 'data-nac-action',
619
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
620
+ 'aria-hidden', 'hidden', 'style',
621
+ ]);
622
+
623
+ function _scopeOfMutation(mutation) {
624
+ /* attributes: target is the element itself.
625
+ childList: walk added/removed nodes; each contributes a scope. */
626
+ const scopes = [];
627
+ if (mutation.type === 'attributes' && mutation.target) {
628
+ const s = _resolvePluginScope(mutation.target);
629
+ if (s) scopes.push(s);
630
+ } else if (mutation.type === 'childList') {
631
+ const collect = function (nl) {
632
+ for (let i = 0; i < nl.length; i++) {
633
+ const n = nl[i];
634
+ if (n.nodeType !== 1) continue;
635
+ /* Only nodes that themselves carry a data-nac-* attribute,
636
+ or that contain one, are agent-relevant. */
637
+ let relevant = false;
638
+ if (n.hasAttribute && (n.hasAttribute('data-nac-id') ||
639
+ n.hasAttribute('data-nac-role') ||
640
+ n.hasAttribute('data-nac-plugin'))) {
641
+ relevant = true;
642
+ }
643
+ if (!relevant && n.querySelector) {
644
+ relevant = !!n.querySelector('[data-nac-id],[data-nac-role],[data-nac-plugin]');
645
+ }
646
+ if (relevant) {
647
+ /* Resolve scope from the mutation parent (where the node
648
+ was inserted/removed), since the removed node may no
649
+ longer be in the tree. */
650
+ const s = _resolvePluginScope(mutation.target);
651
+ if (s) scopes.push(s);
652
+ }
653
+ }
654
+ };
655
+ collect(mutation.addedNodes);
656
+ collect(mutation.removedNodes);
657
+ }
658
+ return scopes;
659
+ }
660
+
661
+ function _isStructuralAttrChange(mutation) {
662
+ if (mutation.type !== 'attributes') return false;
663
+ return _NAC_ATTRS_STRUCTURAL.has(mutation.attributeName || '');
664
+ }
665
+
666
+ function _handleMutationRecords(records) {
667
+ /* Coalesce: collect every affected (slug, instance_id) and emit
668
+ exactly one bump per pair per microtask flush. */
669
+ const affected = new Map();
670
+ for (let i = 0; i < records.length; i++) {
671
+ const r = records[i];
672
+ let structural = false;
673
+ if (r.type === 'childList') structural = true;
674
+ else if (r.type === 'attributes' && _isStructuralAttrChange(r)) structural = true;
675
+ else if (r.type === 'attributes' &&
676
+ (r.attributeName === 'data-nac-plugin' ||
677
+ r.attributeName === 'data-nac-plugin-id') &&
678
+ _plugin_scope_cache && r.target) {
679
+ /* Plugin scope changed -- invalidate cache for this element. */
680
+ try { _plugin_scope_cache.delete(r.target); } catch (_) {}
681
+ }
682
+ if (!structural) continue;
683
+ const scopes = _scopeOfMutation(r);
684
+ for (let j = 0; j < scopes.length; j++) {
685
+ const k = _pluginKey(scopes[j].slug, scopes[j].instance_id);
686
+ if (!affected.has(k)) {
687
+ affected.set(k, { slug: scopes[j].slug, instance_id: scopes[j].instance_id });
688
+ }
689
+ }
690
+ }
691
+ if (affected.size === 0) return;
692
+ affected.forEach(function (scope) {
693
+ _bumpPluginVersion(scope.slug, scope.instance_id, 'mutation');
694
+ });
695
+ }
696
+
697
+ function _installMutationObserver() {
698
+ if (_mutation_observer || typeof MutationObserver === 'undefined' ||
699
+ typeof document === 'undefined' || !document.body) return;
700
+ _mutation_observer = new MutationObserver(_handleMutationRecords);
701
+ _mutation_observer.observe(document.body, {
702
+ childList: true,
703
+ subtree: true,
704
+ attributes: true,
705
+ attributeFilter: ['data-nac-id', 'data-nac-role', 'data-nac-action',
706
+ 'data-nac-plugin', 'data-nac-plugin-id', 'data-nac-verb',
707
+ 'data-nac-state', 'aria-hidden', 'hidden', 'disabled',
708
+ 'style'],
709
+ });
710
+ }
711
+
712
+ /* ---- element_state_hash (RFC sec 5.2) ----
713
+
714
+ The hash covers exactly 5 keys (visible, disabled, value, text,
715
+ custom) per the canonical mini-spec. Truncation at 256 chars on
716
+ value+text is normative. Serializer emits keys alphabetically,
717
+ non-ASCII escaped as \uXXXX lowercase, no whitespace. SHA-256
718
+ over the canonical bytes, truncated to the leading 128 bits
719
+ (16 bytes), encoded as 32 lowercase hex chars. */
720
+
721
+ function _hashIsEffectivelyVisible(el) {
722
+ /* Cheap visibility check: offsetParent + style.display +
723
+ style.visibility + aria-hidden. */
724
+ if (!el || el.nodeType !== 1) return false;
725
+ if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
726
+ if (typeof el.offsetParent === 'object' && el.offsetParent === null) {
727
+ /* position:fixed escapes offsetParent=null. Use rect fallback. */
728
+ if (typeof el.getBoundingClientRect === 'function') {
729
+ const r = el.getBoundingClientRect();
730
+ if (r.width === 0 && r.height === 0) return false;
731
+ } else {
732
+ return false;
733
+ }
734
+ }
735
+ if (typeof window !== 'undefined' && window.getComputedStyle) {
736
+ const cs = window.getComputedStyle(el);
737
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return false;
738
+ }
739
+ return true;
740
+ }
741
+
742
+ function _hashReadValue(el) {
743
+ if (!el || el.nodeType !== 1) return null;
744
+ const tag = (el.tagName || '').toLowerCase();
745
+ if (tag === 'input' || tag === 'textarea') {
746
+ const t = (el.type || '').toLowerCase();
747
+ if (t === 'checkbox' || t === 'radio') return el.checked ? 'true' : 'false';
748
+ return el.value == null ? null : String(el.value).slice(0, 256);
749
+ }
750
+ if (tag === 'select') {
751
+ return el.value == null ? null : String(el.value).slice(0, 256);
752
+ }
753
+ /* role=option fallback: aria-selected. */
754
+ if (el.getAttribute && el.getAttribute('aria-selected') === 'true') return 'selected';
755
+ return null;
756
+ }
757
+
758
+ function _jsonStringCanonical(s) {
759
+ /* RFC 8259 string encoding + the V24-04 normative rule: non-ASCII
760
+ escaped as \uXXXX lowercase. Eliminates engine divergence. */
761
+ let out = '"';
762
+ for (let i = 0; i < s.length; i++) {
763
+ const c = s.charCodeAt(i);
764
+ if (c === 0x22) out += '\\"';
765
+ else if (c === 0x5C) out += '\\\\';
766
+ else if (c === 0x08) out += '\\b';
767
+ else if (c === 0x0C) out += '\\f';
768
+ else if (c === 0x0A) out += '\\n';
769
+ else if (c === 0x0D) out += '\\r';
770
+ else if (c === 0x09) out += '\\t';
771
+ else if (c < 0x20 || c > 0x7E) {
772
+ let hex = c.toString(16);
773
+ while (hex.length < 4) hex = '0' + hex;
774
+ out += '\\u' + hex.toLowerCase();
775
+ } else {
776
+ out += s.charAt(i);
777
+ }
778
+ }
779
+ out += '"';
780
+ return out;
781
+ }
782
+
783
+ function _canonicalSerializeState(obj) {
784
+ /* Keys in alphabetical order: custom, disabled, text, value, visible. */
785
+ return '{'
786
+ + '"custom":' + (obj.custom === null ? 'null' : _jsonStringCanonical(obj.custom)) + ','
787
+ + '"disabled":' + (obj.disabled ? 'true' : 'false') + ','
788
+ + '"text":' + (obj.text === null ? 'null' : _jsonStringCanonical(obj.text)) + ','
789
+ + '"value":' + (obj.value === null ? 'null' : _jsonStringCanonical(obj.value)) + ','
790
+ + '"visible":' + (obj.visible ? 'true' : 'false')
791
+ + '}';
792
+ }
793
+
794
+ function _bytesToHexLower(bytes) {
795
+ let out = '';
796
+ for (let i = 0; i < bytes.length; i++) {
797
+ const v = bytes[i];
798
+ out += (v < 16 ? '0' : '') + v.toString(16);
799
+ }
800
+ return out;
801
+ }
802
+
803
+ /* Synchronous SHA-256 fallback. Used in non-secure contexts where
804
+ crypto.subtle is unavailable (HTTP iframes, legacy embeds).
805
+ Reference implementation (~80 LOC). Produces byte-identical
806
+ digests to crypto.subtle.digest('SHA-256', ...). */
807
+ function _sha256Sync(bytes) {
808
+ const K = [
809
+ 0x428a2f98|0,0x71374491|0,0xb5c0fbcf|0,0xe9b5dba5|0,0x3956c25b|0,0x59f111f1|0,0x923f82a4|0,0xab1c5ed5|0,
810
+ 0xd807aa98|0,0x12835b01|0,0x243185be|0,0x550c7dc3|0,0x72be5d74|0,0x80deb1fe|0,0x9bdc06a7|0,0xc19bf174|0,
811
+ 0xe49b69c1|0,0xefbe4786|0,0x0fc19dc6|0,0x240ca1cc|0,0x2de92c6f|0,0x4a7484aa|0,0x5cb0a9dc|0,0x76f988da|0,
812
+ 0x983e5152|0,0xa831c66d|0,0xb00327c8|0,0xbf597fc7|0,0xc6e00bf3|0,0xd5a79147|0,0x06ca6351|0,0x14292967|0,
813
+ 0x27b70a85|0,0x2e1b2138|0,0x4d2c6dfc|0,0x53380d13|0,0x650a7354|0,0x766a0abb|0,0x81c2c92e|0,0x92722c85|0,
814
+ 0xa2bfe8a1|0,0xa81a664b|0,0xc24b8b70|0,0xc76c51a3|0,0xd192e819|0,0xd6990624|0,0xf40e3585|0,0x106aa070|0,
815
+ 0x19a4c116|0,0x1e376c08|0,0x2748774c|0,0x34b0bcb5|0,0x391c0cb3|0,0x4ed8aa4a|0,0x5b9cca4f|0,0x682e6ff3|0,
816
+ 0x748f82ee|0,0x78a5636f|0,0x84c87814|0,0x8cc70208|0,0x90befffa|0,0xa4506ceb|0,0xbef9a3f7|0,0xc67178f2|0,
817
+ ];
818
+ let H = [0x6a09e667|0,0xbb67ae85|0,0x3c6ef372|0,0xa54ff53a|0,0x510e527f|0,0x9b05688c|0,0x1f83d9ab|0,0x5be0cd19|0];
819
+ /* Padding */
820
+ const ml = bytes.length;
821
+ const bits = ml * 8;
822
+ const padlen = (((ml + 9 + 63) >> 6) << 6) - ml;
823
+ const buf = new Uint8Array(ml + padlen);
824
+ buf.set(bytes, 0);
825
+ buf[ml] = 0x80;
826
+ /* big-endian 64-bit length, low 32 bits in the last 4 bytes */
827
+ buf[buf.length - 4] = (bits >>> 24) & 0xff;
828
+ buf[buf.length - 3] = (bits >>> 16) & 0xff;
829
+ buf[buf.length - 2] = (bits >>> 8) & 0xff;
830
+ buf[buf.length - 1] = bits & 0xff;
831
+ const W = new Int32Array(64);
832
+ function ROTR(x, n) { return (x >>> n) | (x << (32 - n)); }
833
+ for (let chunk = 0; chunk < buf.length; chunk += 64) {
834
+ for (let i = 0; i < 16; i++) {
835
+ W[i] = (buf[chunk + i*4 ] << 24) |
836
+ (buf[chunk + i*4 + 1] << 16) |
837
+ (buf[chunk + i*4 + 2] << 8) |
838
+ (buf[chunk + i*4 + 3]);
839
+ }
840
+ for (let i = 16; i < 64; i++) {
841
+ const s0 = ROTR(W[i-15], 7) ^ ROTR(W[i-15], 18) ^ (W[i-15] >>> 3);
842
+ const s1 = ROTR(W[i-2], 17) ^ ROTR(W[i-2], 19) ^ (W[i-2] >>> 10);
843
+ W[i] = (W[i-16] + s0 + W[i-7] + s1) | 0;
844
+ }
845
+ let a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7];
846
+ for (let i = 0; i < 64; i++) {
847
+ const S1 = ROTR(e,6) ^ ROTR(e,11) ^ ROTR(e,25);
848
+ const ch = (e & f) ^ ((~e) & g);
849
+ const t1 = (h + S1 + ch + K[i] + W[i]) | 0;
850
+ const S0 = ROTR(a,2) ^ ROTR(a,13) ^ ROTR(a,22);
851
+ const mj = (a & b) ^ (a & c) ^ (b & c);
852
+ const t2 = (S0 + mj) | 0;
853
+ h = g; g = f; f = e; e = (d + t1) | 0;
854
+ d = c; c = b; b = a; a = (t1 + t2) | 0;
855
+ }
856
+ H[0]=(H[0]+a)|0; H[1]=(H[1]+b)|0; H[2]=(H[2]+c)|0; H[3]=(H[3]+d)|0;
857
+ H[4]=(H[4]+e)|0; H[5]=(H[5]+f)|0; H[6]=(H[6]+g)|0; H[7]=(H[7]+h)|0;
858
+ }
859
+ const out = new Uint8Array(32);
860
+ for (let i = 0; i < 8; i++) {
861
+ out[i*4 ] = (H[i] >>> 24) & 0xff;
862
+ out[i*4 + 1] = (H[i] >>> 16) & 0xff;
863
+ out[i*4 + 2] = (H[i] >>> 8) & 0xff;
864
+ out[i*4 + 3] = H[i] & 0xff;
865
+ }
866
+ return out;
867
+ }
868
+
869
+ async function _sha256(bytes) {
870
+ if (typeof crypto !== 'undefined' && crypto.subtle && crypto.subtle.digest) {
871
+ const buf = await crypto.subtle.digest('SHA-256', bytes);
872
+ return new Uint8Array(buf);
873
+ }
874
+ return _sha256Sync(bytes);
875
+ }
876
+
877
+ function _buildHashState(el) {
878
+ if (!el || el.nodeType !== 1) return null;
879
+ const role = (el.getAttribute && (el.getAttribute('data-nac-role') || '')) || '';
880
+ let text = null;
881
+ if (role === 'action' || role === 'tab') {
882
+ const t = (el.textContent || '').trim();
883
+ text = t.slice(0, 256);
884
+ }
885
+ let value = null;
886
+ if (role === 'field' || role === 'option') {
887
+ value = _hashReadValue(el);
888
+ }
889
+ return {
890
+ custom: (el.getAttribute && el.getAttribute('data-nac-state')) || null,
891
+ disabled: el.disabled === true ||
892
+ (el.getAttribute && el.getAttribute('aria-disabled') === 'true'),
893
+ text: text,
894
+ value: value,
895
+ visible: _hashIsEffectivelyVisible(el),
896
+ };
897
+ }
898
+
899
+ function _encodeCanonical(canonical) {
900
+ if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(canonical);
901
+ const b = new Uint8Array(canonical.length);
902
+ for (let i = 0; i < canonical.length; i++) b[i] = canonical.charCodeAt(i) & 0xff;
903
+ return b;
904
+ }
905
+
906
+ /* Async variant -- uses WebCrypto when available (faster on long
907
+ strings); falls back to the sync implementation in non-secure
908
+ contexts. Awaited by _resolveVersionExpectations on the hash
909
+ check path. */
910
+ async function _stateHashOf(el) {
911
+ const state = _buildHashState(el);
912
+ if (!state) return null;
913
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
914
+ const digest = await _sha256(enc);
915
+ return _bytesToHexLower(digest.slice(0, 16));
916
+ }
917
+
918
+ /* Sync variant -- always uses _sha256Sync. Used by describe() so
919
+ the public read API stays synchronous. ~0.5-1ms per element on
920
+ modern V8; acceptable up to a few hundred elements per describe.
921
+ Hosts with thousands of elements should pre-cache via the
922
+ eager_hashing flag (future optimization). */
923
+ function _stateHashOfSync(el) {
924
+ const state = _buildHashState(el);
925
+ if (!state) return null;
926
+ const enc = _encodeCanonical(_canonicalSerializeState(state));
927
+ const digest = _sha256Sync(enc);
928
+ return _bytesToHexLower(digest.slice(0, 16));
929
+ }
930
+
931
+ /* ---- markHydrationComplete + 100ms fallback (RFC sec 5.10) ---- */
932
+
933
+ function _completeHydration(triggered_by) {
934
+ if (_hydration_complete) return;
935
+ _hydration_complete = true;
936
+ if (_hydration_fallback_timer) {
937
+ clearTimeout(_hydration_fallback_timer);
938
+ _hydration_fallback_timer = null;
939
+ }
940
+ /* Enumerate every registered plugin instance and emit per-plugin
941
+ events with from_version=null, plus a global tree event. */
942
+ const affected = [];
943
+ _plugin_versions.forEach(function (_n, key) {
944
+ const i = key.indexOf('|');
945
+ const slug = key.slice(0, i);
946
+ const inst = key.slice(i + 1) || null;
947
+ affected.push({ slug: slug, instance_id: inst });
948
+ });
949
+ /* Tree bump tagged as hydration_complete. */
950
+ _bumpTreeVersion('hydration_complete', affected.slice());
951
+ if (typeof document !== 'undefined') {
952
+ for (let i = 0; i < affected.length; i++) {
953
+ const a = affected[i];
954
+ const key = _pluginKey(a.slug, a.instance_id);
955
+ const curN = _plugin_versions.get(key) || 0;
956
+ document.dispatchEvent(new CustomEvent('nac:plugin:invalidated', {
957
+ detail: {
958
+ plugin_slug: a.slug,
959
+ plugin_instance_id: a.instance_id,
960
+ from_version: null,
961
+ to_version: 'v_' + curN,
962
+ trigger: 'hydration_complete',
963
+ },
964
+ }));
965
+ }
966
+ }
967
+ }
968
+
969
+ function markHydrationComplete() {
970
+ if (_hydration_complete) return;
971
+ _completeHydration('explicit');
972
+ }
973
+
974
+ function _armHydrationFallback() {
975
+ if (typeof document === 'undefined') return;
976
+ const start = function () {
977
+ _hydration_fallback_timer = setTimeout(function () {
978
+ if (!_hydration_complete) _completeHydration('fallback_100ms');
979
+ }, 100);
980
+ };
981
+ if (document.readyState === 'loading') {
982
+ document.addEventListener('DOMContentLoaded', start, { once: true });
983
+ } else {
984
+ start();
985
+ }
986
+ }
987
+
988
+ /* ---- versionHistory devtools surface (RFC sec 5.9) ---- */
989
+
990
+ function versionHistory(limit) {
991
+ const n = (typeof limit === 'number' && limit > 0)
992
+ ? Math.min(limit, _version_history.length)
993
+ : Math.min(50, _version_history.length);
994
+ return _version_history.slice(-n).reverse();
995
+ }
996
+
997
+ /* ---- Resolver helper for expected_* checks (RFC sec 5.4 + 8.3) ----
998
+
999
+ Returns Promise<void>. Throws NacError on mismatch / tier reject /
1000
+ STRICT-without-expectation. Cheap-to-expensive order:
1001
+ 1. STRICT gate
1002
+ 2. NAC-3 (non-versioned) tier rejects ANY expected_*
1003
+ 3. expected_plugin_version (integer compare)
1004
+ 4. expected_tree_version (integer compare)
1005
+ 5. expected_element_state_hash (SHA-256, awaited last)
1006
+ */
1007
+ async function _resolveVersionExpectations(opts, el) {
1008
+ const o = opts || {};
1009
+ const hasAny = ('expected_plugin_version' in o) ||
1010
+ ('expected_tree_version' in o) ||
1011
+ ('expected_element_state_hash' in o);
1012
+ if (_strictVersioningOn() && !hasAny) {
1013
+ throw NacError('version_required',
1014
+ 'STRICT_VERSIONING is on; at least one expected_* required.',
1015
+ { method: (o && o.method) || undefined });
1016
+ }
1017
+ /* Tier reject -- conformance_tier is exposed on the NAC export,
1018
+ and a runtime that declares NAC-3 must NOT silently honor any
1019
+ expected_*. */
1020
+ const tier = (typeof window !== 'undefined' && window.NAC &&
1021
+ window.NAC.conformance_tier) || 'NAC-3-versioned';
1022
+ if (tier === 'NAC-3' && hasAny) {
1023
+ throw NacError('feature_not_supported',
1024
+ 'Runtime tier is NAC-3 (non-versioned); expected_* parameters are not honored.',
1025
+ { tier: 'NAC-3', requested_feature: 'versioning' });
1026
+ }
1027
+ /* Plugin version */
1028
+ if ('expected_plugin_version' in o) {
1029
+ const scope = _resolvePluginScope(el);
1030
+ if (scope) {
1031
+ const cur = _pluginVersionFor(scope.slug, scope.instance_id);
1032
+ if (o.expected_plugin_version !== cur) {
1033
+ /* RFC V24-04 sec 5.5: extras nested under .detail.
1034
+ NacError() flattens by default; mirror under detail
1035
+ for the new versioning error class so agents reading
1036
+ the RFC can use err.detail.reason directly. */
1037
+ const detail = {
1038
+ reason: 'plugin_changed',
1039
+ plugin_slug: scope.slug,
1040
+ plugin_instance_id: scope.instance_id,
1041
+ expected_plugin_version: o.expected_plugin_version,
1042
+ current_plugin_version: cur,
1043
+ };
1044
+ throw NacError('snapshot_stale',
1045
+ 'expected_plugin_version=' + o.expected_plugin_version +
1046
+ ' current_plugin_version=' + cur,
1047
+ Object.assign({ detail: detail }, detail));
1048
+ }
1049
+ }
1050
+ }
1051
+ /* Tree version */
1052
+ if ('expected_tree_version' in o) {
1053
+ const cur = _treeVersionStr();
1054
+ if (o.expected_tree_version !== cur) {
1055
+ const detail = {
1056
+ reason: 'tree_changed',
1057
+ expected_tree_version: o.expected_tree_version,
1058
+ current_tree_version: cur,
1059
+ };
1060
+ throw NacError('snapshot_stale',
1061
+ 'expected_tree_version=' + o.expected_tree_version +
1062
+ ' current_tree_version=' + cur,
1063
+ Object.assign({ detail: detail }, detail));
1064
+ }
1065
+ }
1066
+ /* Element state hash (awaited last) */
1067
+ if ('expected_element_state_hash' in o) {
1068
+ const cur = await _stateHashOf(el);
1069
+ if (o.expected_element_state_hash !== cur) {
1070
+ const detail = {
1071
+ reason: 'element_changed',
1072
+ expected_element_state_hash: o.expected_element_state_hash,
1073
+ current_element_state_hash: cur,
1074
+ };
1075
+ throw NacError('snapshot_stale',
1076
+ 'expected_element_state_hash=' + o.expected_element_state_hash +
1077
+ ' current_element_state_hash=' + cur,
1078
+ Object.assign({ detail: detail }, detail));
1079
+ }
1080
+ }
1081
+ }
1082
+
1083
+ /* Read back the post-dispatch versions. Used by every mutating API
1084
+ after the side effect lands. Pair with _flushObserverQueue() to
1085
+ guarantee MutationObserver records have been integrated. */
1086
+ function _atVersionsFor(el) {
1087
+ const scope = _resolvePluginScope(el);
1088
+ return {
1089
+ at_plugin_version: scope ? _pluginVersionFor(scope.slug, scope.instance_id) : null,
1090
+ at_tree_version: _treeVersionStr(),
1091
+ };
1092
+ }
1093
+
1094
+ /* Flush pending MutationObserver records into version bumps before
1095
+ resolving the promise (RFC sec 5.8). queueMicrotask is enough --
1096
+ the observer fires once per microtask flush. */
1097
+ function _flushObserverQueue() {
1098
+ return new Promise(function (resolve) {
1099
+ if (typeof queueMicrotask === 'function') {
1100
+ queueMicrotask(resolve);
1101
+ } else {
1102
+ Promise.resolve().then(resolve);
1103
+ }
1104
+ });
1105
+ }
1106
+
1107
+ /* ==================================================================
1108
+ End of v2.4 / RFC V24-04 foundation block.
1109
+ ================================================================== */
1110
+
326
1111
  /* H1.v7 (2026-05-21): structured disambiguation contract.
327
1112
  When the runtime cannot resolve an id/verb/qualifier/label
328
1113
  unambiguously, it MUST emit `nac:disambiguation_requested` with
@@ -1432,6 +2217,20 @@
1432
2217
  if (!manifest.version) manifest.version = '1.0.0';
1433
2218
  if (!manifest.nac_version) manifest.nac_version = '1.0';
1434
2219
 
2220
+ /* v2.5 / RFC V24-01 -- synchronous slug uniqueness gate.
2221
+ Throws NacError('duplicate_plugin_no_instance_id', ...) when
2222
+ the DOM already contains multiple roots for this slug and any
2223
+ of them omit or duplicate data-nac-plugin-id. Gated by
2224
+ NAC.HARD_DEDUP (default true; settable false for migration). */
2225
+ const _hardDedup = (typeof global !== 'undefined' && global.NAC
2226
+ ? global.NAC.HARD_DEDUP !== false
2227
+ : (typeof window !== 'undefined' && window.NAC
2228
+ ? window.NAC.HARD_DEDUP !== false
2229
+ : true));
2230
+ if (_hardDedup) {
2231
+ _checkPluginSlugUniqueOrThrow(slug);
2232
+ }
2233
+
1435
2234
  /* v1.5.1 cross-plugin duplicate-id detection.
1436
2235
  Spec section P7 expects nac_ids to be plugin-namespaced
1437
2236
  ('plugin.element' convention). When two manifests register
@@ -1599,6 +2398,254 @@
1599
2398
  return _manifests[slug] || null;
1600
2399
  }
1601
2400
 
2401
+ /* ================================================================
2402
+ v2.5 V24-02 -- syncPlugin: idempotent registration
2403
+ ================================================================
2404
+
2405
+ SPA hosts that re-render a component call register() again on
2406
+ remount; the legacy register() appends a new manifest entry,
2407
+ accumulating stale state. syncPlugin REPLACES the manifest for a
2408
+ given slug instead of appending. Calling N times with the same
2409
+ manifest leaves the registry in the same state as calling once.
2410
+
2411
+ Validation is identical to register() (manifest_role_unknown,
2412
+ tab_id_manifest_role_drift, etc honour STRICT_VALIDATION).
2413
+ Versioning: each call mints a new plugin_version (V24-04 OCC)
2414
+ and -- only on REPLACE, not first-add -- emits
2415
+ nac:plugin:invalidated so subscribers can refresh derived state. */
2416
+
2417
+ /* syncPlugin uses the V24-04 versioning machinery: every replace
2418
+ calls _bumpPluginVersion(slug, null, 'syncPlugin') which bumps
2419
+ _plugin_versions + _tree_version + dispatches nac:plugin:invalidated
2420
+ in one atomic step. Single source of truth for OCC. */
2421
+ function syncPlugin(arg1, arg2) {
2422
+ let m;
2423
+ if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
2424
+ /* (slug, manifest) form -- match register's calling convention. */
2425
+ m = Object.assign({}, arg2);
2426
+ if (!m.plugin_slug) m.plugin_slug = arg1;
2427
+ } else if (arg1 && typeof arg1 === 'object') {
2428
+ m = arg1;
2429
+ } else {
2430
+ throw NacError('invalid',
2431
+ 'syncPlugin: requires (manifest) or (slug, manifest)');
2432
+ }
2433
+ const slug = m.plugin_slug;
2434
+ if (!slug || typeof slug !== 'string') {
2435
+ throw NacError('invalid',
2436
+ 'syncPlugin: manifest.plugin_slug required (non-empty string)');
2437
+ }
2438
+ const wasPresent = !!_manifests[slug];
2439
+ /* Replace path: drop the prior entry so register() does not
2440
+ append-by-side-effect when callers used the array-of-elements
2441
+ merge pattern. */
2442
+ if (wasPresent) {
2443
+ delete _manifests[slug];
2444
+ if (typeof _instances !== 'undefined') delete _instances[slug];
2445
+ }
2446
+ /* Delegate to register() so validation + storage code-path stays
2447
+ exactly one place. If register throws (strict validation), the
2448
+ prior entry is GONE -- caller's responsibility to handle. */
2449
+ register(m);
2450
+ /* Bump V24-04 OCC version on REPLACE only. First-add is a normal
2451
+ register: the boot tree_version already reflects the new plugin
2452
+ and subscribers do not need to refresh anything that did not
2453
+ exist a moment ago. _bumpPluginVersion fires nac:plugin:invalidated
2454
+ as part of its work, so we don't dispatch again here. */
2455
+ if (wasPresent) {
2456
+ _bumpPluginVersion(slug, null, 'syncPlugin');
2457
+ }
2458
+ return {
2459
+ replaced: wasPresent,
2460
+ slug: slug,
2461
+ version: _pluginVersionFor(slug, null),
2462
+ };
2463
+ }
2464
+
2465
+ /* ================================================================
2466
+ v2.5 V24-05 -- Agent authority + sudo elevation
2467
+ ================================================================
2468
+
2469
+ Three primitives for a host to interpose a confirmation UI
2470
+ between an agent dispatch and the action's side effect, with a
2471
+ SUDO-style elevation that bypasses confirmations for a granted
2472
+ scope until its TTL expires.
2473
+
2474
+ NAC.set_confirm_handler(fn)
2475
+ fn is async (req) => boolean. The host renders its UI
2476
+ (modal, voice, Discord button, etc) and resolves true on
2477
+ approve, false on reject. A handler that throws is treated
2478
+ as "reject" (never as a silent approval).
2479
+
2480
+ NAC.confirm_action(action_id, message, opts?)
2481
+ opts = { scope?: 'low'|'medium'|'high', metadata?: {...} }
2482
+ Returns Promise<boolean>. If currently elevated for an
2483
+ equal-or-stricter scope, resolves true synchronously
2484
+ WITHOUT invoking the handler.
2485
+
2486
+ NAC.request_authority(scope, ttl_ms, opts?)
2487
+ Asks the host for sudo elevation. On grant, subsequent
2488
+ confirm_action calls in that scope (or lower) resolve
2489
+ immediately for ttl_ms. After TTL the elevation
2490
+ auto-revokes; manual revoke is NAC.revoke_authority(scope).
2491
+
2492
+ NAC.has_authority(scope) -> boolean
2493
+ NAC.revoke_authority(scope) -> void (idempotent)
2494
+
2495
+ Scope rank: high > medium > low. Granted high authority
2496
+ satisfies medium + low; granted low does NOT satisfy higher.
2497
+
2498
+ Provenance on document:
2499
+ nac:authority:requested / :granted / :denied / :revoked / :expired
2500
+ nac:action:confirmed / :rejected */
2501
+
2502
+ const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
2503
+ const _v25_authority_grants = new Map();
2504
+ let _v25_authReqSeq = 0;
2505
+ let _v25_confirm_handler = null;
2506
+
2507
+ function _v25_emitAuth(kind, detail) {
2508
+ if (typeof document === 'undefined') return;
2509
+ try {
2510
+ document.dispatchEvent(new CustomEvent('nac:authority:' + kind,
2511
+ { detail: detail, bubbles: true }));
2512
+ } catch (_) { /* SSR or no document */ }
2513
+ }
2514
+ function _v25_emitAction(kind, detail) {
2515
+ if (typeof document === 'undefined') return;
2516
+ try {
2517
+ document.dispatchEvent(new CustomEvent('nac:action:' + kind,
2518
+ { detail: detail, bubbles: true }));
2519
+ } catch (_) { /* SSR or no document */ }
2520
+ }
2521
+
2522
+ function set_confirm_handler(fn) {
2523
+ if (typeof fn !== 'function') {
2524
+ throw NacError('invalid',
2525
+ 'NAC.set_confirm_handler: fn must be a function');
2526
+ }
2527
+ _v25_confirm_handler = fn;
2528
+ }
2529
+
2530
+ function has_authority(scope) {
2531
+ if (!_V25_SCOPE_RANK[scope]) return false;
2532
+ const want = _V25_SCOPE_RANK[scope];
2533
+ const now = Date.now();
2534
+ /* Iterate live grants. Higher rank satisfies lower-rank check.
2535
+ Auto-purge expired entries inline so the map stays clean. */
2536
+ let satisfied = false;
2537
+ _v25_authority_grants.forEach(function (info, grantedScope) {
2538
+ if (info.expires_at <= now) return; /* timer will purge */
2539
+ if (_V25_SCOPE_RANK[grantedScope] >= want) satisfied = true;
2540
+ });
2541
+ return satisfied;
2542
+ }
2543
+
2544
+ function revoke_authority(scope) {
2545
+ const info = _v25_authority_grants.get(scope);
2546
+ if (!info) return; /* idempotent */
2547
+ if (info.timer) { try { clearTimeout(info.timer); } catch (_) {} }
2548
+ _v25_authority_grants.delete(scope);
2549
+ _v25_emitAuth('revoked', { scope: scope, reason: 'manual' });
2550
+ }
2551
+
2552
+ function request_authority(scope, ttl_ms, opts) {
2553
+ return new Promise(function (resolve, reject) {
2554
+ if (!_V25_SCOPE_RANK[scope]) {
2555
+ reject(NacError('invalid',
2556
+ 'request_authority: scope must be one of low|medium|high'));
2557
+ return;
2558
+ }
2559
+ if (typeof ttl_ms !== 'number' || ttl_ms < 0 || !isFinite(ttl_ms)) {
2560
+ reject(NacError('invalid',
2561
+ 'request_authority: ttl_ms must be a non-negative finite number'));
2562
+ return;
2563
+ }
2564
+ if (!_v25_confirm_handler) {
2565
+ reject(NacError('no_confirm_handler',
2566
+ 'request_authority: NAC.set_confirm_handler must be called first'));
2567
+ return;
2568
+ }
2569
+ const reqId = 'auth_' + Date.now().toString(36) + '_' + (++_v25_authReqSeq).toString(36);
2570
+ const req = {
2571
+ kind: 'request_authority',
2572
+ request_id: reqId,
2573
+ scope: scope,
2574
+ ttl_ms: ttl_ms,
2575
+ metadata: (opts && opts.metadata) || {},
2576
+ };
2577
+ _v25_emitAuth('requested', req);
2578
+ let p;
2579
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
2580
+ catch (e) { p = Promise.resolve(false); }
2581
+ p.then(function (granted) { return !!granted; },
2582
+ function () { return false; })
2583
+ .then(function (granted) {
2584
+ if (!granted) {
2585
+ _v25_emitAuth('denied',
2586
+ { scope: scope, ttl_ms: ttl_ms, request_id: reqId });
2587
+ resolve({ granted: false, scope: scope, expires_at: null });
2588
+ return;
2589
+ }
2590
+ const now = Date.now();
2591
+ const expires_at = now + ttl_ms;
2592
+ /* Replace any prior grant for the same scope. */
2593
+ const prior = _v25_authority_grants.get(scope);
2594
+ if (prior && prior.timer) { try { clearTimeout(prior.timer); } catch (_) {} }
2595
+ const timer = setTimeout(function () {
2596
+ _v25_authority_grants.delete(scope);
2597
+ _v25_emitAuth('expired', { scope: scope, reason: 'ttl' });
2598
+ }, ttl_ms);
2599
+ _v25_authority_grants.set(scope, { expires_at: expires_at, timer: timer });
2600
+ _v25_emitAuth('granted',
2601
+ { scope: scope, expires_at: expires_at, request_id: reqId });
2602
+ resolve({ granted: true, scope: scope, expires_at: expires_at });
2603
+ });
2604
+ });
2605
+ }
2606
+
2607
+ function confirm_action(action_id, message, opts) {
2608
+ return new Promise(function (resolve, reject) {
2609
+ if (typeof action_id !== 'string' || !action_id) {
2610
+ reject(NacError('invalid',
2611
+ 'confirm_action: action_id must be a non-empty string'));
2612
+ return;
2613
+ }
2614
+ const scope = (opts && opts.scope) || 'medium';
2615
+ const metadata = (opts && opts.metadata) || {};
2616
+ /* Sudo bypass -- if we already have authority for this scope
2617
+ (or higher), short-circuit without calling the handler. */
2618
+ if (has_authority(scope)) {
2619
+ _v25_emitAction('confirmed',
2620
+ { action_id: action_id, scope: scope, sudo: true });
2621
+ resolve(true);
2622
+ return;
2623
+ }
2624
+ if (!_v25_confirm_handler) {
2625
+ reject(NacError('no_confirm_handler',
2626
+ 'confirm_action: NAC.set_confirm_handler must be called first'));
2627
+ return;
2628
+ }
2629
+ const req = {
2630
+ kind: 'confirm_action',
2631
+ action_id: action_id,
2632
+ message: message,
2633
+ scope: scope,
2634
+ metadata: metadata,
2635
+ };
2636
+ let p;
2637
+ try { p = Promise.resolve(_v25_confirm_handler(req)); }
2638
+ catch (e) { p = Promise.resolve(false); }
2639
+ p.then(function (approved) { return !!approved; },
2640
+ function () { return false; })
2641
+ .then(function (approved) {
2642
+ _v25_emitAction(approved ? 'confirmed' : 'rejected',
2643
+ { action_id: action_id, scope: scope, sudo: false });
2644
+ resolve(approved);
2645
+ });
2646
+ });
2647
+ }
2648
+
1602
2649
  /* ---------- Element discovery ----------------------------------- */
1603
2650
 
1604
2651
  /* ---------- v2.3 shadow DOM resolution (F1 + F6) ----------
@@ -1838,12 +2885,20 @@
1838
2885
  const plugins = Array.prototype.slice.call(
1839
2886
  document.querySelectorAll('[data-nac-plugin]')
1840
2887
  ).map(function (root) {
2888
+ const slug = root.getAttribute('data-nac-plugin');
2889
+ const instance_id = root.getAttribute('data-nac-plugin-id') || null;
1841
2890
  return {
1842
- plugin: root.getAttribute('data-nac-plugin'),
1843
- plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
1844
- elements: Array.prototype.slice.call(
2891
+ plugin: slug,
2892
+ plugin_instance_id: instance_id,
2893
+ plugin_state: root.getAttribute('data-nac-plugin-state') || 'idle',
2894
+ /* v2.5 / RFC V24-04 (sec 5.1): per-plugin monotonic version
2895
+ token. Primary tool for agents -- ignore noise outside the
2896
+ targeted plugin by passing expected_plugin_version on
2897
+ dispatch. */
2898
+ plugin_version: _pluginVersionFor(slug, instance_id),
2899
+ elements: Array.prototype.slice.call(
1845
2900
  root.querySelectorAll('[data-nac-id]')
1846
- ).map(_serializeElement),
2901
+ ).map(_serializeElementWithHash),
1847
2902
  };
1848
2903
  });
1849
2904
  return {
@@ -1852,9 +2907,24 @@
1852
2907
  url: location.href,
1853
2908
  active: _activePlugin(),
1854
2909
  plugins: plugins,
2910
+ /* v2.5 / RFC V24-04 (sec 5.3): global monotonic version token.
2911
+ Escape hatch for cross-plugin orchestration; prefer
2912
+ plugin_version for single-plugin plans. */
2913
+ tree_version: _treeVersionStr(),
1855
2914
  };
1856
2915
  }
1857
2916
 
2917
+ /* v2.5 / RFC V24-04 (sec 5.2): serialize + attach element_state_hash.
2918
+ Sync compute; ~0.5-1ms per element. NULL when the element does
2919
+ not carry a role that contributes to the hash. */
2920
+ function _serializeElementWithHash(el) {
2921
+ const base = _serializeElement(el);
2922
+ if (!base) return base;
2923
+ try { base.element_state_hash = _stateHashOfSync(el); }
2924
+ catch (_) { base.element_state_hash = null; }
2925
+ return base;
2926
+ }
2927
+
1858
2928
  function list(role) {
1859
2929
  const all = _allElements().map(_serializeElement);
1860
2930
  if (!role) return all;
@@ -3500,6 +4570,10 @@
3500
4570
  orphans: [],
3501
4571
  unmounted: [],
3502
4572
  convention_violations: [],
4573
+ /* v2.5 / RFC V24-01: plugin slug uniqueness findings live in
4574
+ their own bucket so CI integrations can gate on them
4575
+ independently of nac_id duplicates. */
4576
+ plugin_instance_violations: _scanPluginInstances(),
3503
4577
  plugin_count: 0,
3504
4578
  total_ids: 0,
3505
4579
  timestamp: Date.now(),
@@ -5540,114 +6614,6 @@
5540
6614
  };
5541
6615
  }
5542
6616
 
5543
- /* ---------- v1.9.0: action confirmation (sec 6.2.32) ---------- */
5544
-
5545
- /* The runtime maintains an in-memory map of in-flight confirm
5546
- requests keyed by confirm_id. confirm_action() emits the
5547
- requested event, awaits the host's handler decision (or the
5548
- default window.confirm), then emits granted/denied. */
5549
- let _confirmHandler = null;
5550
- function set_confirm_handler(fn) {
5551
- _confirmHandler = (typeof fn === 'function') ? fn : null;
5552
- }
5553
- function _newConfirmId() {
5554
- return 'cfm-' + Date.now().toString(36) + '-' +
5555
- Math.random().toString(36).slice(2, 8);
5556
- }
5557
- async function confirm_action(action_id, opts) {
5558
- opts = opts || {};
5559
- /* Resolve the element + its declared a11y_hint. */
5560
- const el = _findElement(action_id, {});
5561
- let hints = opts.hints;
5562
- if (!hints && el) {
5563
- const raw = el.getAttribute('data-nac-a11y-hint') || '';
5564
- hints = raw.split('|').map(function (s) { return s.trim(); })
5565
- .filter(function (s) { return s.length > 0; });
5566
- }
5567
- hints = hints || [];
5568
- const locale = (document.documentElement.lang || 'en').split('-')[0];
5569
- /* v1.9.0 sec 3.1: data-nac-confirmation-message override.
5570
- Host can declare per-element confirmation text (literal or
5571
- i18n key). Beats the auto-generated hint vocabulary text. */
5572
- let hint_text = opts.hint_text;
5573
- if (!hint_text && el) {
5574
- const cm = el.getAttribute('data-nac-confirmation-message');
5575
- if (cm && cm.length) {
5576
- if (cm.indexOf('i18n:') === 0 && _a11y_hint_localizer) {
5577
- /* Re-use the localizer hook with the i18n key as tag. */
5578
- try {
5579
- const v = _a11y_hint_localizer(cm.slice(5), locale);
5580
- if (typeof v === 'string' && v) hint_text = v;
5581
- } catch (e) { /* fall through */ }
5582
- }
5583
- if (!hint_text) hint_text = cm.indexOf('i18n:') === 0 ? cm.slice(5) : cm;
5584
- }
5585
- }
5586
- if (!hint_text) {
5587
- /* v1.9.0: walk hints in normative priority order so the
5588
- strongest tag leads the interposition text. */
5589
- const sorted = sort_hints_by_priority(hints);
5590
- hint_text = sorted.map(function (t) { return _localizeHintTag(t, locale); }).join(' ');
5591
- }
5592
- if (!hint_text) hint_text = 'Confirm this action?';
5593
- const verb = (el && el.getAttribute('data-nac-action')) || 'apply';
5594
- const confirm_id = _newConfirmId();
5595
- const pluginRoot = el && el.closest('[data-nac-plugin]');
5596
- const plugin = pluginRoot ? pluginRoot.getAttribute('data-nac-plugin') : null;
5597
- const reqDetail = {
5598
- plugin: plugin, plugin_instance_id: null,
5599
- action_id: action_id,
5600
- verb: verb,
5601
- hints: hints,
5602
- hint_text: hint_text,
5603
- confirm_id: confirm_id,
5604
- expires_at: Date.now() + (opts.timeout_ms || 60000),
5605
- };
5606
- /* opts.source defaults to {type:'script'} via _emit's normalisation. */
5607
- if (opts.source) reqDetail.source = opts.source;
5608
- _emit('nac:action:confirm:requested', reqDetail);
5609
- let resp;
5610
- try {
5611
- if (_confirmHandler) {
5612
- resp = await _confirmHandler(reqDetail);
5613
- } else if (typeof window.confirm === 'function') {
5614
- const ok = window.confirm(hint_text);
5615
- resp = { granted: !!ok, granted_via: 'window_confirm' };
5616
- } else {
5617
- resp = { granted: false, reason: 'no_handler' };
5618
- }
5619
- } catch (err) {
5620
- resp = { granted: false, reason: 'handler_error',
5621
- error: err && err.message };
5622
- }
5623
- if (resp.granted) {
5624
- _emit('nac:action:confirm:granted', {
5625
- plugin: plugin, plugin_instance_id: null,
5626
- action_id: action_id,
5627
- confirm_id: confirm_id,
5628
- granted_by: opts.source && opts.source.type === 'agent' ? 'agent' : 'user',
5629
- granted_via: resp.granted_via || 'modal_button',
5630
- source: opts.source || { type: 'user' },
5631
- });
5632
- } else {
5633
- _emit('nac:action:confirm:denied', {
5634
- plugin: plugin, plugin_instance_id: null,
5635
- action_id: action_id,
5636
- confirm_id: confirm_id,
5637
- reason: resp.reason || 'user_cancelled',
5638
- source: opts.source || { type: 'user' },
5639
- });
5640
- }
5641
- return {
5642
- confirm_id: confirm_id,
5643
- granted: !!resp.granted,
5644
- granted_by: resp.granted ?
5645
- (opts.source && opts.source.type === 'agent' ? 'agent' : 'user') : undefined,
5646
- granted_via: resp.granted ? (resp.granted_via || 'modal_button') : undefined,
5647
- reason: resp.granted ? undefined : (resp.reason || 'user_cancelled'),
5648
- };
5649
- }
5650
-
5651
6617
  /* ---------- v1.9.0: action undoable flag (sec 6.2.33) --------- */
5652
6618
 
5653
6619
  function _findActionInManifests(action_id) {
@@ -5780,12 +6746,777 @@
5780
6746
  return count;
5781
6747
  }
5782
6748
 
6749
+ /* ================================================================
6750
+ v2.5 Block A -- plugin extension contract (SPEC.md sec 15)
6751
+ ================================================================
6752
+
6753
+ Adds an agnostic routing layer so a plugin can declare verbs /
6754
+ state / events that flow through backends other than direct DOM:
6755
+ postMessage to iframes, plugin SDK calls, script bridges, DOM
6756
+ mirrors, same-origin window reads, synthetic events. The runtime
6757
+ stays ignorant of any specific app -- it only knows the fixed
6758
+ vocabulary of backend kinds and the extractor DSL.
6759
+
6760
+ IMPORTANT: NO fallback to v2.4 register() semantics. v2.5 plugins
6761
+ live in their own registry. NAC.call / read / subscribe ONLY
6762
+ consult this registry; they never silently degrade to NAC.click()
6763
+ against a same-named DOM element. */
6764
+
6765
+ const _v25_plugins = Object.create(null);
6766
+
6767
+ /* The 8 backend names from SPEC.md sec 15.4. Any other name in a
6768
+ manifest is a hard reject at register time. */
6769
+ const _V25_VALID_BACKENDS = {
6770
+ 'postmessage': true,
6771
+ 'postmessage-listen': true,
6772
+ 'sdk-call': true,
6773
+ 'script-bridge': true,
6774
+ 'dom-mirror': true,
6775
+ 'same-origin-window': true,
6776
+ 'synthetic-mutation': true,
6777
+ 'synthetic-poll': true,
6778
+ };
6779
+
6780
+ /* Counter for the request_id baked into every provenance event. */
6781
+ let _v25_req_counter = 0;
6782
+ function _v25_nextRequestId(prefix) {
6783
+ _v25_req_counter += 1;
6784
+ /* Hex-ish but non-cryptographic; the contract only requires
6785
+ uniqueness within a session for correlation. */
6786
+ return prefix + '_' + Date.now().toString(36) + '_' + _v25_req_counter.toString(36);
6787
+ }
6788
+
6789
+ /* ---------- 15.5 extractor DSL ---------- */
6790
+
6791
+ /* Apply an extractor DSL string to a raw value (or DOM element).
6792
+ Returns the extracted value. Throws if the DSL is malformed.
6793
+ The runtime swallows extractor errors at dispatch time (treats
6794
+ them as "this binding failed"); throwing here lets the test
6795
+ surface bad manifests during register / first call. */
6796
+ function _v25_extract(rawValue, dsl, isDom) {
6797
+ if (dsl == null || dsl === '') return rawValue;
6798
+ /* DOM-only forms first */
6799
+ if (dsl === 'text') {
6800
+ if (!isDom) throw new Error('extractor "text" requires a DOM element');
6801
+ return rawValue.textContent;
6802
+ }
6803
+ if (dsl === 'value') {
6804
+ if (!isDom) throw new Error('extractor "value" requires a DOM element');
6805
+ return rawValue.value;
6806
+ }
6807
+ if (dsl === 'present') {
6808
+ /* For DOM backends, rawValue is the element OR null. */
6809
+ return rawValue != null;
6810
+ }
6811
+ if (dsl.indexOf('attribute:') === 0) {
6812
+ if (!isDom) throw new Error('extractor "attribute:" requires a DOM element');
6813
+ const attr = dsl.slice('attribute:'.length);
6814
+ return rawValue.getAttribute(attr);
6815
+ }
6816
+ if (dsl.indexOf('classList.contains:') === 0) {
6817
+ if (!isDom) throw new Error('extractor "classList.contains:" requires a DOM element');
6818
+ const cls = dsl.slice('classList.contains:'.length);
6819
+ return rawValue.classList.contains(cls);
6820
+ }
6821
+ /* Otherwise treat as a dotted field path against rawValue. */
6822
+ if (/^[A-Za-z_][\w.]*$/.test(dsl)) {
6823
+ const parts = dsl.split('.');
6824
+ let cur = rawValue;
6825
+ for (let i = 0; i < parts.length; i++) {
6826
+ if (cur == null) return undefined;
6827
+ cur = cur[parts[i]];
6828
+ }
6829
+ return cur;
6830
+ }
6831
+ throw new Error('unknown extractor DSL: ' + dsl);
6832
+ }
6833
+
6834
+ /* ---------- 15.4 backend dispatchers ----------
6835
+ Each backend dispatcher returns a Promise.
6836
+ - For verbs: resolves with the backend's return value (often {ok}).
6837
+ - For state: resolves with the raw value (extractor applied by caller).
6838
+ - Rejects with a plain Error whose .message goes into provenance /
6839
+ err.attempts. */
6840
+
6841
+ function _v25_resolvePath(root, path) {
6842
+ /* Walk a dotted path. Returns { parent, key, value } where
6843
+ parent[key] === value. Used by sdk-call assign / read. */
6844
+ if (!path) return { parent: null, key: null, value: undefined };
6845
+ const parts = path.split('.');
6846
+ let parent = null;
6847
+ let cur = root;
6848
+ let key = null;
6849
+ for (let i = 0; i < parts.length; i++) {
6850
+ if (cur == null) return { parent: null, key: parts[i], value: undefined };
6851
+ parent = cur;
6852
+ key = parts[i];
6853
+ cur = cur[key];
6854
+ }
6855
+ return { parent: parent, key: key, value: cur };
6856
+ }
6857
+
6858
+ function _v25_backend_sdk_call(binding, args) {
6859
+ const mode = binding.mode || 'invoke';
6860
+ const path = binding.path;
6861
+ if (!path || typeof path !== 'string') {
6862
+ return Promise.reject(new Error('sdk-call requires `path` string'));
6863
+ }
6864
+ const resolved = _v25_resolvePath(global, path);
6865
+ if (mode === 'read') {
6866
+ if (resolved.parent == null) {
6867
+ return Promise.reject(new Error('sdk-call read: path not resolvable: ' + path));
6868
+ }
6869
+ if (resolved.value === undefined) {
6870
+ return Promise.reject(new Error('sdk-call read: path resolves to undefined: ' + path));
6871
+ }
6872
+ return Promise.resolve(resolved.value);
6873
+ }
6874
+ if (mode === 'assign') {
6875
+ if (resolved.parent == null) {
6876
+ return Promise.reject(new Error('sdk-call assign: path parent not resolvable: ' + path));
6877
+ }
6878
+ resolved.parent[resolved.key] = args;
6879
+ return Promise.resolve({ ok: true });
6880
+ }
6881
+ if (mode === 'invoke') {
6882
+ if (resolved.parent == null || typeof resolved.value !== 'function') {
6883
+ return Promise.reject(new Error('sdk-call invoke: path is not a function: ' + path));
6884
+ }
6885
+ try {
6886
+ const ret = resolved.value.call(resolved.parent, args);
6887
+ return Promise.resolve(ret);
6888
+ } catch (e) {
6889
+ return Promise.reject(e);
6890
+ }
6891
+ }
6892
+ return Promise.reject(new Error('sdk-call: unknown mode ' + mode));
6893
+ }
6894
+
6895
+ function _v25_backend_dom_mirror(binding /*, args*/) {
6896
+ const sel = binding.selector;
6897
+ if (!sel) return Promise.reject(new Error('dom-mirror requires `selector` string'));
6898
+ const el = document.querySelector(sel);
6899
+ if (binding.extract === 'present') {
6900
+ /* present extractor is well-defined even for null element. */
6901
+ return Promise.resolve(el != null);
6902
+ }
6903
+ if (el == null) {
6904
+ return Promise.reject(new Error('dom-mirror: selector matched no element: ' + sel));
6905
+ }
6906
+ try {
6907
+ const value = _v25_extract(el, binding.extract, true);
6908
+ if (value === undefined) {
6909
+ return Promise.reject(new Error('dom-mirror: extractor returned undefined for ' + sel));
6910
+ }
6911
+ return Promise.resolve(value);
6912
+ } catch (e) {
6913
+ return Promise.reject(e);
6914
+ }
6915
+ }
6916
+
6917
+ /* postmessage (verb): post a structured message to the iframe.contentWindow
6918
+ of the target. `values` literal + `values_from_args` forward keys. */
6919
+ function _v25_backend_postmessage(binding, args) {
6920
+ const sel = binding.target;
6921
+ if (!sel) return Promise.reject(new Error('postmessage requires `target` selector'));
6922
+ const iframe = document.querySelector(sel);
6923
+ if (!iframe) {
6924
+ const e = new Error('postmessage: target iframe not found: ' + sel);
6925
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6926
+ }
6927
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
6928
+ const e = new Error('postmessage: target has no contentWindow.postMessage');
6929
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6930
+ }
6931
+ const msg = {
6932
+ MessageId: binding.message,
6933
+ SendTime: Date.now(),
6934
+ Values: Object.assign({}, binding.values || {}),
6935
+ };
6936
+ if (Array.isArray(binding.values_from_args) && args && typeof args === 'object') {
6937
+ for (let i = 0; i < binding.values_from_args.length; i++) {
6938
+ const k = binding.values_from_args[i];
6939
+ if (Object.prototype.hasOwnProperty.call(args, k)) msg.Values[k] = args[k];
6940
+ }
6941
+ }
6942
+ try {
6943
+ iframe.contentWindow.postMessage(msg, binding.target_origin || '*');
6944
+ return Promise.resolve({ ok: true });
6945
+ } catch (e) {
6946
+ return Promise.reject(e);
6947
+ }
6948
+ }
6949
+
6950
+ /* same-origin-window (state): read iframe.contentWindow.<path>. Throws
6951
+ a cross-origin sentinel if accessing the contentWindow fails the
6952
+ same-origin check. In the reference shim we honor an `_sameOrigin`
6953
+ flag the test sets explicitly; in real browsers the property access
6954
+ throws a DOMException SecurityError which we map the same way. */
6955
+ function _v25_backend_same_origin_window(binding /*, args*/) {
6956
+ const sel = binding.target;
6957
+ if (!sel) return Promise.reject(new Error('same-origin-window requires `target`'));
6958
+ const iframe = document.querySelector(sel);
6959
+ if (!iframe) {
6960
+ const e = new Error('same-origin-window: iframe not found: ' + sel);
6961
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6962
+ }
6963
+ if (iframe._sameOrigin === false) {
6964
+ const e = new Error('cross_origin_blocked: iframe is cross-origin');
6965
+ e._code = 'cross_origin_blocked'; return Promise.reject(e);
6966
+ }
6967
+ let cw;
6968
+ try { cw = iframe.contentWindow; }
6969
+ catch (e) {
6970
+ const ex = new Error('cross_origin_blocked: contentWindow access threw');
6971
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6972
+ }
6973
+ if (!cw) {
6974
+ const e = new Error('same-origin-window: contentWindow is null');
6975
+ e._code = 'backend_target_missing'; return Promise.reject(e);
6976
+ }
6977
+ /* Walk the path. */
6978
+ if (!binding.path) return Promise.reject(new Error('same-origin-window requires `path`'));
6979
+ const parts = binding.path.split('.');
6980
+ let cur = cw;
6981
+ for (let i = 0; i < parts.length; i++) {
6982
+ if (cur == null) return Promise.reject(new Error('same-origin-window: path segment ' + parts[i] + ' is null'));
6983
+ try { cur = cur[parts[i]]; }
6984
+ catch (e) {
6985
+ const ex = new Error('cross_origin_blocked: read into contentWindow threw');
6986
+ ex._code = 'cross_origin_blocked'; return Promise.reject(ex);
6987
+ }
6988
+ }
6989
+ if (cur === undefined) {
6990
+ return Promise.reject(new Error('same-origin-window: path resolves to undefined'));
6991
+ }
6992
+ return Promise.resolve(cur);
6993
+ }
6994
+
6995
+ /* script-bridge (state/verb): postmessage with a request, await a
6996
+ correlated response, extract the value. Used by Collabora's
6997
+ CallPythonScript pattern; generalises to any app that exposes a
6998
+ RPC channel over postMessage. */
6999
+ function _v25_backend_script_bridge(binding, args) {
7000
+ const sel = binding.target;
7001
+ if (!sel) return Promise.reject(new Error('script-bridge requires `target`'));
7002
+ const iframe = document.querySelector(sel);
7003
+ if (!iframe) {
7004
+ const e = new Error('script-bridge: iframe not found: ' + sel);
7005
+ e._code = 'backend_target_missing'; return Promise.reject(e);
7006
+ }
7007
+ if (!iframe.contentWindow || typeof iframe.contentWindow.postMessage !== 'function') {
7008
+ const e = new Error('script-bridge: target has no contentWindow.postMessage');
7009
+ e._code = 'backend_target_missing'; return Promise.reject(e);
7010
+ }
7011
+ const responseMsgId = binding.response_match;
7012
+ if (!responseMsgId) return Promise.reject(new Error('script-bridge requires `response_match`'));
7013
+ const timeoutMs = binding.timeout_ms || 5000;
7014
+ const wantValues = Object.assign({}, binding.values || {});
7015
+ if (args && typeof args === 'object') {
7016
+ for (const k in args) wantValues[k] = args[k];
7017
+ }
7018
+ return new Promise(function (resolve, reject) {
7019
+ let settled = false;
7020
+ function onMessage(ev) {
7021
+ if (settled) return;
7022
+ if (!ev || !ev.data) return;
7023
+ if (ev.source !== iframe.contentWindow) return;
7024
+ if (ev.data.MessageId !== responseMsgId) return;
7025
+ settled = true;
7026
+ global.removeEventListener('message', onMessage);
7027
+ clearTimeout(t);
7028
+ /* Resolve with the raw response object. The caller (read or call)
7029
+ applies binding.extract once -- the dispatcher does not, so the
7030
+ extractor is never run twice. */
7031
+ resolve(ev.data);
7032
+ }
7033
+ const t = setTimeout(function () {
7034
+ if (settled) return;
7035
+ settled = true;
7036
+ global.removeEventListener('message', onMessage);
7037
+ reject(new Error('script-bridge: timeout after ' + timeoutMs + 'ms'));
7038
+ }, timeoutMs);
7039
+ global.addEventListener('message', onMessage);
7040
+ /* Fire the request. */
7041
+ iframe.contentWindow.postMessage({
7042
+ MessageId: binding.message,
7043
+ SendTime: Date.now(),
7044
+ Values: wantValues,
7045
+ }, binding.target_origin || '*');
7046
+ });
7047
+ }
7048
+
7049
+ /* synthetic-poll (event): observe declared state paths on a fixed
7050
+ setInterval cadence. On each tick, re-read every observed path,
7051
+ compare to the cached snapshot, and fire the cb with the new
7052
+ snapshot when ANY value differs. Requires only setInterval; no
7053
+ MutationObserver dependency. Teardown clears the interval. */
7054
+ function _v25_subscribe_synthetic_poll(plugin, event_path, binding, cb) {
7055
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
7056
+ throw new Error('synthetic-poll requires `observe: [state_path, ...]`');
7057
+ }
7058
+ const interval = binding.interval_ms || 250;
7059
+ const paths = binding.observe.slice();
7060
+ let cached = null; /* null until first successful snapshot */
7061
+ function snapshot() {
7062
+ const out = {};
7063
+ let allOk = true;
7064
+ const promises = paths.map(function (p) {
7065
+ return read(plugin, p).then(function (v) { out[p] = v; },
7066
+ function () { allOk = false; });
7067
+ });
7068
+ return Promise.all(promises).then(function () {
7069
+ return allOk ? out : null;
7070
+ });
7071
+ }
7072
+ function diffsFromCached(snap) {
7073
+ if (cached == null) return false;
7074
+ for (let i = 0; i < paths.length; i++) {
7075
+ const k = paths[i];
7076
+ /* Strict JSON-shape compare for primitives + objects. */
7077
+ const a = cached[k]; const b = snap[k];
7078
+ if (a !== b) {
7079
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
7080
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
7081
+ }
7082
+ }
7083
+ return false;
7084
+ }
7085
+ /* Prime the cache from the first snapshot so the first real change
7086
+ fires (and not the initial baseline). */
7087
+ snapshot().then(function (first) { if (first != null) cached = first; });
7088
+ const handle = setInterval(function () {
7089
+ snapshot().then(function (snap) {
7090
+ if (snap == null) return;
7091
+ if (cached == null) { cached = snap; return; }
7092
+ if (diffsFromCached(snap)) {
7093
+ cached = snap;
7094
+ try { cb(snap); }
7095
+ finally {
7096
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-poll',
7097
+ _v25_nextRequestId('pe'), true, null, 0);
7098
+ }
7099
+ }
7100
+ });
7101
+ }, interval);
7102
+ return function teardown() { clearInterval(handle); };
7103
+ }
7104
+
7105
+ /* synthetic-mutation (event): observe declared state paths via
7106
+ MutationObserver on the underlying dom-mirror elements. On
7107
+ mutation (with throttle), re-read every observed path and fire
7108
+ the user cb when ANY value changed vs the cached snapshot.
7109
+
7110
+ Requires that every observed path's FIRST state binding be
7111
+ dom-mirror -- only DOM-rooted state is observable via mutations.
7112
+ Mixed manifests (dom-mirror + sdk-call in the same observe list)
7113
+ reject at subscribe time with `invalid`. The manifest author can
7114
+ fall back to synthetic-poll for those cases (declared, not
7115
+ implicit). */
7116
+ function _v25_subscribe_synthetic_mutation(plugin, event_path, binding, cb) {
7117
+ if (typeof MutationObserver === 'undefined') {
7118
+ throw new Error('synthetic-mutation requires MutationObserver in scope');
7119
+ }
7120
+ if (!Array.isArray(binding.observe) || binding.observe.length === 0) {
7121
+ throw new Error('synthetic-mutation requires `observe: [state_path, ...]`');
7122
+ }
7123
+ const throttle = binding.throttle_ms != null ? binding.throttle_ms : 100;
7124
+ const paths = binding.observe.slice();
7125
+ /* Resolve each observed path to a dom-mirror element. Reject the
7126
+ whole subscription if any observed path's primary binding is
7127
+ not dom-mirror -- spec contract, no silent degradation. */
7128
+ const elements = [];
7129
+ const manifest = _v25_plugins[plugin];
7130
+ for (let i = 0; i < paths.length; i++) {
7131
+ const stateChain = manifest.state[paths[i]];
7132
+ if (!stateChain || !stateChain.length) {
7133
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] + '" not declared');
7134
+ e._code = 'invalid'; throw e;
7135
+ }
7136
+ const first = stateChain[0];
7137
+ if (first.backend !== 'dom-mirror') {
7138
+ const e = new Error('synthetic-mutation: observed state "' + paths[i] +
7139
+ '" primary backend must be dom-mirror, got ' + first.backend);
7140
+ e._code = 'invalid'; throw e;
7141
+ }
7142
+ const el = document.querySelector(first.selector);
7143
+ if (el) elements.push(el);
7144
+ }
7145
+ let cached = null;
7146
+ let pending = null;
7147
+ function snapshot() {
7148
+ const out = {};
7149
+ let allOk = true;
7150
+ const promises = paths.map(function (p) {
7151
+ return read(plugin, p).then(function (v) { out[p] = v; },
7152
+ function () { allOk = false; });
7153
+ });
7154
+ return Promise.all(promises).then(function () {
7155
+ return allOk ? out : null;
7156
+ });
7157
+ }
7158
+ function diffsFromCached(snap) {
7159
+ if (cached == null) return false;
7160
+ for (let i = 0; i < paths.length; i++) {
7161
+ const k = paths[i];
7162
+ const a = cached[k]; const b = snap[k];
7163
+ if (a !== b) {
7164
+ if (typeof a !== 'object' || typeof b !== 'object') return true;
7165
+ if (JSON.stringify(a) !== JSON.stringify(b)) return true;
7166
+ }
7167
+ }
7168
+ return false;
7169
+ }
7170
+ function tick() {
7171
+ pending = null;
7172
+ snapshot().then(function (snap) {
7173
+ if (snap == null) return;
7174
+ if (cached == null) { cached = snap; return; }
7175
+ if (diffsFromCached(snap)) {
7176
+ cached = snap;
7177
+ try { cb(snap); }
7178
+ finally {
7179
+ _v25_emitProvenance('event', plugin, event_path, 'synthetic-mutation',
7180
+ _v25_nextRequestId('pe'), true, null, 0);
7181
+ }
7182
+ }
7183
+ });
7184
+ }
7185
+ /* Prime cache from first snapshot. */
7186
+ snapshot().then(function (first) { if (first != null) cached = first; });
7187
+ const observer = new MutationObserver(function () {
7188
+ if (pending != null) return; /* already throttled */
7189
+ pending = setTimeout(tick, throttle);
7190
+ });
7191
+ for (let i = 0; i < elements.length; i++) {
7192
+ observer.observe(elements[i], {
7193
+ attributes: true, childList: true, characterData: true, subtree: true,
7194
+ });
7195
+ }
7196
+ return function teardown() {
7197
+ observer.disconnect();
7198
+ if (pending != null) { clearTimeout(pending); pending = null; }
7199
+ };
7200
+ }
7201
+
7202
+ /* postmessage-listen (event): subscribe to incoming `message` events
7203
+ on the host window, filter by source iframe + MessageId, run the
7204
+ extractor, fire the user callback. Returns a teardown closure. */
7205
+ function _v25_subscribe_postmessage_listen(plugin, event_path, binding, cb) {
7206
+ const sel = binding.source;
7207
+ const wantMsgId = binding.message;
7208
+ if (!wantMsgId) throw new Error('postmessage-listen requires `message`');
7209
+ /* Source filtering: if a selector is given, resolve the iframe NOW.
7210
+ If the iframe is later replaced, the subscription stops matching;
7211
+ that is intentional -- callers can re-subscribe on remount. */
7212
+ const iframe = sel ? document.querySelector(sel) : null;
7213
+ function onMessage(ev) {
7214
+ if (!ev || !ev.data) return;
7215
+ if (ev.data.MessageId !== wantMsgId) return;
7216
+ if (iframe && ev.source !== iframe.contentWindow) return;
7217
+ let value;
7218
+ try {
7219
+ value = binding.extract ? _v25_extract(ev.data, binding.extract, false) : ev.data;
7220
+ } catch (e) {
7221
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
7222
+ _v25_nextRequestId('pe'), false, e.message, 0);
7223
+ return;
7224
+ }
7225
+ try { cb(value); }
7226
+ finally {
7227
+ _v25_emitProvenance('event', plugin, event_path, 'postmessage-listen',
7228
+ _v25_nextRequestId('pe'), true, null, 0);
7229
+ }
7230
+ }
7231
+ global.addEventListener('message', onMessage);
7232
+ return function teardown() { global.removeEventListener('message', onMessage); };
7233
+ }
7234
+
7235
+ /* Registry of dispatchers keyed by backend name. */
7236
+ const _V25_VERB_DISPATCHERS = {
7237
+ 'sdk-call': _v25_backend_sdk_call,
7238
+ 'postmessage': _v25_backend_postmessage,
7239
+ 'script-bridge': _v25_backend_script_bridge,
7240
+ /* same-origin-window and dom-mirror are state-only; the synthetic
7241
+ backends are event-only. */
7242
+ };
7243
+ const _V25_STATE_DISPATCHERS = {
7244
+ 'sdk-call': _v25_backend_sdk_call,
7245
+ 'dom-mirror': _v25_backend_dom_mirror,
7246
+ 'same-origin-window': _v25_backend_same_origin_window,
7247
+ 'script-bridge': _v25_backend_script_bridge,
7248
+ };
7249
+ const _V25_EVENT_SUBSCRIBERS = {
7250
+ 'postmessage-listen': _v25_subscribe_postmessage_listen,
7251
+ 'synthetic-poll': _v25_subscribe_synthetic_poll,
7252
+ 'synthetic-mutation': _v25_subscribe_synthetic_mutation,
7253
+ };
7254
+
7255
+ /* ---------- 15.2 / 15.3 public surface ---------- */
7256
+
7257
+ function _v25_validateManifest(slug, manifest) {
7258
+ if (typeof slug !== 'string' || !slug) {
7259
+ const e = new Error('registerPlugin: slug must be non-empty string');
7260
+ e.code = 'invalid'; throw e;
7261
+ }
7262
+ if (manifest == null || typeof manifest !== 'object') {
7263
+ const e = new Error('registerPlugin: manifest object required');
7264
+ e.code = 'invalid'; throw e;
7265
+ }
7266
+ const verbs = manifest.verbs || {};
7267
+ const states = manifest.state || {};
7268
+ const events = manifest.events || {};
7269
+ /* Verbs: single binding each, backend in vocabulary. */
7270
+ for (const vp in verbs) {
7271
+ const b = verbs[vp];
7272
+ if (!b || typeof b !== 'object' || !b.backend) {
7273
+ const e = new Error('verb "' + vp + '" missing backend');
7274
+ e.code = 'invalid'; throw e;
7275
+ }
7276
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7277
+ const e = new Error('verb "' + vp + '" declares unknown backend: ' + b.backend);
7278
+ e.code = 'backend_unknown'; throw e;
7279
+ }
7280
+ }
7281
+ /* State: array of bindings each. */
7282
+ for (const sp in states) {
7283
+ const arr = states[sp];
7284
+ if (!Array.isArray(arr) || arr.length === 0) {
7285
+ const e = new Error('state "' + sp + '" must be a non-empty array of bindings');
7286
+ e.code = 'invalid'; throw e;
7287
+ }
7288
+ for (let i = 0; i < arr.length; i++) {
7289
+ const b = arr[i];
7290
+ if (!b || typeof b !== 'object' || !b.backend) {
7291
+ const e = new Error('state "' + sp + '" binding[' + i + '] missing backend');
7292
+ e.code = 'invalid'; throw e;
7293
+ }
7294
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7295
+ const e = new Error('state "' + sp + '" binding[' + i + '] unknown backend: ' + b.backend);
7296
+ e.code = 'backend_unknown'; throw e;
7297
+ }
7298
+ }
7299
+ }
7300
+ /* Events: single binding each. */
7301
+ for (const ep in events) {
7302
+ const b = events[ep];
7303
+ if (!b || typeof b !== 'object' || !b.backend) {
7304
+ const e = new Error('event "' + ep + '" missing backend');
7305
+ e.code = 'invalid'; throw e;
7306
+ }
7307
+ if (!_V25_VALID_BACKENDS[b.backend]) {
7308
+ const e = new Error('event "' + ep + '" unknown backend: ' + b.backend);
7309
+ e.code = 'backend_unknown'; throw e;
7310
+ }
7311
+ }
7312
+ }
7313
+
7314
+ function registerPlugin(slug, manifest) {
7315
+ _v25_validateManifest(slug, manifest);
7316
+ /* Re-register replaces -- idempotent for live-reload scenarios. */
7317
+ _v25_plugins[slug] = {
7318
+ slug: slug,
7319
+ verbs: manifest.verbs || {},
7320
+ state: manifest.state || {},
7321
+ events: manifest.events || {},
7322
+ };
7323
+ }
7324
+
7325
+ /* Provenance emit helper -- the kind is one of 'invoked', 'read',
7326
+ 'event'. Detail shape per SPEC.md sec 15.7. */
7327
+ function _v25_emitProvenance(kind, plugin, path, backend, request_id, ok, error, duration_ms, extra) {
7328
+ const detail = {
7329
+ plugin: plugin,
7330
+ backend: backend || null,
7331
+ request_id: request_id,
7332
+ source: 'agent',
7333
+ trusted: false,
7334
+ duration_ms: duration_ms,
7335
+ ok: !!ok,
7336
+ error: error || null,
7337
+ };
7338
+ if (kind === 'invoked') detail.verb_path = path;
7339
+ else if (kind === 'read') detail.state_path = path;
7340
+ else if (kind === 'event') detail.event_path = path;
7341
+ if (extra) {
7342
+ for (const k in extra) detail[k] = extra[k];
7343
+ }
7344
+ try {
7345
+ document.dispatchEvent(new CustomEvent('nac:plugin:' + kind, { detail: detail, bubbles: true }));
7346
+ } catch (_) { /* if document lacks dispatch, swallow */ }
7347
+ }
7348
+
7349
+ function _v25_buildNacError(code, message, extra) {
7350
+ const e = new Error(message);
7351
+ e.code = code;
7352
+ if (extra) for (const k in extra) e[k] = extra[k];
7353
+ return e;
7354
+ }
7355
+
7356
+ function call(plugin, verb_path, args) {
7357
+ const request_id = _v25_nextRequestId('pi');
7358
+ const t0 = Date.now();
7359
+ /* Errors that surface BEFORE any backend dispatch still get a
7360
+ provenance row -- the agent's request happened, it just failed
7361
+ at routing. backend stays null in that case. */
7362
+ if (!_v25_plugins[plugin]) {
7363
+ const err = _v25_buildNacError('plugin_not_registered',
7364
+ 'NAC.call: plugin "' + plugin + '" not registered');
7365
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
7366
+ return Promise.reject(err);
7367
+ }
7368
+ const binding = _v25_plugins[plugin].verbs[verb_path];
7369
+ if (!binding) {
7370
+ const err = _v25_buildNacError('verb_not_declared',
7371
+ 'NAC.call: plugin "' + plugin + '" has no verb "' + verb_path + '"');
7372
+ _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
7373
+ return Promise.reject(err);
7374
+ }
7375
+ const dispatcher = _V25_VERB_DISPATCHERS[binding.backend];
7376
+ if (!dispatcher) {
7377
+ const err = _v25_buildNacError('backend_unknown',
7378
+ 'NAC.call: backend "' + binding.backend + '" not implemented for verbs');
7379
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, err.message, Date.now() - t0);
7380
+ return Promise.reject(err);
7381
+ }
7382
+ return dispatcher(binding, args).then(function (value) {
7383
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, true, null, Date.now() - t0);
7384
+ return value;
7385
+ }, function (err) {
7386
+ /* If the dispatcher tagged the error with a NacError code via
7387
+ `_code`, lift it onto a proper NacError so callers see e.g.
7388
+ backend_target_missing or cross_origin_blocked instead of the
7389
+ raw Error. Provenance always records the human message. */
7390
+ const msg = (err && err.message) || String(err);
7391
+ _v25_emitProvenance('invoked', plugin, verb_path, binding.backend, request_id, false, msg, Date.now() - t0);
7392
+ if (err && err._code) {
7393
+ throw _v25_buildNacError(err._code, msg);
7394
+ }
7395
+ throw err;
7396
+ });
7397
+ }
7398
+
7399
+ function read(plugin, state_path) {
7400
+ const request_id = _v25_nextRequestId('pr');
7401
+ const t0 = Date.now();
7402
+ if (!_v25_plugins[plugin]) {
7403
+ const err = _v25_buildNacError('plugin_not_registered',
7404
+ 'NAC.read: plugin "' + plugin + '" not registered');
7405
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
7406
+ return Promise.reject(err);
7407
+ }
7408
+ const chain = _v25_plugins[plugin].state[state_path];
7409
+ if (!chain) {
7410
+ const err = _v25_buildNacError('state_not_declared',
7411
+ 'NAC.read: plugin "' + plugin + '" has no state "' + state_path + '"');
7412
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
7413
+ return Promise.reject(err);
7414
+ }
7415
+ /* Walk the chain in declared order. First binding to resolve with
7416
+ a non-undefined value wins. Every failure is recorded for the
7417
+ state_unreadable error if none succeed. */
7418
+ const attempts = [];
7419
+ function tryAt(i) {
7420
+ if (i >= chain.length) {
7421
+ const err = _v25_buildNacError('state_unreadable',
7422
+ 'NAC.read: every binding in chain for "' + state_path + '" failed',
7423
+ { attempts: attempts });
7424
+ _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0, { attempts: attempts });
7425
+ return Promise.reject(err);
7426
+ }
7427
+ const binding = chain[i];
7428
+ const dispatcher = _V25_STATE_DISPATCHERS[binding.backend];
7429
+ if (!dispatcher) {
7430
+ attempts.push({ backend: binding.backend, reason: 'dispatcher not implemented for state' });
7431
+ return tryAt(i + 1);
7432
+ }
7433
+ return dispatcher(binding).then(function (raw) {
7434
+ /* For dom-mirror with extract, the dispatcher already applied
7435
+ the extractor and returned the extracted value. For sdk-call
7436
+ with mode:read, the raw value is the path's value -- no
7437
+ extractor needed unless the manifest declared one. */
7438
+ let value;
7439
+ if (binding.backend === 'dom-mirror') {
7440
+ value = raw; /* already extracted */
7441
+ } else if (binding.extract) {
7442
+ try { value = _v25_extract(raw, binding.extract, false); }
7443
+ catch (e) {
7444
+ attempts.push({ backend: binding.backend, reason: e.message });
7445
+ return tryAt(i + 1);
7446
+ }
7447
+ } else {
7448
+ value = raw;
7449
+ }
7450
+ if (value === undefined) {
7451
+ attempts.push({ backend: binding.backend, reason: 'resolved value was undefined' });
7452
+ return tryAt(i + 1);
7453
+ }
7454
+ _v25_emitProvenance('read', plugin, state_path, binding.backend, request_id, true, null, Date.now() - t0);
7455
+ return value;
7456
+ }, function (err) {
7457
+ attempts.push({ backend: binding.backend, reason: err.message || String(err) });
7458
+ return tryAt(i + 1);
7459
+ });
7460
+ }
7461
+ return tryAt(0);
7462
+ }
7463
+
7464
+ /* Active subscription handles -> teardown closures. Allows
7465
+ idempotent unsubscribe by handle reference. */
7466
+ const _v25_subscriptions = new WeakMap();
7467
+ let _v25_sub_counter = 0;
7468
+
7469
+ function subscribe(plugin, event_path, cb) {
7470
+ if (typeof cb !== 'function') {
7471
+ throw _v25_buildNacError('invalid', 'NAC.subscribe: cb must be a function');
7472
+ }
7473
+ if (!_v25_plugins[plugin]) {
7474
+ throw _v25_buildNacError('plugin_not_registered',
7475
+ 'NAC.subscribe: plugin "' + plugin + '" not registered');
7476
+ }
7477
+ const binding = _v25_plugins[plugin].events[event_path];
7478
+ if (!binding) {
7479
+ throw _v25_buildNacError('event_not_declared',
7480
+ 'NAC.subscribe: plugin "' + plugin + '" has no event "' + event_path + '"');
7481
+ }
7482
+ const subscriber = _V25_EVENT_SUBSCRIBERS[binding.backend];
7483
+ if (!subscriber) {
7484
+ throw _v25_buildNacError('backend_unknown',
7485
+ 'NAC.subscribe: backend "' + binding.backend + '" not implemented for events');
7486
+ }
7487
+ let teardown;
7488
+ try { teardown = subscriber(plugin, event_path, binding, cb); }
7489
+ catch (e) {
7490
+ if (e && e._code) throw _v25_buildNacError(e._code, e.message);
7491
+ throw e;
7492
+ }
7493
+ _v25_sub_counter += 1;
7494
+ const handle = {
7495
+ __v25_sub: true,
7496
+ id: _v25_sub_counter,
7497
+ plugin: plugin,
7498
+ event_path: event_path,
7499
+ backend: binding.backend,
7500
+ };
7501
+ _v25_subscriptions.set(handle, teardown);
7502
+ return handle;
7503
+ }
7504
+
7505
+ function unsubscribe(handle) {
7506
+ if (!handle || !handle.__v25_sub) return;
7507
+ const teardown = _v25_subscriptions.get(handle);
7508
+ if (teardown) {
7509
+ try { teardown(); } catch (_) { /* idempotent */ }
7510
+ _v25_subscriptions.delete(handle);
7511
+ }
7512
+ }
7513
+
5783
7514
  /* ---------- Install -------------------------------------------- */
5784
7515
 
5785
7516
  global.NAC = {
5786
7517
  __nac_v1_installed: true,
5787
- version: '2.4.0',
5788
- spec_version: '2.4',
7518
+ version: '2.5.0-alpha.2',
7519
+ spec_version: '2.5',
5789
7520
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
5790
7521
  NAC.register throws on findings (manifest_role_unknown,
5791
7522
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).
@@ -5795,10 +7526,43 @@
5795
7526
  bootstrap before any register() call. See
5796
7527
  guides/MIGRATION_v2.2_to_v2.3.md. */
5797
7528
  STRICT_VALIDATION: true,
7529
+ /* v2.5 / RFC V24-01 -- when true (default), NAC.register throws
7530
+ on the first slug uniqueness violation; the boot-time pass
7531
+ paints a red banner + dispatches nac:fatal. Set false BEFORE
7532
+ any register() call to opt out for a single migration window.
7533
+ The flag is removed in v2.6 (enforcement becomes unconditional). */
7534
+ HARD_DEDUP: true,
5798
7535
  /* registry */
5799
7536
  register: register,
5800
7537
  unregister: unregister,
5801
7538
  manifest: manifest,
7539
+ /* v2.5 V24-02 -- idempotent registration. Use this in SPA hosts
7540
+ where a component remount may call into NAC twice; syncPlugin
7541
+ replaces the manifest instead of appending. */
7542
+ syncPlugin: syncPlugin,
7543
+ /* v2.5 V24-05 -- Agent authority + sudo elevation. The host
7544
+ interposes a confirmation UI between agent dispatch and the
7545
+ action's side effect; request_authority + has_authority let
7546
+ the user grant a time-bounded "sudo" elevation that bypasses
7547
+ confirmations for a scope until TTL expires. */
7548
+ set_confirm_handler: set_confirm_handler,
7549
+ confirm_action: confirm_action,
7550
+ request_authority: request_authority,
7551
+ has_authority: has_authority,
7552
+ revoke_authority: revoke_authority,
7553
+ /* v2.5 V24-04 -- Snapshot versioning + optimistic concurrency.
7554
+ plugin_version + element_state_hash + tree_version appear in
7555
+ describe() output (RFC sec 5.2/5.3). expected_plugin_version
7556
+ / expected_tree_version / expected_element_state_hash on every
7557
+ mutating API reject with NacError('snapshot_stale', ...) when
7558
+ the snapshot is stale. Default STRICT_VERSIONING=false in
7559
+ 2.5.0-alpha.2 so adopters opt in; flips to true in alpha.3
7560
+ once the dispatch hooks finish their soak window. */
7561
+ STRICT_VERSIONING: false,
7562
+ eager_hashing: false,
7563
+ conformance_tier: 'NAC-3-versioned',
7564
+ markHydrationComplete: markHydrationComplete,
7565
+ versionHistory: versionHistory,
5802
7566
  /* v2.3 preview (V23-02): introspection helper that returns the
5803
7567
  list of plugin slugs currently registered (regardless of DOM
5804
7568
  mount state). Used by the interop layer's export_tree to
@@ -5966,9 +7730,10 @@
5966
7730
  assert_event_count: assert_event_count,
5967
7731
  perf_probe: perf_probe,
5968
7732
  replay_pending: replay_pending,
5969
- /* v1.9.0 -- action confirmation (sec 6.2.32) */
5970
- confirm_action: confirm_action,
5971
- set_confirm_handler: set_confirm_handler,
7733
+ /* v1.9.0 -- action confirmation -- superseded by v2.5 V24-05
7734
+ (set_confirm_handler / confirm_action / request_authority /
7735
+ has_authority / revoke_authority exposed earlier in this
7736
+ object). The v1.9 single-handler model is a strict subset. */
5972
7737
  /* v1.9.0 -- action undoable flag (sec 6.2.33) */
5973
7738
  action_undoable: action_undoable,
5974
7739
  action_undo_window_ms: action_undo_window_ms,
@@ -5990,6 +7755,15 @@
5990
7755
  },
5991
7756
  /* errors */
5992
7757
  NacError: NacError,
7758
+ /* v2.5 Block A -- plugin extension contract (SPEC.md sec 15).
7759
+ Agnostic routing for canvas + API surfaces (Collabora, Figma,
7760
+ Miro, Excalidraw, etc). Lives in its own registry; never falls
7761
+ back to v2.4 register() semantics. */
7762
+ registerPlugin: registerPlugin,
7763
+ call: call,
7764
+ read: read,
7765
+ subscribe: subscribe,
7766
+ unsubscribe: unsubscribe,
5993
7767
  };
5994
7768
 
5995
7769
  /* v2.2.1: guard browser-only init so this module is importable in