@nac3/runtime 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2096 @@
1
+ // Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac-v2-extensions.js
2
+ /* ===============================================================
3
+ nac-v2-extensions.js -- NAC v2.0 additive extensions to v1.9
4
+ ---------------------------------------------------------------
5
+ Strict superset: this file LOADS AFTER nac.js v1.9.0 and ATTACHES
6
+ the v2.0 primitives onto window.NAC without modifying the v1.9
7
+ surface. Every v1.9 client keeps working unchanged.
8
+
9
+ Provides:
10
+ - NAC.scope(spec) hierarchical constructor
11
+ - NAC.autoRegister(el, opts) DOM-driven registration
12
+ - NAC.adopt(rule) third-party non-compliant
13
+ - NAC.bridgeShadowRoot(host) Shadow DOM bridge
14
+ - NAC.bridgeIframe(iframeEl, opts) same-vendor iframe bridge
15
+ - NAC.declareVirtual(spec) virtualized lists
16
+ - NAC.captureEphemeral(opts) transient UI capture
17
+ - NAC.setTenantPrefix(slug) multi-tenant naming
18
+ - NAC.declareSitemap(spec) optional sitemap (sec 17)
19
+ - NAC.attestUserGesture(opts) isTrusted attestation
20
+ - NAC.t(key, opts?) i18n resolver
21
+ - NAC.registerCatalog(catalog) i18n catalog registration
22
+ - NAC.locale(code?) locale getter/setter
23
+ - NAC.setSupportedLocales(arr) extend supported list
24
+ - NAC.setRTLLocales(arr) extend RTL list
25
+ - NAC.set_provenance_secret(secret) HMAC secret registration
26
+
27
+ And tightens (only at NAC-3):
28
+ - check_canonical_shape: agent must sign + user_gesture_attested
29
+ - validate_global: i18n_strict mode
30
+
31
+ Spec: spec/NAC-v2.0.md + RFC_v2.0.0.md
32
+ ASCII-only.
33
+ =============================================================== */
34
+ (function (global) {
35
+ 'use strict';
36
+ if (!global.NAC) {
37
+ console.error('[NAC v2] requires nac.js v1.9.0+ to be loaded first');
38
+ return;
39
+ }
40
+ if (global.NAC.__nac_v2_installed) return;
41
+ global.NAC.__nac_v2_installed = true;
42
+
43
+ var NAC = global.NAC;
44
+ var SEPARATOR = '.';
45
+ var MAX_DEPTH = 6;
46
+ var WARN_DEPTH = 4;
47
+
48
+ /* ------------------------------------------------------------- locales */
49
+
50
+ var SUPPORTED_LOCALES_DEFAULT = ['es','en','pt','fr','it','de','ja','zh','hi','ar'];
51
+ var RTL_LOCALES_DEFAULT = ['ar','he','fa','ur'];
52
+ var _supported = SUPPORTED_LOCALES_DEFAULT.slice();
53
+ var _rtl = RTL_LOCALES_DEFAULT.slice();
54
+ var _currentLocale = (function () {
55
+ try {
56
+ var l = (document.documentElement.getAttribute('lang')
57
+ || navigator.language
58
+ || 'es').slice(0, 2).toLowerCase();
59
+ return _supported.indexOf(l) >= 0 ? l : 'es';
60
+ } catch (_) { return 'es'; }
61
+ })();
62
+ var _catalog = Object.create(null);
63
+
64
+ function setSupportedLocales(arr) {
65
+ if (!Array.isArray(arr) || !arr.length) {
66
+ throw new Error('[NAC v2] setSupportedLocales requires non-empty array');
67
+ }
68
+ _supported = arr.slice();
69
+ }
70
+ function setRTLLocales(arr) {
71
+ if (!Array.isArray(arr)) throw new Error('[NAC v2] setRTLLocales requires array');
72
+ _rtl = arr.slice();
73
+ }
74
+ /* v2.0-rc3 (Claude T5-F4): some hosts ship multi-locale
75
+ content in one DOM (e.g. user in 'ar' viewing untranslated
76
+ English log lines); auto-flipping dir=rtl on documentElement
77
+ globally breaks the LTR content's BIDI. Hosts opt out via
78
+ setAutoRTL(false), then manage dir on a sub-tree element. */
79
+ var _autoRTL = true;
80
+ function setAutoRTL(enabled) { _autoRTL = !!enabled; }
81
+
82
+ function locale(code) {
83
+ if (code === undefined) return _currentLocale;
84
+ if (_supported.indexOf(code) < 0) {
85
+ console.warn('[NAC v2] locale', code, 'not in supported list');
86
+ }
87
+ _currentLocale = code;
88
+ /* Auto-apply dir=rtl unless host opted out via setAutoRTL(false). */
89
+ if (_autoRTL) {
90
+ try {
91
+ if (_rtl.indexOf(code) >= 0) {
92
+ document.documentElement.setAttribute('dir', 'rtl');
93
+ } else {
94
+ document.documentElement.removeAttribute('dir');
95
+ }
96
+ } catch (_) {}
97
+ }
98
+ document.dispatchEvent(new CustomEvent('nac:locale_changed', {
99
+ detail: { locale: code, autoRTL: _autoRTL }, bubbles: true
100
+ }));
101
+ }
102
+ function registerCatalog(obj) {
103
+ if (!obj || typeof obj !== 'object') {
104
+ throw new Error('[NAC v2] registerCatalog requires object');
105
+ }
106
+ Object.keys(obj).forEach(function (k) { _catalog[k] = obj[k]; });
107
+ }
108
+ function t(key, opts) {
109
+ opts = opts || {};
110
+ var loc = opts.locale || _currentLocale;
111
+ var entry = _catalog[key];
112
+ if (!entry) return opts.fallback || key;
113
+ if (entry[loc]) return entry[loc];
114
+ /* Fallback chain: requested -> es -> en -> first available */
115
+ if (entry.es) return entry.es;
116
+ if (entry.en) return entry.en;
117
+ var firstKey = Object.keys(entry)[0];
118
+ return firstKey ? entry[firstKey] : (opts.fallback || key);
119
+ }
120
+
121
+ /* ------------------------------------------------------------- HMAC */
122
+
123
+ var _provenanceSecrets = [];
124
+ function set_provenance_secret(s) {
125
+ if (typeof s === 'string') _provenanceSecrets = [s];
126
+ else if (Array.isArray(s)) _provenanceSecrets = s.slice();
127
+ else if (s == null) _provenanceSecrets = [];
128
+ else throw new Error('[NAC v2] set_provenance_secret expects string|string[]');
129
+ /* v2.0-rc3 (Claude T6-F2): warm the crypto path now that we
130
+ have a secret registered; first agent sign won't pay the
131
+ cold-start cost. */
132
+ if (_provenanceSecrets[0] && typeof NAC.sign_provenance === 'function') {
133
+ try {
134
+ NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
135
+ .catch(function () {});
136
+ } catch (_) {}
137
+ }
138
+ }
139
+ /* sign / verify provenance helpers exist in v1.9 already; reuse them */
140
+ function _hasSecrets() { return _provenanceSecrets.length > 0; }
141
+
142
+ async function _verify_with_registered(detail) {
143
+ if (!_hasSecrets()) return false;
144
+ if (typeof NAC.verify_provenance !== 'function') return false;
145
+ for (var i = 0; i < _provenanceSecrets.length; i++) {
146
+ try {
147
+ var ok = await NAC.verify_provenance(detail, _provenanceSecrets[i]);
148
+ if (ok) return true;
149
+ } catch (_) {}
150
+ }
151
+ return false;
152
+ }
153
+
154
+ /* ------------------------------------------------------------- isTrusted */
155
+
156
+ /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): the gesture buffer is now
157
+ bound to the originating event's composedPath, NOT a global
158
+ flag. _readGestureAttested(forElement) verifies that the
159
+ element being invoked is in the captured path before honoring
160
+ attested. Without this, any user click anywhere on the page
161
+ leaked attested=true to ANY subsequent _invoke within the
162
+ freshness window -- the FOURTH impersonation path Claude
163
+ surfaced.
164
+
165
+ Additionally: GESTURE_FRESH_MS reduced 100ms -> 16ms (one
166
+ animation frame). Genuine click handlers run synchronously
167
+ (or via microtask), well within 16ms. Promise-resolved-later
168
+ handlers no longer count as user-attested -- which is the
169
+ security-correct behaviour. */
170
+ var _lastGestureTrusted = null;
171
+ var _lastGestureTime = 0;
172
+ var _lastGesturePath = null; /* Array<EventTarget> from e.composedPath() */
173
+ var GESTURE_FRESH_MS = 16; /* was 100 in rc2 */
174
+
175
+ /* v2.0-rc2 (Mistral T4-F1): mobile WebView contexts (Cordova,
176
+ Capacitor, React Native WebView) have inconsistent isTrusted
177
+ semantics. Hosts running in those environments register a
178
+ custom derivation function via setMobileWebViewAttestation so
179
+ the platform-specific signal substitutes for browser
180
+ event.isTrusted. */
181
+ var _mobileWebViewAttestor = null;
182
+
183
+ function setMobileWebViewAttestation(fn) {
184
+ if (fn != null && typeof fn !== 'function') {
185
+ throw new Error('[NAC v2] setMobileWebViewAttestation expects function|null');
186
+ }
187
+ _mobileWebViewAttestor = fn;
188
+ }
189
+
190
+ function _captureGestureFromDom() {
191
+ var handler = function (e) {
192
+ /* When a custom WebView attestor is registered, its return
193
+ value (or function call given the event) substitutes the
194
+ raw isTrusted reading. */
195
+ if (_mobileWebViewAttestor) {
196
+ try {
197
+ var attested = !!_mobileWebViewAttestor(e);
198
+ _lastGestureTrusted = attested;
199
+ } catch (err) {
200
+ _lastGestureTrusted = !!e.isTrusted;
201
+ }
202
+ } else {
203
+ _lastGestureTrusted = !!e.isTrusted;
204
+ }
205
+ _lastGestureTime = Date.now();
206
+ /* v2.0-rc3: capture the composed path so _invoke can verify
207
+ identity. Polyfill for ancient browsers via target ancestor
208
+ walk (composedPath() ships in all browsers >= 2018). */
209
+ try {
210
+ if (typeof e.composedPath === 'function') {
211
+ _lastGesturePath = e.composedPath();
212
+ } else {
213
+ _lastGesturePath = [];
214
+ var n = e.target;
215
+ while (n) { _lastGesturePath.push(n); n = n.parentNode; }
216
+ }
217
+ } catch (_) {
218
+ _lastGesturePath = e.target ? [e.target] : [];
219
+ }
220
+ };
221
+ ['click','keydown','keyup','touchstart','pointerdown'].forEach(function (n) {
222
+ document.addEventListener(n, handler, { capture: true, passive: true });
223
+ });
224
+ }
225
+ if (document.readyState === 'loading') {
226
+ document.addEventListener('DOMContentLoaded', _captureGestureFromDom);
227
+ } else {
228
+ _captureGestureFromDom();
229
+ }
230
+
231
+ /* v2.0-rc3: _readGestureAttested now requires the element being
232
+ invoked. Returns the captured attested flag ONLY if:
233
+ (a) the gesture is within GESTURE_FRESH_MS (16ms) AND
234
+ (b) `forElement` is in the captured composedPath (or no
235
+ element was captured -- legacy callers).
236
+ Returns null in all other cases (matrix treats null as
237
+ not-attested -> 'user' source rejected at NAC-3). */
238
+ function _readGestureAttested(forElement) {
239
+ if (Date.now() - _lastGestureTime > GESTURE_FRESH_MS) return null;
240
+ if (!forElement) return _lastGestureTrusted; /* legacy fallback */
241
+ if (!_lastGesturePath || !_lastGesturePath.length) return _lastGestureTrusted;
242
+ /* Identity check: only honor attested when the target element
243
+ is in the originating event's path. Closes Claude T4-F1. */
244
+ if (_lastGesturePath.indexOf(forElement) >= 0) {
245
+ return _lastGestureTrusted;
246
+ }
247
+ return null;
248
+ }
249
+
250
+ /* Buffer for validate_global_v2 to surface findings emitted
251
+ by runtime guards (added rc6). Declared BEFORE
252
+ attestUserGesture so the override-blocking branch can
253
+ push into it without a temporal-dead-zone error. */
254
+ var _validatorFindings = [];
255
+
256
+ var _scriptOverride = null;
257
+ function attestUserGesture(opts) {
258
+ opts = opts || {};
259
+ /* 2026-05-09 (Claude R6 MEDIUM): the API was previously a
260
+ complete bypass for the identity-binding check. A page-
261
+ level script could call
262
+ attestUserGesture({trusted:true, type:'user'}) and the
263
+ next invoke would inherit attested=true with NO identity
264
+ binding to a real isTrusted gesture path. The override
265
+ was specified as testing-only (sec 15.10) but the runtime
266
+ accepted arbitrary opts.type values.
267
+
268
+ Fix: opts.type may ONLY be 'script' or 'agent'. Attempts
269
+ to claim 'user' (the only type that maps to source.type=
270
+ 'user' downstream) are blocked at runtime AND emit a
271
+ finding code script_override_claims_user that
272
+ validate_global_v2() reports. The override remains
273
+ useful for headless test fixtures (testing-only as the
274
+ spec always said) but cannot launder a script-origin
275
+ action as a user-origin one. */
276
+ var requestedType = (typeof opts.type === 'string' && opts.type) ? opts.type : 'script';
277
+ if (requestedType === 'user') {
278
+ _validatorFindings.push({
279
+ code: 'script_override_claims_user',
280
+ severity: 'error',
281
+ timestamp: Date.now(),
282
+ note: 'attestUserGesture rejected opts.type="user" -- only script/agent permitted'
283
+ });
284
+ console.warn('[NAC v2] attestUserGesture: opts.type="user" rejected; '
285
+ + 'forcing type="script". Identity-binding bypass blocked.');
286
+ requestedType = 'script';
287
+ }
288
+ if (requestedType !== 'script' && requestedType !== 'agent') {
289
+ throw new Error('[NAC v2] attestUserGesture: opts.type must be '
290
+ + '"script" or "agent" (got "' + requestedType + '")');
291
+ }
292
+ _scriptOverride = {
293
+ trusted: !!opts.trusted,
294
+ type: requestedType,
295
+ ts: Date.now()
296
+ };
297
+ }
298
+
299
+ /* ------------------------------------------------------------- perf tolerance */
300
+
301
+ /* v2.0-rc2 (Grok+Mistral T6-F1): default throttle bumped 50ms ->
302
+ 100ms after concurrent reviewer feedback that 50ms drops
303
+ events on bursty UIs. set_perf_tolerance({mutation_throttle_ms,
304
+ describe_target_ms, etc}) lets hosts tune for their workload. */
305
+ var _perfTolerance = {
306
+ mutation_throttle_ms: 100, /* was 50 in rc1 */
307
+ describe_target_ms: 50, /* was 30 in rc1 (Mistral T6-F2) */
308
+ describe_hard_fail_ms: 150, /* was 100 in rc1 */
309
+ adopt_hard_fail_ms: 20, /* was 15 in rc1 */
310
+ autoregister_hard_fail_ms: 5,
311
+ /* v2.0-rc4 (Claude T8.1 middle ground): hard-fail RATE
312
+ tightened from 5%/5s (rc2/rc3) to 2%/5s (rc4). Same
313
+ window width, tighter rate. Rationale: 5% over 5s = ~1
314
+ hitched describe() per 20s on Snapdragon 6 Gen 1 = breaks
315
+ SR reading flow; 1%/10s window too long for bursty
316
+ stalls. 2%/5s captures sustained AND bursty correctly.
317
+ Tunable for hosts that need looser thresholds. */
318
+ perf_budget_fail_rate_pct: 2, /* was implicit 5% in rc3 */
319
+ perf_budget_window_ms: 5000 /* unchanged */
320
+ };
321
+
322
+ function set_perf_tolerance(opts) {
323
+ if (!opts || typeof opts !== 'object') {
324
+ throw new Error('[NAC v2] set_perf_tolerance expects object');
325
+ }
326
+ Object.keys(opts).forEach(function (k) {
327
+ if (k in _perfTolerance && typeof opts[k] === 'number' && opts[k] > 0) {
328
+ _perfTolerance[k] = opts[k];
329
+ }
330
+ });
331
+ }
332
+ function get_perf_tolerance() { return Object.assign({}, _perfTolerance); }
333
+
334
+ /* ------------------------------------------------------------- validation tolerance */
335
+
336
+ /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): NAC-3 default i18n
337
+ severity bumped from 'error' to 'warn' after concurrent
338
+ reviewer feedback that mandatory at NAC-3 blocks incremental
339
+ SaaS rollouts. Hosts that want strict 'error' behaviour opt
340
+ in via set_validation_tolerance({i18n_strict: 'error'}). */
341
+ var _validationTolerance = {
342
+ i18n_strict: 'warn', /* 'warn' (default) | 'error' | 'silent' */
343
+ /* v2.0-rc4 (Mistral T7-F1): iframe_strict opt-in turns on
344
+ NAC-3 fail-closed for bridgeIframe. Default 'warn' = rc3
345
+ fail-open behaviour preserved for NAC-1/NAC-2. */
346
+ iframe_strict: 'warn', /* 'warn' (default) | 'error' */
347
+ /* v2.0-rc4 (Claude T8.2): autoderived_action signals when
348
+ autoRegister inferred the action without an explicit
349
+ data-nac-action attribute. Default 'warn'; opt-in 'error'
350
+ for regulated-environment audit pipelines. */
351
+ autoderived_action: 'warn' /* 'warn' (default) | 'error' | 'silent' */
352
+ };
353
+
354
+ function set_validation_tolerance(opts) {
355
+ if (!opts || typeof opts !== 'object') {
356
+ throw new Error('[NAC v2] set_validation_tolerance expects object');
357
+ }
358
+ if (opts.i18n_strict && ['warn', 'error', 'silent'].indexOf(opts.i18n_strict) >= 0) {
359
+ _validationTolerance.i18n_strict = opts.i18n_strict;
360
+ }
361
+ if (opts.iframe_strict && ['warn', 'error'].indexOf(opts.iframe_strict) >= 0) {
362
+ _validationTolerance.iframe_strict = opts.iframe_strict;
363
+ }
364
+ if (opts.autoderived_action && ['warn', 'error', 'silent'].indexOf(opts.autoderived_action) >= 0) {
365
+ _validationTolerance.autoderived_action = opts.autoderived_action;
366
+ }
367
+ }
368
+ function get_validation_tolerance() { return Object.assign({}, _validationTolerance); }
369
+
370
+ /* ------------------------------------------------------------- scope */
371
+
372
+ var _scopes = Object.create(null);
373
+
374
+ function _validateLeaf(slug) {
375
+ if (!slug || typeof slug !== 'string') {
376
+ throw new Error('[NAC v2] slug required');
377
+ }
378
+ /* v2.0-rc3 (DeepSeek T3.1): empty string passes the typeof
379
+ check + indexOf check, then produces malformed slugs. Reject
380
+ it explicitly. */
381
+ if (slug.length === 0) {
382
+ throw new Error('[NAC v2] slug_invalid: empty string');
383
+ }
384
+ if (slug.indexOf(SEPARATOR) >= 0) {
385
+ throw new Error('[NAC v2] slug_invalid: contains "' + SEPARATOR + '"');
386
+ }
387
+ }
388
+
389
+ function scope(spec) {
390
+ spec = spec || {};
391
+ _validateLeaf(spec.slug);
392
+ return _makeSubScope(spec.slug, [spec.slug], spec);
393
+ }
394
+
395
+ function _makeSubScope(currentSlug, chain, spec) {
396
+ var depth = chain.length;
397
+ if (depth > MAX_DEPTH) {
398
+ throw new Error('[NAC v2] depth_exceeded: ' + chain.join(SEPARATOR));
399
+ }
400
+ if (depth === WARN_DEPTH + 1) {
401
+ document.dispatchEvent(new CustomEvent('nac:depth_warn', {
402
+ detail: { path: chain.join(SEPARATOR), depth: depth }, bubbles: true
403
+ }));
404
+ }
405
+
406
+ var node = {
407
+ id: chain.join(SEPARATOR),
408
+ depth: depth,
409
+ label_i18n: spec ? spec.label_i18n || null : null,
410
+ };
411
+ /* v2.0-rc3 (Claude T3.1): track intermediate nodes that carry
412
+ a label_i18n so describe_v2 can expose them. Leaf nodes go
413
+ through register() and end up in _scopes; intermediate
414
+ (non-leaf) nodes need a separate index. */
415
+ if (node.label_i18n) {
416
+ _intermediateScopes[node.id] = {
417
+ depth: depth,
418
+ label_i18n: node.label_i18n
419
+ };
420
+ }
421
+ Object.assign(node, {
422
+
423
+ scope: function (childSpec) {
424
+ _validateLeaf(childSpec.slug);
425
+ var childChain = chain.concat([childSpec.slug]);
426
+ return _makeSubScope(childSpec.slug, childChain, childSpec);
427
+ },
428
+
429
+ register: function (regSpec) {
430
+ _validateLeaf(regSpec.slug);
431
+ var fullSlug = chain.concat([regSpec.slug]).join(SEPARATOR);
432
+
433
+ var entry = {
434
+ slug: fullSlug,
435
+ intent: regSpec.intent || 'navigate',
436
+ source: regSpec.source || 'human',
437
+ label_i18n: regSpec.label_i18n || null,
438
+ desc_i18n: regSpec.desc_i18n || null,
439
+ a11y_hint: regSpec.a11y_hint || null,
440
+ irreversible:!!regSpec.irreversible,
441
+ role: regSpec.role || null,
442
+ element: regSpec.element || null,
443
+ handler: typeof regSpec.handler === 'function' ? regSpec.handler : null,
444
+ autoderived: false,
445
+ parent_chain: chain.slice(),
446
+ registered_at: Date.now()
447
+ };
448
+
449
+ /* Idempotent: re-register with same slug + same element silently
450
+ updates; re-register with same slug + different element warns. */
451
+ var prior = _scopes[fullSlug];
452
+ if (prior) {
453
+ if (prior.element === entry.element) {
454
+ _scopes[fullSlug] = entry;
455
+ } else {
456
+ document.dispatchEvent(new CustomEvent('nac:duplicate_warn', {
457
+ detail: { slug: fullSlug, prior: prior, next: entry }, bubbles: true
458
+ }));
459
+ _scopes[fullSlug] = entry; /* last-wins */
460
+ }
461
+ } else {
462
+ _scopes[fullSlug] = entry;
463
+ }
464
+
465
+ if (entry.element) {
466
+ entry.element.setAttribute('data-nac-id', fullSlug);
467
+ entry.element.setAttribute('data-nac-parent', chain.join(' '));
468
+ if (entry.role) entry.element.setAttribute('role', entry.role);
469
+ if (entry.label_i18n) {
470
+ var lbl = t.bind(null);
471
+ var labelText = (function () {
472
+ if (entry.label_i18n[_currentLocale]) return entry.label_i18n[_currentLocale];
473
+ if (entry.label_i18n.es) return entry.label_i18n.es;
474
+ if (entry.label_i18n.en) return entry.label_i18n.en;
475
+ return fullSlug;
476
+ })();
477
+ if (!entry.element.getAttribute('aria-label')) {
478
+ entry.element.setAttribute('aria-label', labelText);
479
+ }
480
+ }
481
+ if (entry.irreversible) {
482
+ entry.element.setAttribute('data-nac-irreversible', '1');
483
+ }
484
+ }
485
+
486
+ return {
487
+ id: fullSlug,
488
+ invoke: function (params) { return _invoke(fullSlug, params); }
489
+ };
490
+ }
491
+ });
492
+ return node;
493
+ }
494
+
495
+ function _invoke(slug, params) {
496
+ var entry = _scopes[slug];
497
+ if (!entry) return Promise.reject(new Error('unknown_slug:' + slug));
498
+ var src = (params && params.source) || entry.source || 'human';
499
+
500
+ var attested;
501
+ if (_scriptOverride && Date.now() - _scriptOverride.ts < GESTURE_FRESH_MS) {
502
+ attested = _scriptOverride.trusted;
503
+ _scriptOverride = null;
504
+ } else {
505
+ /* v2.0-rc3 (Claude T4-F1 BLOCKER fix): pass entry.element so
506
+ _readGestureAttested can verify identity, not just freshness.
507
+ Closes the gesture-buffer leak. */
508
+ attested = _readGestureAttested(entry.element);
509
+ }
510
+
511
+ /* v2.0-rc3 (Claude T4-F3): os_level pass-through. When source is
512
+ 'agent' AND host opts in (e.g. for Computer Use telemetry),
513
+ params.os_level is propagated into provenance for audit. */
514
+ var osLevel = (params && params.os_level === true) ? true : null;
515
+
516
+ var prov = {
517
+ slug: slug,
518
+ intent: entry.intent,
519
+ source: src,
520
+ type: src,
521
+ user_gesture_attested: attested,
522
+ ts: Date.now(),
523
+ params: params || null
524
+ };
525
+ if (osLevel === true) prov.os_level = true;
526
+
527
+ /* Agent + irreversible -> decline path */
528
+ if (src === 'agent' && entry.irreversible) {
529
+ var hint = entry.a11y_hint
530
+ ? (entry.a11y_hint[_currentLocale] || entry.a11y_hint.es)
531
+ : null;
532
+ document.dispatchEvent(new CustomEvent('nac:command_rejected', {
533
+ detail: { slug: slug, reason: 'agent_declined_irreversible', hint: hint, ts: Date.now() },
534
+ bubbles: true
535
+ }));
536
+ return Promise.reject(new Error('agent_declined_irreversible'));
537
+ }
538
+
539
+ /* Sign if we can (agent must) */
540
+ var signPromise;
541
+ if (typeof NAC.sign_provenance === 'function' && _provenanceSecrets[0]) {
542
+ signPromise = NAC.sign_provenance(prov, _provenanceSecrets[0]);
543
+ } else {
544
+ signPromise = Promise.resolve(null);
545
+ }
546
+
547
+ return signPromise.then(function (sig) {
548
+ if (sig) prov.signature = sig;
549
+ var detail = { provenance: prov, signature: sig, version: 'v2.0' };
550
+ document.dispatchEvent(new CustomEvent('nac:command_pending', {
551
+ detail: detail, bubbles: true
552
+ }));
553
+ var run = entry.handler
554
+ ? Promise.resolve().then(function () { return entry.handler(params || {}, detail); })
555
+ : Promise.resolve(null);
556
+ return run.then(function (result) {
557
+ document.dispatchEvent(new CustomEvent('nac:command_done', {
558
+ detail: Object.assign({}, detail, { result: result }), bubbles: true
559
+ }));
560
+ return result;
561
+ }, function (err) {
562
+ document.dispatchEvent(new CustomEvent('nac:command_failed', {
563
+ detail: Object.assign({}, detail, { error: String(err) }), bubbles: true
564
+ }));
565
+ throw err;
566
+ });
567
+ });
568
+ }
569
+
570
+ /* ------------------------------------------------------------- autoRegister */
571
+
572
+ function _findScopeAncestor(el) {
573
+ var anc = el.parentElement;
574
+ while (anc) {
575
+ if (anc.hasAttribute && anc.hasAttribute('data-nac-scope')) {
576
+ return anc.getAttribute('data-nac-scope');
577
+ }
578
+ anc = anc.parentElement;
579
+ }
580
+ return null;
581
+ }
582
+
583
+ function _deriveLeafSlug(el) {
584
+ if (el.id) return el.id;
585
+ if (el.dataset && el.dataset.nacAction) return el.dataset.nacAction;
586
+ /* v2.0-rc3 (Claude T3.2): the rc1 fallback hashed only
587
+ el.outerHTML.slice(0,100) which produces identical hashes for
588
+ 400 cards rendered from the same template (template prefixes
589
+ are byte-identical). The fix mixes in: tag name + textContent
590
+ (more discriminating) + position-in-parent (guaranteed
591
+ unique). Collisions still possible when two truly identical
592
+ elements exist; idempotent register handles those by
593
+ last-wins-same-element. */
594
+ var src = '';
595
+ src += el.tagName || '';
596
+ src += '|';
597
+ src += (el.textContent || '').trim().slice(0, 60);
598
+ src += '|';
599
+ if (el.parentNode) {
600
+ try {
601
+ var siblings = el.parentNode.children;
602
+ for (var s = 0; s < siblings.length; s++) {
603
+ if (siblings[s] === el) { src += '@' + s; break; }
604
+ }
605
+ } catch (_) {}
606
+ }
607
+ src += '|';
608
+ src += (el.outerHTML || '').slice(0, 80);
609
+ var h = 0;
610
+ for (var i = 0; i < src.length; i++) {
611
+ h = ((h << 5) - h) + src.charCodeAt(i);
612
+ h |= 0;
613
+ }
614
+ return 'auto_' + (Math.abs(h)).toString(36);
615
+ }
616
+
617
+ function _deriveRole(el) {
618
+ var tag = el.tagName.toLowerCase();
619
+ var attrRole = el.getAttribute('role');
620
+ if (attrRole) return attrRole;
621
+ if (tag === 'button') return 'button';
622
+ if (tag === 'a' && el.hasAttribute('href')) return 'link';
623
+ if (tag === 'input') {
624
+ var t = el.getAttribute('type') || 'text';
625
+ if (t === 'checkbox' || t === 'radio') return 'toggle';
626
+ return 'field';
627
+ }
628
+ if (tag === 'textarea') return 'field';
629
+ if (tag === 'select') return 'select';
630
+ return 'interactive';
631
+ }
632
+
633
+ function _deriveLabel(el) {
634
+ var aria = el.getAttribute('aria-label');
635
+ if (aria) return aria;
636
+ return (el.textContent || '').trim().slice(0, 200);
637
+ }
638
+
639
+ function autoRegister(el, opts) {
640
+ opts = opts || {};
641
+ if (!el) throw new Error('[NAC v2] autoRegister requires element');
642
+ var leaf = _deriveLeafSlug(el);
643
+ var parentSlug = opts.inheritScope !== false ? _findScopeAncestor(el) : null;
644
+ /* v2.0-rc3 (DeepSeek T3.2): warn on orphan slugs (no parent
645
+ scope ancestor found). Easy to happen on pages with multiple
646
+ dynamic regions; without a warn the slug ends up huerfano
647
+ silently. */
648
+ if (opts.inheritScope !== false && !parentSlug) {
649
+ try {
650
+ document.dispatchEvent(new CustomEvent('nac:autoregister_orphan_warn', {
651
+ detail: { leaf: leaf, element: el }, bubbles: true
652
+ }));
653
+ } catch (_) {}
654
+ }
655
+ var fullSlug = parentSlug ? (parentSlug + SEPARATOR + leaf) : leaf;
656
+
657
+ /* i18n strict check */
658
+ var i18nKey = el.getAttribute('data-i18n-key');
659
+ var labelI18n = null;
660
+ var autoderived = false;
661
+ if (i18nKey && _catalog[i18nKey]) {
662
+ labelI18n = _catalog[i18nKey];
663
+ } else if (i18nKey) {
664
+ /* Key declared but catalog missing the entry */
665
+ if (opts.i18n_strict !== false) {
666
+ document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
667
+ detail: { slug: fullSlug, key: i18nKey, reason: 'catalog_missing' },
668
+ bubbles: true
669
+ }));
670
+ return null;
671
+ }
672
+ } else {
673
+ /* No data-i18n-key. In strict (default) we skip; in permissive
674
+ we mono-locale fallback */
675
+ if (opts.i18n_strict !== false && opts.i18n_strict !== 'permissive') {
676
+ document.dispatchEvent(new CustomEvent('nac:i18n_skipped', {
677
+ detail: { slug: fullSlug, reason: 'no_data_i18n_key' },
678
+ bubbles: true
679
+ }));
680
+ return null;
681
+ }
682
+ var derivedLabel = _deriveLabel(el);
683
+ labelI18n = {};
684
+ labelI18n[_currentLocale] = derivedLabel;
685
+ autoderived = true;
686
+ }
687
+
688
+ var role = (opts.derive && opts.derive.role === 'auto')
689
+ ? _deriveRole(el)
690
+ : (opts.derive && opts.derive.role) || _deriveRole(el);
691
+
692
+ var entry = {
693
+ slug: fullSlug,
694
+ intent: 'navigate',
695
+ source: 'human',
696
+ label_i18n: labelI18n,
697
+ role: role,
698
+ element: el,
699
+ autoderived: autoderived,
700
+ registered_at: Date.now()
701
+ };
702
+ _scopes[fullSlug] = entry;
703
+ el.setAttribute('data-nac-id', fullSlug);
704
+ if (parentSlug) {
705
+ el.setAttribute('data-nac-parent', parentSlug.split(SEPARATOR).join(' '));
706
+ }
707
+ if (role && !el.getAttribute('role')) el.setAttribute('role', role);
708
+ if (labelI18n && !el.getAttribute('aria-label')) {
709
+ var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
710
+ el.setAttribute('aria-label', lab);
711
+ }
712
+ return entry;
713
+ }
714
+
715
+ /* MutationObserver-based watch */
716
+ var _watchObservers = [];
717
+ autoRegister.watch = function (containerEl, opts) {
718
+ opts = opts || {};
719
+ /* v2.0-rc2: default throttle pulled from _perfTolerance (100ms),
720
+ caller may still override per-watch via opts.throttleMs. */
721
+ var throttleMs = opts.throttleMs || _perfTolerance.mutation_throttle_ms;
722
+ var pending = false;
723
+ var queue = [];
724
+
725
+ /* v2.0-rc3 (Claude T6-F1): chunk batches > 50 elements via
726
+ requestIdleCallback (or setTimeout fallback) to stay under
727
+ the cumulative-batch perf budget. Per-element cost stays the
728
+ same; main thread is yielded between sub-batches so the
729
+ page stays responsive. */
730
+ var CHUNK_SIZE = 50;
731
+ function _yieldThen(fn) {
732
+ if (typeof window.requestIdleCallback === 'function') {
733
+ window.requestIdleCallback(fn, { timeout: 100 });
734
+ } else {
735
+ setTimeout(fn, 0);
736
+ }
737
+ }
738
+ function processOne(entry) {
739
+ if (entry.added) {
740
+ if (entry.el.hasAttribute && entry.el.hasAttribute('data-nac-action')) {
741
+ try { autoRegister(entry.el, opts); } catch (_) {}
742
+ }
743
+ /* Descend into added subtree */
744
+ if (entry.el.querySelectorAll) {
745
+ entry.el.querySelectorAll('[data-nac-action]').forEach(function (x) {
746
+ try { autoRegister(x, opts); } catch (_) {}
747
+ });
748
+ }
749
+ } else {
750
+ /* Removed: clean manifest */
751
+ if (entry.el.getAttribute) {
752
+ var slug = entry.el.getAttribute('data-nac-id');
753
+ if (slug && _scopes[slug]) delete _scopes[slug];
754
+ }
755
+ }
756
+ }
757
+ function flush() {
758
+ var batch = queue.splice(0);
759
+ pending = false;
760
+ if (batch.length <= CHUNK_SIZE) {
761
+ batch.forEach(processOne);
762
+ return;
763
+ }
764
+ /* Chunked path: yield between sub-batches. */
765
+ var idx = 0;
766
+ function step() {
767
+ var end = Math.min(idx + CHUNK_SIZE, batch.length);
768
+ for (; idx < end; idx++) processOne(batch[idx]);
769
+ if (idx < batch.length) _yieldThen(step);
770
+ }
771
+ step();
772
+ }
773
+
774
+ var obs = new MutationObserver(function (muts) {
775
+ muts.forEach(function (m) {
776
+ m.addedNodes.forEach(function (n) {
777
+ if (n.nodeType === 1) queue.push({ added: true, el: n });
778
+ });
779
+ m.removedNodes.forEach(function (n) {
780
+ if (n.nodeType === 1) queue.push({ added: false, el: n });
781
+ });
782
+ });
783
+ if (!pending) {
784
+ pending = true;
785
+ setTimeout(flush, throttleMs);
786
+ }
787
+ });
788
+ obs.observe(containerEl, { childList: true, subtree: true });
789
+ _watchObservers.push(obs);
790
+ /* Also process existing descendants */
791
+ containerEl.querySelectorAll('[data-nac-action]').forEach(function (el) {
792
+ try { autoRegister(el, opts); } catch (_) {}
793
+ });
794
+ return obs;
795
+ };
796
+
797
+ /* ------------------------------------------------------------- adopt */
798
+
799
+ function adopt(rule) {
800
+ if (!rule || !rule.selector) throw new Error('[NAC v2] adopt requires selector');
801
+ rule.parent = rule.parent || null;
802
+ rule.observe = rule.observe !== false;
803
+
804
+ function process(el) {
805
+ try {
806
+ var leaf = (rule.derive && rule.derive.slug)
807
+ ? rule.derive.slug(el)
808
+ : _deriveLeafSlug(el);
809
+ var fullSlug = rule.parent
810
+ ? (rule.parent + SEPARATOR + leaf)
811
+ : leaf;
812
+ var role = (rule.derive && rule.derive.role)
813
+ ? rule.derive.role(el)
814
+ : _deriveRole(el);
815
+ var labelI18n = (rule.derive && rule.derive.label_i18n)
816
+ ? rule.derive.label_i18n(el)
817
+ : (function () { var o={}; o[_currentLocale]=_deriveLabel(el); return o; })();
818
+ var irreversible = (rule.derive && rule.derive.irreversible)
819
+ ? rule.derive.irreversible(el)
820
+ : false;
821
+ var entry = {
822
+ slug: fullSlug,
823
+ intent: (rule.derive && rule.derive.intent && rule.derive.intent(el)) || 'navigate',
824
+ source: 'human',
825
+ label_i18n: labelI18n,
826
+ role: role,
827
+ element: el,
828
+ irreversible: irreversible,
829
+ adopted: true,
830
+ registered_at: Date.now()
831
+ };
832
+ _scopes[fullSlug] = entry;
833
+ el.setAttribute('data-nac-id', fullSlug);
834
+ if (role && !el.getAttribute('role')) el.setAttribute('role', role);
835
+ if (labelI18n && !el.getAttribute('aria-label')) {
836
+ var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
837
+ el.setAttribute('aria-label', lab);
838
+ }
839
+ if (irreversible) el.setAttribute('data-nac-irreversible', '1');
840
+ } catch (e) {
841
+ document.dispatchEvent(new CustomEvent('nac:adopt_failed', {
842
+ detail: { rule: rule.selector, error: String(e) }, bubbles: true
843
+ }));
844
+ }
845
+ }
846
+
847
+ /* v2.0-rc3 (Claude T3.3): scope the observer to a host-supplied
848
+ containerEl (smaller subtree) when provided, instead of always
849
+ attaching to document.body. Reduces mutation-observer cost
850
+ on DOM-heavy pages with N rules. */
851
+ var scopedRoot = (rule.containerEl && rule.containerEl.nodeType === 1)
852
+ ? rule.containerEl
853
+ : document.body;
854
+
855
+ /* Initial pass: query within the scoped root, not always document. */
856
+ scopedRoot.querySelectorAll(rule.selector).forEach(process);
857
+
858
+ /* Observer */
859
+ if (rule.observe) {
860
+ var obs = new MutationObserver(function (muts) {
861
+ muts.forEach(function (m) {
862
+ m.addedNodes.forEach(function (n) {
863
+ if (n.nodeType !== 1) return;
864
+ if (n.matches && n.matches(rule.selector)) process(n);
865
+ if (n.querySelectorAll) {
866
+ n.querySelectorAll(rule.selector).forEach(process);
867
+ }
868
+ });
869
+ });
870
+ });
871
+ obs.observe(scopedRoot, { childList: true, subtree: true });
872
+ }
873
+ return rule;
874
+ }
875
+
876
+ /* ------------------------------------------------------------- bridges */
877
+
878
+ /* v2.0-rc3 (DeepSeek T3.4): dedup bridged hosts via WeakSet so
879
+ repeat calls on the same host do not produce duplicate
880
+ registrations. */
881
+ var _bridgedShadowHosts = new WeakSet();
882
+
883
+ function bridgeShadowRoot(host, depth) {
884
+ depth = depth || 0;
885
+ if (depth > 6) {
886
+ document.dispatchEvent(new CustomEvent('nac:shadow_depth_exceeded', {
887
+ detail: { host: host }, bubbles: true
888
+ }));
889
+ return;
890
+ }
891
+ if (!host || !host.shadowRoot) {
892
+ document.dispatchEvent(new CustomEvent('nac:shadow_blocked', {
893
+ detail: { host: host, reason: 'closed_or_missing' }, bubbles: true
894
+ }));
895
+ return;
896
+ }
897
+ /* v2.0-rc3: skip if already bridged. */
898
+ if (_bridgedShadowHosts.has(host)) return;
899
+ _bridgedShadowHosts.add(host);
900
+ /* Walk shadow root: any [data-nac-id] becomes operable; any
901
+ [data-nac-action] auto-registers */
902
+ var sr = host.shadowRoot;
903
+ sr.querySelectorAll('[data-nac-action]').forEach(function (el) {
904
+ try { autoRegister(el, { i18n_strict: 'permissive' }); } catch (_) {}
905
+ });
906
+ /* Recurse */
907
+ sr.querySelectorAll('*').forEach(function (el) {
908
+ if (el.shadowRoot) bridgeShadowRoot(el, depth + 1);
909
+ });
910
+ }
911
+
912
+ function bridgeIframe(iframeEl, opts) {
913
+ opts = opts || {};
914
+ var ns = opts.postMessageNamespace || 'nac.iframe.v1';
915
+ var trusted = opts.trusted_origins || [];
916
+ var timeout = opts.timeout_ms || 5000;
917
+ var iframeId = iframeEl.id || 'iframe_' + Math.random().toString(36).slice(2,8);
918
+ /* v2.0-rc4 (Mistral T7-F1 + Claude T4-F2.1): NAC-3 enforcement
919
+ opt-in. When opts.nac_level === 3 (or auto-detected from
920
+ _validationTolerance.iframe_strict === 'error'), runtime
921
+ enforces fail-closed on missing secret and verifies
922
+ signatures on BOTH handshake_ack AND describe_result. */
923
+ var nacLevel = opts.nac_level
924
+ || (_validationTolerance.iframe_strict === 'error' ? 3 : 1);
925
+
926
+ /* v2.0-rc3 (Claude T4-F2): the spec mandates HMAC chain on
927
+ cross-origin agent-source events. We additionally require
928
+ that handshake_ack and describe_result messages carry
929
+ signature fields verifiable against our registered HMAC
930
+ secret. Without this, a compromised trusted-origin (XSS in
931
+ a vendor's CDN) can ride on the allowlist trust to inject
932
+ manifest entries unchecked.
933
+ v2.0-rc4: extended to describe_result + NAC-3 fail-closed. */
934
+ return new Promise(function (resolve, reject) {
935
+ var done = false;
936
+ function listener(ev) {
937
+ if (trusted.length && trusted.indexOf(ev.origin) < 0) {
938
+ document.dispatchEvent(new CustomEvent('nac:iframe_untrusted', {
939
+ detail: { origin: ev.origin }, bubbles: true
940
+ }));
941
+ return;
942
+ }
943
+ var d = ev.data;
944
+ if (!d || d.ns !== ns) return;
945
+ if (d.cmd === 'handshake_ack') {
946
+ if (done) return;
947
+ /* v2.0-rc4 (Mistral T7-F1): NAC-3 fail-closed. If no
948
+ secret registered AND we are at NAC-3, reject the
949
+ handshake. NAC-1/NAC-2 path keeps fail-open with
950
+ warn (rc3 behaviour). */
951
+ if (nacLevel >= 3 && !_hasSecrets()) {
952
+ done = true;
953
+ window.removeEventListener('message', listener);
954
+ document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
955
+ detail: { iframeId: iframeId }, bubbles: true
956
+ }));
957
+ reject(new Error('iframe_no_secret_at_nac3'));
958
+ return;
959
+ }
960
+ /* v2.0-rc3: verify signature on handshake_ack if HMAC
961
+ secret registered. */
962
+ if (_hasSecrets() && d.signature) {
963
+ _verify_with_registered({ ns: d.ns, cmd: d.cmd, version: d.version, signature: d.signature })
964
+ .then(function (ok) {
965
+ if (!ok) {
966
+ done = true;
967
+ window.removeEventListener('message', listener);
968
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
969
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
970
+ }));
971
+ reject(new Error('iframe_signature_invalid'));
972
+ return;
973
+ }
974
+ _continueHandshakeAck();
975
+ });
976
+ return;
977
+ }
978
+ if (_hasSecrets() && !d.signature) {
979
+ /* Secret registered but iframe did not sign -> at
980
+ NAC-3 fail-closed; at lower levels emit warn and
981
+ continue. */
982
+ if (nacLevel >= 3) {
983
+ done = true;
984
+ window.removeEventListener('message', listener);
985
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
986
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
987
+ }));
988
+ reject(new Error('iframe_signature_missing'));
989
+ return;
990
+ }
991
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
992
+ detail: { iframeId: iframeId, message: 'handshake_ack' }, bubbles: true
993
+ }));
994
+ }
995
+ _continueHandshakeAck();
996
+
997
+ function _continueHandshakeAck() {
998
+ done = true;
999
+ if (d.version && d.version.split('.')[0] !== '2') {
1000
+ document.dispatchEvent(new CustomEvent('nac:iframe_version_mismatch', {
1001
+ detail: { theirs: d.version, ours: '2.0' }, bubbles: true
1002
+ }));
1003
+ reject(new Error('iframe_version_mismatch'));
1004
+ return;
1005
+ }
1006
+ window.removeEventListener('message', listener);
1007
+ resolve({ iframeId: iframeId, version: d.version,
1008
+ signed: !!d.signature, nac_level: nacLevel });
1009
+ }
1010
+ }
1011
+ /* v2.0-rc4 (Mistral T4-F2.1): describe_result messages
1012
+ ALSO must be HMAC-verified at NAC-3. The handshake
1013
+ promise has already resolved by this point; this
1014
+ listener stays installed for follow-up describe()
1015
+ pulls. We emit events but cannot reject the promise
1016
+ (already settled). */
1017
+ if (d.cmd === 'describe_result') {
1018
+ if (nacLevel >= 3 && !_hasSecrets()) {
1019
+ document.dispatchEvent(new CustomEvent('nac:iframe_no_secret_at_nac3', {
1020
+ detail: { iframeId: iframeId, message: 'describe_result' },
1021
+ bubbles: true
1022
+ }));
1023
+ return;
1024
+ }
1025
+ if (_hasSecrets() && d.signature) {
1026
+ _verify_with_registered({
1027
+ ns: d.ns, cmd: d.cmd, manifest: d.manifest, signature: d.signature
1028
+ }).then(function (ok) {
1029
+ if (!ok) {
1030
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_invalid', {
1031
+ detail: { iframeId: iframeId, message: 'describe_result' },
1032
+ bubbles: true
1033
+ }));
1034
+ return;
1035
+ }
1036
+ /* Verified: forward manifest to whoever subscribes. */
1037
+ document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1038
+ detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1039
+ }));
1040
+ });
1041
+ return;
1042
+ }
1043
+ if (_hasSecrets() && !d.signature) {
1044
+ document.dispatchEvent(new CustomEvent('nac:iframe_signature_missing', {
1045
+ detail: { iframeId: iframeId, message: 'describe_result' }, bubbles: true
1046
+ }));
1047
+ if (nacLevel >= 3) return; /* drop unsigned at NAC-3 */
1048
+ }
1049
+ /* NAC-1/NAC-2 + no secret: forward manifest as-is. */
1050
+ document.dispatchEvent(new CustomEvent('nac:iframe_describe_received', {
1051
+ detail: { iframeId: iframeId, manifest: d.manifest }, bubbles: true
1052
+ }));
1053
+ }
1054
+ }
1055
+ window.addEventListener('message', listener);
1056
+ iframeEl.contentWindow.postMessage(
1057
+ { ns: ns, cmd: 'handshake', version: '2.0' },
1058
+ trusted.length ? trusted[0] : '*'
1059
+ );
1060
+ setTimeout(function () {
1061
+ if (!done) {
1062
+ done = true;
1063
+ window.removeEventListener('message', listener);
1064
+ document.dispatchEvent(new CustomEvent('nac:iframe_handshake_timeout', {
1065
+ detail: { iframeId: iframeId }, bubbles: true
1066
+ }));
1067
+ reject(new Error('iframe_handshake_timeout'));
1068
+ }
1069
+ }, timeout);
1070
+ });
1071
+ }
1072
+
1073
+ /* ------------------------------------------------------------- virtual */
1074
+
1075
+ var _virtuals = [];
1076
+ function declareVirtual(spec) {
1077
+ if (!spec || !spec.slug_pattern || typeof spec.resolver !== 'function') {
1078
+ throw new Error('[NAC v2] declareVirtual requires {slug_pattern, count, resolver}');
1079
+ }
1080
+ _virtuals.push(spec);
1081
+ return spec;
1082
+ }
1083
+ /* v2.0-rc3 (Claude T3.6 / DeepSeek T3.6): escape regex
1084
+ metacharacters in the static parts of the pattern before
1085
+ substituting {i}. Without this, `pipeline.runs.row.{i}` would
1086
+ match `pipelineXrunsXrowX7` (because `.` is a regex wildcard);
1087
+ a malicious URL or DOM-injected slug could hit arbitrary
1088
+ pattern. */
1089
+ function _escapeRegex(s) {
1090
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1091
+ }
1092
+ function _resolveVirtual(slug) {
1093
+ for (var i = 0; i < _virtuals.length; i++) {
1094
+ var v = _virtuals[i];
1095
+ /* Split on {i} so we can escape the static parts. */
1096
+ var parts = v.slug_pattern.split('{i}');
1097
+ var pat = parts.map(_escapeRegex).join('(\\d+)');
1098
+ var m = slug.match(new RegExp('^' + pat + '$'));
1099
+ if (m) {
1100
+ var idx = parseInt(m[1], 10);
1101
+ var count = typeof v.count === 'function' ? v.count() : v.count;
1102
+ if (idx >= 0 && idx < count) {
1103
+ var t0 = performance.now();
1104
+ var entry = v.resolver(idx);
1105
+ var elapsed = performance.now() - t0;
1106
+ if (elapsed > 50) {
1107
+ document.dispatchEvent(new CustomEvent('nac:virtual_resolver_slow', {
1108
+ detail: { slug: slug, elapsed_ms: elapsed }, bubbles: true
1109
+ }));
1110
+ }
1111
+ return entry;
1112
+ }
1113
+ }
1114
+ }
1115
+ return null;
1116
+ }
1117
+
1118
+ /* ------------------------------------------------------------- ephemeral */
1119
+
1120
+ var _ephemeralRing = [];
1121
+ var _ephemeralOpts = null;
1122
+ function captureEphemeral(opts) {
1123
+ opts = opts || {};
1124
+ _ephemeralOpts = {
1125
+ duration_ms: opts.duration_ms || 3000,
1126
+ ring_size: opts.ring_size || 100,
1127
+ on_capture: opts.on_capture || null
1128
+ };
1129
+ var liveTimers = new Map();
1130
+ var obs = new MutationObserver(function (muts) {
1131
+ muts.forEach(function (m) {
1132
+ m.addedNodes.forEach(function (n) {
1133
+ if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1134
+ var slug = n.getAttribute('data-nac-id');
1135
+ liveTimers.set(slug, { added_at: Date.now(), node: n });
1136
+ }
1137
+ });
1138
+ m.removedNodes.forEach(function (n) {
1139
+ if (n.nodeType === 1 && n.getAttribute && n.getAttribute('data-nac-id')) {
1140
+ var slug = n.getAttribute('data-nac-id');
1141
+ var live = liveTimers.get(slug);
1142
+ if (live && (Date.now() - live.added_at) <= _ephemeralOpts.duration_ms) {
1143
+ var capture = {
1144
+ slug: slug,
1145
+ role: n.getAttribute('role'),
1146
+ label: n.textContent.trim().slice(0, 200),
1147
+ added_at: live.added_at,
1148
+ removed_at: Date.now(),
1149
+ duration_ms: Date.now() - live.added_at
1150
+ };
1151
+ _ephemeralRing.push(capture);
1152
+ if (_ephemeralRing.length > _ephemeralOpts.ring_size) {
1153
+ _ephemeralRing.shift();
1154
+ }
1155
+ if (_ephemeralOpts.on_capture) _ephemeralOpts.on_capture(capture);
1156
+ }
1157
+ liveTimers.delete(slug);
1158
+ }
1159
+ });
1160
+ });
1161
+ });
1162
+ obs.observe(document.body, { childList: true, subtree: true });
1163
+ return obs;
1164
+ }
1165
+
1166
+ /* ------------------------------------------------------------- tenant */
1167
+
1168
+ var _tenantPrefix = null;
1169
+ function setTenantPrefix(slug) {
1170
+ if (_tenantPrefix !== null) {
1171
+ throw new Error('[NAC v2] tenant_prefix_locked: already set to ' + _tenantPrefix);
1172
+ }
1173
+ _validateLeaf(slug);
1174
+ _tenantPrefix = slug;
1175
+ }
1176
+ function getTenantPrefix() { return _tenantPrefix; }
1177
+
1178
+ /* ------------------------------------------------------------- describe v2 */
1179
+
1180
+ /* Augment v1.9's describe() with v2 additions when called.
1181
+ We don't replace the v1.9 function; we expose a new
1182
+ `describe_v2()` and decorate the v1 result. */
1183
+ /* v2.0-rc3 (Claude T3.1): track intermediate scope nodes so
1184
+ describe_v2 can expose their label_i18n. Without this,
1185
+ a catalog declares `shell.topbar` label but no consumer
1186
+ reads it because the intermediate node has no element.
1187
+
1188
+ v2.0-rc4 (Mistral T7-F2): the index grows monotonically with
1189
+ unique scope paths created. Realistic SPA case is bounded
1190
+ (~6 levels x ~few sections = O(N small)) but an SPA that
1191
+ dynamically creates and discards scopes can leak. WeakMap
1192
+ was rejected because keys are strings (paths), not objects.
1193
+ Solution: NAC.gcIntermediateScopes(activePathSet) lets the
1194
+ host prune entries no longer in use. Default behaviour:
1195
+ no automatic GC; documented growth pattern. */
1196
+ var _intermediateScopes = Object.create(null);
1197
+
1198
+ /* v2.0-rc5 (spec sec 17): optional sitemap primitive. Hosts with
1199
+ 50+ logical screens declare the full path catalog so the
1200
+ intermediary can plan navigation to slugs not currently in
1201
+ the visible tree. Authority separation is CRITICAL: the
1202
+ sitemap is navigational metadata only, never a source of
1203
+ can-operate truth. The visible tree (_scopes / v1 manifest)
1204
+ remains the only authority for dispatch. */
1205
+ var _sitemap = null; /* { paths: [...] } or null */
1206
+
1207
+ function declareSitemap(spec) {
1208
+ if (spec === null || typeof spec === 'undefined') {
1209
+ _sitemap = null;
1210
+ return;
1211
+ }
1212
+ if (typeof spec !== 'object' || !Array.isArray(spec.paths)) {
1213
+ throw new Error('[NAC v2] declareSitemap: spec must be { paths: [...] }');
1214
+ }
1215
+ var seenSlugs = Object.create(null);
1216
+ var clean = [];
1217
+ for (var i = 0; i < spec.paths.length; i++) {
1218
+ var p = spec.paths[i];
1219
+ if (!p || typeof p.slug !== 'string' || p.slug === '') {
1220
+ throw new Error('[NAC v2] declareSitemap: paths[' + i + '].slug required');
1221
+ }
1222
+ if (seenSlugs[p.slug]) {
1223
+ throw new Error('[NAC v2] declareSitemap: duplicate slug "' + p.slug + '"');
1224
+ }
1225
+ seenSlugs[p.slug] = true;
1226
+ var entry = { slug: p.slug };
1227
+ if (p.label_i18n && typeof p.label_i18n === 'object') {
1228
+ entry.label_i18n = p.label_i18n;
1229
+ }
1230
+ if (Array.isArray(p.affordance_to_navigate)) {
1231
+ entry.affordance_to_navigate = p.affordance_to_navigate.slice();
1232
+ }
1233
+ if (Array.isArray(p.requires_permission)) {
1234
+ entry.requires_permission = p.requires_permission.slice();
1235
+ }
1236
+ if (Array.isArray(p.tags)) {
1237
+ entry.tags = p.tags.slice();
1238
+ }
1239
+ clean.push(entry);
1240
+ }
1241
+ _sitemap = { paths: clean };
1242
+ }
1243
+
1244
+ function getSitemap() {
1245
+ if (!_sitemap) return null;
1246
+ /* return a defensive shallow copy so callers cannot mutate
1247
+ internal state */
1248
+ return { paths: _sitemap.paths.slice() };
1249
+ }
1250
+
1251
+ /* Public GC API (rc4): the host passes a Set or array of path
1252
+ strings that are still considered "active". Any entry in the
1253
+ index whose path is NOT in that set gets removed. */
1254
+ function gcIntermediateScopes(activePaths) {
1255
+ if (!activePaths) {
1256
+ /* No-arg form: clear ALL intermediate scopes. Use only when
1257
+ tearing down the SPA / navigating to a totally new shell. */
1258
+ _intermediateScopes = Object.create(null);
1259
+ return 0;
1260
+ }
1261
+ var active = (typeof activePaths.has === 'function')
1262
+ ? activePaths
1263
+ : new Set(activePaths);
1264
+ var removed = 0;
1265
+ Object.keys(_intermediateScopes).forEach(function (k) {
1266
+ if (!active.has(k)) {
1267
+ delete _intermediateScopes[k];
1268
+ removed++;
1269
+ }
1270
+ });
1271
+ return removed;
1272
+ }
1273
+
1274
+ function describe_v2() {
1275
+ var v1 = (typeof NAC.describe === 'function') ? NAC.describe() : { plugins: [] };
1276
+ var scopeEntries = Object.keys(_scopes).map(function (k) {
1277
+ var e = _scopes[k];
1278
+ return {
1279
+ slug: e.slug,
1280
+ role: e.role,
1281
+ intent: e.intent,
1282
+ autoderived: e.autoderived || false,
1283
+ adopted: e.adopted || false,
1284
+ irreversible: e.irreversible || false,
1285
+ parent_chain: e.parent_chain || null,
1286
+ has_element: !!e.element
1287
+ };
1288
+ });
1289
+ var intermediateScopes = Object.keys(_intermediateScopes).map(function (k) {
1290
+ return {
1291
+ slug: k,
1292
+ depth: _intermediateScopes[k].depth,
1293
+ label_i18n: _intermediateScopes[k].label_i18n,
1294
+ is_intermediate: true
1295
+ };
1296
+ });
1297
+ var virtual_summary = _virtuals.map(function (v) {
1298
+ var count = typeof v.count === 'function' ? v.count() : v.count;
1299
+ return { slug_pattern: v.slug_pattern, count: count };
1300
+ });
1301
+ /* v2.1 sec 18: surface every registered data-table so the
1302
+ chatbot intermediary, RPA bot and test runner all see the
1303
+ same snapshot. data_tables is [] when no host has called
1304
+ registerDataTable(). */
1305
+ var dataTables = (typeof NAC.__v2_dtSummariseAll === 'function')
1306
+ ? NAC.__v2_dtSummariseAll()
1307
+ : [];
1308
+ return {
1309
+ nac_version: '2.1.0-rc1',
1310
+ timestamp: Date.now(),
1311
+ tenant_prefix: _tenantPrefix,
1312
+ v1_plugins: v1.plugins || [],
1313
+ v2_scope_entries: scopeEntries,
1314
+ v2_intermediate_scopes: intermediateScopes,
1315
+ virtual: virtual_summary,
1316
+ ephemeral_log: _ephemeralRing.slice(),
1317
+ locale: _currentLocale,
1318
+ supported_locales: _supported.slice(),
1319
+ /* v2.0-rc5 (spec sec 17): null when host has not declared a
1320
+ sitemap (small SPAs / demos); otherwise the path catalog.
1321
+ Intermediaries treat this as PLANNING data, not authority. */
1322
+ sitemap: _sitemap ? { paths: _sitemap.paths.slice() } : null,
1323
+ /* v2.1 (spec sec 18): registered data-tables with their full
1324
+ state. [] when no host has registered any. */
1325
+ data_tables: dataTables
1326
+ };
1327
+ }
1328
+
1329
+ /* ------------------------------------------------------------- validate v2 */
1330
+
1331
+ function validate_global_v2(opts) {
1332
+ opts = opts || {};
1333
+ var findings = { errors: [], warnings: [] };
1334
+ /* 2026-05-09 (Claude R6): drain runtime guard findings
1335
+ FIRST, before any early-return, so security-relevant
1336
+ events (script_override_claims_user, etc.) ALWAYS reach
1337
+ the validator output regardless of i18n severity. */
1338
+ for (var fi = 0; fi < _validatorFindings.length; fi++) {
1339
+ var rf = _validatorFindings[fi];
1340
+ var bkt = rf.severity === 'error' ? findings.errors : findings.warnings;
1341
+ bkt.push({
1342
+ code: rf.code,
1343
+ severity: rf.severity,
1344
+ timestamp: rf.timestamp,
1345
+ note: rf.note
1346
+ });
1347
+ }
1348
+ /* v2.0-rc2 (Grok T5-F1 + Mistral T5-F2): severity for missing-
1349
+ locale findings now honours the tolerance setting. Default
1350
+ at NAC-3 is 'warn'; hosts that need NAC-4-equivalent strict
1351
+ mode opt in via set_validation_tolerance({i18n_strict:'error'})
1352
+ OR pass opts.i18n_strict_severity explicitly. */
1353
+ var severity = opts.i18n_strict_severity || _validationTolerance.i18n_strict;
1354
+ if (severity === 'silent') return findings;
1355
+ var bucket = severity === 'error' ? findings.errors : findings.warnings;
1356
+
1357
+ if (opts.i18n_strict) {
1358
+ Object.keys(_catalog).forEach(function (key) {
1359
+ var entry = _catalog[key];
1360
+ var missing = _supported.filter(function (loc) { return !entry[loc]; });
1361
+ if (missing.length) {
1362
+ bucket.push({
1363
+ code: 'i18n_missing_locale',
1364
+ key: key,
1365
+ missing: missing,
1366
+ severity: severity
1367
+ });
1368
+ }
1369
+ Object.keys(entry).forEach(function (loc) {
1370
+ if (_supported.indexOf(loc) < 0) {
1371
+ /* invalid_locale always error: catalog has nonsense key */
1372
+ findings.errors.push({
1373
+ code: 'i18n_invalid_locale',
1374
+ key: key,
1375
+ locale: loc
1376
+ });
1377
+ }
1378
+ /* empty_string honours severity tolerance too */
1379
+ if (typeof entry[loc] === 'string' && entry[loc].length === 0) {
1380
+ bucket.push({ code: 'i18n_string_empty', key: key, locale: loc, severity: severity });
1381
+ }
1382
+ if (typeof entry[loc] === 'string' && entry[loc].length > 1000) {
1383
+ findings.warnings.push({ code: 'i18n_string_too_long', key: key, locale: loc });
1384
+ }
1385
+ });
1386
+ });
1387
+ /* Mono-locale autoderived warn (always warn -- this is a
1388
+ drift signal, not a correctness signal). */
1389
+ Object.keys(_scopes).forEach(function (slug) {
1390
+ if (_scopes[slug].autoderived) {
1391
+ findings.warnings.push({ code: 'i18n_mono_locale_autoderived', slug: slug });
1392
+ }
1393
+ });
1394
+ }
1395
+
1396
+ /* v2.0-rc4 (Claude T8.2 codification): at NAC-3, autoderived
1397
+ data-nac-action is SHOULD with REQUIRED fallback. Emit
1398
+ data_nac_action_autoderived per scope where the action was
1399
+ inferred rather than declared. Severity follows
1400
+ _validationTolerance.autoderived_action (default warn). */
1401
+ var autodSev = opts.autoderived_action_severity
1402
+ || _validationTolerance.autoderived_action;
1403
+ if (autodSev !== 'silent') {
1404
+ var autodBucket = autodSev === 'error' ? findings.errors : findings.warnings;
1405
+ Object.keys(_scopes).forEach(function (slug) {
1406
+ var entry = _scopes[slug];
1407
+ if (entry.element && !entry.element.hasAttribute('data-nac-action')) {
1408
+ /* Only emit for elements that DO have a registered
1409
+ intent but lack the explicit data-nac-action attr.
1410
+ autoRegister-only path: the slug exists in _scopes
1411
+ but the host did not declare data-nac-action. */
1412
+ if (entry.autoderived || entry.adopted) {
1413
+ autodBucket.push({
1414
+ code: 'data_nac_action_autoderived',
1415
+ slug: slug,
1416
+ severity: autodSev
1417
+ });
1418
+ }
1419
+ }
1420
+ });
1421
+ }
1422
+ return findings;
1423
+ }
1424
+
1425
+ /* ------------------------------------------------------------- exports */
1426
+
1427
+ /* Attach v2 surface to NAC namespace without overwriting v1.9 */
1428
+ NAC.scope = scope;
1429
+ NAC.autoRegister = autoRegister;
1430
+ NAC.adopt = adopt;
1431
+ NAC.bridgeShadowRoot = bridgeShadowRoot;
1432
+ NAC.bridgeIframe = bridgeIframe;
1433
+ NAC.declareVirtual = declareVirtual;
1434
+ NAC.captureEphemeral = captureEphemeral;
1435
+ NAC.setTenantPrefix = setTenantPrefix;
1436
+ NAC.getTenantPrefix = getTenantPrefix;
1437
+ NAC.attestUserGesture = attestUserGesture;
1438
+ NAC.setMobileWebViewAttestation = setMobileWebViewAttestation;
1439
+ NAC.t = t;
1440
+ NAC.registerCatalog = registerCatalog;
1441
+ NAC.locale = locale;
1442
+ NAC.setSupportedLocales = setSupportedLocales;
1443
+ NAC.setRTLLocales = setRTLLocales;
1444
+ NAC.setAutoRTL = setAutoRTL;
1445
+ NAC.set_provenance_secret = set_provenance_secret;
1446
+ NAC.set_perf_tolerance = set_perf_tolerance;
1447
+ NAC.get_perf_tolerance = get_perf_tolerance;
1448
+ NAC.set_validation_tolerance = set_validation_tolerance;
1449
+ NAC.get_validation_tolerance = get_validation_tolerance;
1450
+ NAC.describe_v2 = describe_v2;
1451
+ NAC.validate_global_v2 = validate_global_v2;
1452
+ NAC.gcIntermediateScopes = gcIntermediateScopes;
1453
+ NAC.declareSitemap = declareSitemap;
1454
+ NAC.getSitemap = getSitemap;
1455
+
1456
+ /* Convenience: expose internals for tests */
1457
+ NAC.__v2 = {
1458
+ SUPPORTED_LOCALES_DEFAULT: SUPPORTED_LOCALES_DEFAULT,
1459
+ SEPARATOR: SEPARATOR,
1460
+ MAX_DEPTH: MAX_DEPTH,
1461
+ _scopes: _scopes,
1462
+ _catalog: _catalog,
1463
+ _virtuals: _virtuals,
1464
+ _ephemeralRing: _ephemeralRing
1465
+ };
1466
+
1467
+ /* v2.0-rc3 (Claude T6-F2): warm SubtleCrypto's HMAC sign path
1468
+ at boot so the cold-start cost is paid once, not at first
1469
+ agent action. Best-effort: fails silently when no secret is
1470
+ registered yet (which is fine -- adopters that wire HMAC
1471
+ register the secret at boot). */
1472
+ function _warmCrypto() {
1473
+ if (typeof NAC.sign_provenance !== 'function') return;
1474
+ if (!_provenanceSecrets[0]) return;
1475
+ try {
1476
+ NAC.sign_provenance({ _warmup: true, ts: Date.now() }, _provenanceSecrets[0])
1477
+ .catch(function () {}); /* silently swallow warmup errors */
1478
+ } catch (_) {}
1479
+ }
1480
+ /* Defer warm to next tick so the secret-registration call has a
1481
+ chance to land first. Hosts that register the secret AFTER
1482
+ boot can manually call NAC.set_provenance_secret() which
1483
+ re-warms. */
1484
+ setTimeout(_warmCrypto, 0);
1485
+
1486
+ /* ------------------------------------------------------------- v2.1 data-table primitive (spec sec 18) */
1487
+ /* See docs/V2_1_DATA_TABLE_GUIDE.md for the adopter walk-through.
1488
+ Authority separation: the runtime owns the in-memory state,
1489
+ the host owns persistence (commit handler does the HTTP/DB
1490
+ write). All operator classes (user, agent, bot) use the same
1491
+ dt_* API; the `by` discriminator on every emitted event lets
1492
+ audit pipelines attribute changes per source.type contract. */
1493
+
1494
+ var _dataTables = Object.create(null);
1495
+ /* { table_id -> {
1496
+ schema: {...}, // immutable post-register
1497
+ current_rows: [...], // collection: array of objects
1498
+ current_cells: [...], // matrix: array of {row, col, value}
1499
+ initial_state: deep_copy, // for discard()
1500
+ selected: Set<row_id>, // collection only
1501
+ modified: bool,
1502
+ computed_fns: { col_key -> fn(row, allRows) } } } */
1503
+
1504
+ function _dtDeepCopy(o) {
1505
+ /* JSON-roundtrip: cheap, preserves the primitive shapes our
1506
+ cells carry (string/number/boolean/null/array/plain object).
1507
+ If a host puts Date/Map in a cell we reject at register time. */
1508
+ return o === undefined ? undefined : JSON.parse(JSON.stringify(o));
1509
+ }
1510
+
1511
+ function _dtEmit(name, detail) {
1512
+ document.dispatchEvent(new CustomEvent(name, { detail: detail, bubbles: true }));
1513
+ }
1514
+
1515
+ function _dtBy() {
1516
+ /* Detect operator class. If the call originated from a recent
1517
+ attested user gesture, by='user'; otherwise by='agent'. The
1518
+ gesture buffer (rc3 T4-F1) is the source of truth. */
1519
+ try {
1520
+ if (typeof NAC.attestUserGesture === 'function') {
1521
+ var gesture = NAC._readGestureAttested
1522
+ ? NAC._readGestureAttested()
1523
+ : null;
1524
+ if (gesture && gesture.attested) return 'user';
1525
+ }
1526
+ } catch (_) {}
1527
+ return 'agent';
1528
+ }
1529
+
1530
+ function _dtCheckColumnValue(col, value) {
1531
+ if (value === null || value === undefined) {
1532
+ if (col.required) return { ok: false, error: 'required_missing' };
1533
+ return { ok: true };
1534
+ }
1535
+ var t = col.type;
1536
+ if (t === 'number' || t === 'currency') {
1537
+ if (typeof value !== 'number' || !isFinite(value)) {
1538
+ return { ok: false, error: 'invalid_type:expected_number' };
1539
+ }
1540
+ if (typeof col.min === 'number' && value < col.min) {
1541
+ return { ok: false, error: 'below_min:' + col.min };
1542
+ }
1543
+ if (typeof col.max === 'number' && value > col.max) {
1544
+ return { ok: false, error: 'above_max:' + col.max };
1545
+ }
1546
+ } else if (t === 'boolean') {
1547
+ if (typeof value !== 'boolean') {
1548
+ return { ok: false, error: 'invalid_type:expected_boolean' };
1549
+ }
1550
+ } else if (t === 'select') {
1551
+ var opts = col.options || [];
1552
+ var ok = opts.some(function (o) { return (o.value !== undefined ? o.value : o) === value; });
1553
+ if (!ok) return { ok: false, error: 'invalid_option' };
1554
+ } else if (t === 'date') {
1555
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(value)) {
1556
+ return { ok: false, error: 'invalid_type:expected_date_iso' };
1557
+ }
1558
+ } else {
1559
+ /* text and others: just require string-like */
1560
+ if (typeof value !== 'string' && typeof value !== 'number') {
1561
+ return { ok: false, error: 'invalid_type:expected_text' };
1562
+ }
1563
+ }
1564
+ return { ok: true };
1565
+ }
1566
+
1567
+ function _dtRecomputeRow(table, row) {
1568
+ /* Recompute every column whose `computed:true` and a fn is
1569
+ registered. */
1570
+ var changed = false;
1571
+ table.schema.columns.forEach(function (col) {
1572
+ if (!col.computed) return;
1573
+ var fn = table.computed_fns[col.key];
1574
+ if (!fn) return;
1575
+ try {
1576
+ var newVal = fn(row, table.current_rows);
1577
+ if (row[col.key] !== newVal) {
1578
+ row[col.key] = newVal;
1579
+ changed = true;
1580
+ }
1581
+ } catch (_) { /* swallow; computed err leaves stale value */ }
1582
+ });
1583
+ return changed;
1584
+ }
1585
+
1586
+ function _dtRecomputeAggregates(table, prevAggs) {
1587
+ var aggs = {};
1588
+ var defs = table.schema.aggregates || {};
1589
+ Object.keys(defs).forEach(function (aggKey) {
1590
+ var cols = defs[aggKey] || [];
1591
+ aggs[aggKey] = {};
1592
+ cols.forEach(function (colKey) {
1593
+ if (colKey === '*') {
1594
+ aggs[aggKey]['*'] = aggKey === 'count' ? table.current_rows.length : 0;
1595
+ return;
1596
+ }
1597
+ var values = table.current_rows
1598
+ .map(function (r) { return r[colKey]; })
1599
+ .filter(function (v) { return typeof v === 'number' && isFinite(v); });
1600
+ if (aggKey === 'sum') {
1601
+ aggs[aggKey][colKey] = values.reduce(function (s, v) { return s + v; }, 0);
1602
+ } else if (aggKey === 'avg') {
1603
+ aggs[aggKey][colKey] = values.length
1604
+ ? values.reduce(function (s, v) { return s + v; }, 0) / values.length
1605
+ : 0;
1606
+ } else if (aggKey === 'count') {
1607
+ aggs[aggKey][colKey] = values.length;
1608
+ } else if (aggKey === 'min') {
1609
+ aggs[aggKey][colKey] = values.length ? Math.min.apply(null, values) : null;
1610
+ } else if (aggKey === 'max') {
1611
+ aggs[aggKey][colKey] = values.length ? Math.max.apply(null, values) : null;
1612
+ }
1613
+ });
1614
+ });
1615
+ /* Emit per (agg, column) pair when changed. */
1616
+ if (prevAggs) {
1617
+ Object.keys(aggs).forEach(function (aggKey) {
1618
+ Object.keys(aggs[aggKey]).forEach(function (colKey) {
1619
+ var oldV = (prevAggs[aggKey] || {})[colKey];
1620
+ var newV = aggs[aggKey][colKey];
1621
+ if (oldV !== newV) {
1622
+ _dtEmit('nac:dt:aggregate_changed', {
1623
+ table_id: table.schema.table_id,
1624
+ agg_key: aggKey, column: colKey, old: oldV, new: newV
1625
+ });
1626
+ }
1627
+ });
1628
+ });
1629
+ }
1630
+ return aggs;
1631
+ }
1632
+
1633
+ function _dtGenRowId(table) {
1634
+ var prefix = (table.schema.row_id_field || 'r').slice(0, 1).toUpperCase();
1635
+ var n = table.current_rows.length + 1;
1636
+ var candidate;
1637
+ do {
1638
+ candidate = prefix + n;
1639
+ n++;
1640
+ } while (table.current_rows.some(function (r) { return r[table.schema.row_id_field] === candidate; }));
1641
+ return candidate;
1642
+ }
1643
+
1644
+ function registerDataTable(spec) {
1645
+ if (!spec || typeof spec !== 'object') {
1646
+ throw new Error('[NAC v2.1] registerDataTable: spec must be an object');
1647
+ }
1648
+ if (typeof spec.table_id !== 'string' || !spec.table_id) {
1649
+ throw new Error('[NAC v2.1] registerDataTable: table_id required');
1650
+ }
1651
+ if (_dataTables[spec.table_id]) {
1652
+ throw new Error('[NAC v2.1] registerDataTable: table_id "'
1653
+ + spec.table_id + '" already registered');
1654
+ }
1655
+ var subkind = spec.subkind || 'collection';
1656
+ if (['collection', 'matrix', 'readonly'].indexOf(subkind) < 0) {
1657
+ throw new Error('[NAC v2.1] registerDataTable: invalid subkind "' + subkind + '"');
1658
+ }
1659
+ /* Subkind-specific validation. */
1660
+ if (subkind === 'matrix') {
1661
+ if (!spec.row_axis || !spec.column_axis) {
1662
+ throw new Error('[NAC v2.1] registerDataTable: matrix requires row_axis + column_axis');
1663
+ }
1664
+ } else {
1665
+ if (!Array.isArray(spec.columns) || !spec.columns.length) {
1666
+ throw new Error('[NAC v2.1] registerDataTable: collection/readonly requires columns[]');
1667
+ }
1668
+ if (!spec.row_id_field) {
1669
+ throw new Error('[NAC v2.1] registerDataTable: row_id_field required for collection');
1670
+ }
1671
+ }
1672
+ var schema = {
1673
+ table_id: spec.table_id,
1674
+ scope_owner: spec.scope_owner || null,
1675
+ subkind: subkind,
1676
+ transactional: spec.transactional !== false,
1677
+ row_id_field: spec.row_id_field || null,
1678
+ columns: spec.columns || [],
1679
+ row_axis: spec.row_axis || null,
1680
+ column_axis: spec.column_axis || null,
1681
+ cell_type: spec.cell_type || 'boolean',
1682
+ supports: spec.supports || [],
1683
+ selection_mode: spec.selection_mode || 'none',
1684
+ aggregates: spec.aggregates || {},
1685
+ validators: spec.validators || []
1686
+ };
1687
+ var table = {
1688
+ schema: schema,
1689
+ current_rows: subkind === 'matrix' ? [] : (_dtDeepCopy(spec.initial_rows) || []),
1690
+ current_cells: subkind === 'matrix' ? (_dtDeepCopy(spec.initial_cells) || []) : [],
1691
+ initial_state: subkind === 'matrix'
1692
+ ? { cells: _dtDeepCopy(spec.initial_cells) || [] }
1693
+ : { rows: _dtDeepCopy(spec.initial_rows) || [] },
1694
+ selected: new Set(),
1695
+ modified: false,
1696
+ computed_fns: Object.create(null),
1697
+ _aggregates_cache: null
1698
+ };
1699
+ _dataTables[spec.table_id] = table;
1700
+ table._aggregates_cache = _dtRecomputeAggregates(table, null);
1701
+ _dtEmit('nac:dt:registered', { table_id: spec.table_id, schema: schema });
1702
+ return spec.table_id;
1703
+ }
1704
+
1705
+ function unregisterDataTable(table_id) {
1706
+ if (_dataTables[table_id]) {
1707
+ delete _dataTables[table_id];
1708
+ _dtEmit('nac:dt:unregistered', { table_id: table_id });
1709
+ }
1710
+ }
1711
+
1712
+ function registerDataTableComputed(table_id, column_key, fn) {
1713
+ var t = _dataTables[table_id];
1714
+ if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1715
+ if (typeof fn !== 'function') {
1716
+ throw new Error('[NAC v2.1] computed fn must be a function');
1717
+ }
1718
+ t.computed_fns[column_key] = fn;
1719
+ /* Recompute now so newly-attached fns reflect on existing rows. */
1720
+ t.current_rows.forEach(function (row) { _dtRecomputeRow(t, row); });
1721
+ var prev = t._aggregates_cache;
1722
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1723
+ }
1724
+
1725
+ function dt_state(table_id) {
1726
+ var t = _dataTables[table_id];
1727
+ if (!t) return null;
1728
+ if (t.schema.subkind === 'matrix') {
1729
+ return {
1730
+ cells: _dtDeepCopy(t.current_cells),
1731
+ modified: t.modified,
1732
+ valid: dt_validate(table_id).valid
1733
+ };
1734
+ }
1735
+ return {
1736
+ rows: _dtDeepCopy(t.current_rows),
1737
+ aggregates: _dtDeepCopy(t._aggregates_cache),
1738
+ modified: t.modified,
1739
+ valid: dt_validate(table_id).valid,
1740
+ selected_count: t.selected.size,
1741
+ selected_ids: Array.from(t.selected)
1742
+ };
1743
+ }
1744
+
1745
+ function dt_add_row(table_id, valuesByColumn) {
1746
+ var t = _dataTables[table_id];
1747
+ if (!t) throw new Error('[NAC v2.1] data-table not registered: ' + table_id);
1748
+ if (t.schema.subkind === 'matrix') {
1749
+ throw new Error('[NAC v2.1] add_row not applicable to matrix');
1750
+ }
1751
+ if (t.schema.subkind === 'readonly') {
1752
+ throw new Error('[NAC v2.1] add_row not allowed on readonly');
1753
+ }
1754
+ var values = valuesByColumn || {};
1755
+ var row = {};
1756
+ t.schema.columns.forEach(function (col) {
1757
+ if (col.key === t.schema.row_id_field) return;
1758
+ if (Object.prototype.hasOwnProperty.call(values, col.key)) {
1759
+ row[col.key] = values[col.key];
1760
+ } else if (col.required && !col.computed) {
1761
+ /* required but missing -- caller must provide */
1762
+ }
1763
+ });
1764
+ /* Row id: caller-provided OR auto-generated. */
1765
+ var rowId = values[t.schema.row_id_field];
1766
+ if (!rowId) rowId = _dtGenRowId(t);
1767
+ row[t.schema.row_id_field] = rowId;
1768
+ /* Validate every provided column. */
1769
+ var fail = null;
1770
+ t.schema.columns.forEach(function (col) {
1771
+ if (fail) return;
1772
+ if (col.computed) return;
1773
+ var v = row[col.key];
1774
+ var check = _dtCheckColumnValue(col, v);
1775
+ if (!check.ok) fail = { column: col.key, error: check.error };
1776
+ });
1777
+ if (fail) {
1778
+ _dtEmit('nac:dt:validation_failed', {
1779
+ table_id: t.schema.table_id,
1780
+ errors: [{ code: 'add_row_invalid', column: fail.column, message_i18n: { en: fail.error } }]
1781
+ });
1782
+ return { row_id: null, ok: false, error: fail.error, column: fail.column };
1783
+ }
1784
+ t.current_rows.push(row);
1785
+ _dtRecomputeRow(t, row);
1786
+ var prev = t._aggregates_cache;
1787
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1788
+ t.modified = true;
1789
+ _dtEmit('nac:dt:row_added', {
1790
+ table_id: t.schema.table_id, row: _dtDeepCopy(row), by: _dtBy()
1791
+ });
1792
+ return { row_id: rowId, ok: true };
1793
+ }
1794
+
1795
+ function dt_remove_row(table_id, row_id) {
1796
+ var t = _dataTables[table_id];
1797
+ if (!t || t.schema.subkind === 'matrix' || t.schema.subkind === 'readonly') return;
1798
+ var idx = -1;
1799
+ for (var i = 0; i < t.current_rows.length; i++) {
1800
+ if (t.current_rows[i][t.schema.row_id_field] === row_id) { idx = i; break; }
1801
+ }
1802
+ if (idx < 0) return;
1803
+ t.current_rows.splice(idx, 1);
1804
+ t.selected.delete(row_id);
1805
+ var prev = t._aggregates_cache;
1806
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1807
+ t.modified = true;
1808
+ _dtEmit('nac:dt:row_removed', {
1809
+ table_id: t.schema.table_id, row_id: row_id, by: _dtBy()
1810
+ });
1811
+ }
1812
+
1813
+ function dt_edit_cell(table_id, row_id, column_key, value) {
1814
+ var t = _dataTables[table_id];
1815
+ if (!t) return { ok: false, error: 'table_not_registered' };
1816
+ if (t.schema.subkind === 'matrix') {
1817
+ return { ok: false, error: 'use_dt_set_cell_for_matrix' };
1818
+ }
1819
+ if (t.schema.subkind === 'readonly') return { ok: false, error: 'readonly' };
1820
+ var col = t.schema.columns.filter(function (c) { return c.key === column_key; })[0];
1821
+ if (!col) return { ok: false, error: 'column_not_found' };
1822
+ /* computed wins over editable -- a column declared
1823
+ `computed:true` is implicitly non-editable even if the
1824
+ host forgets to set editable:false. Spec sec 18.4 ordering. */
1825
+ if (col.computed) return { ok: false, error: 'computed_column' };
1826
+ if (!col.editable) return { ok: false, error: 'column_not_editable' };
1827
+ var check = _dtCheckColumnValue(col, value);
1828
+ if (!check.ok) {
1829
+ _dtEmit('nac:dt:validation_failed', {
1830
+ table_id: t.schema.table_id,
1831
+ errors: [{ code: 'edit_cell_invalid', row_id: row_id, column: column_key,
1832
+ message_i18n: { en: check.error } }]
1833
+ });
1834
+ return { ok: false, error: check.error };
1835
+ }
1836
+ var row = t.current_rows.filter(function (r) {
1837
+ return r[t.schema.row_id_field] === row_id;
1838
+ })[0];
1839
+ if (!row) return { ok: false, error: 'row_not_found' };
1840
+ var oldVal = row[column_key];
1841
+ if (oldVal === value) return { ok: true, unchanged: true };
1842
+ row[column_key] = value;
1843
+ _dtRecomputeRow(t, row);
1844
+ var prev = t._aggregates_cache;
1845
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
1846
+ t.modified = true;
1847
+ _dtEmit('nac:dt:cell_edited', {
1848
+ table_id: t.schema.table_id,
1849
+ row_id: row_id, column: column_key,
1850
+ old: oldVal, new: value, by: _dtBy()
1851
+ });
1852
+ return { ok: true };
1853
+ }
1854
+
1855
+ function dt_read_aggregate(table_id, agg_key, column_key) {
1856
+ var t = _dataTables[table_id];
1857
+ if (!t) return null;
1858
+ if (!t._aggregates_cache || !t._aggregates_cache[agg_key]) return null;
1859
+ var v = t._aggregates_cache[agg_key][column_key];
1860
+ return v === undefined ? null : v;
1861
+ }
1862
+
1863
+ function dt_validate(table_id) {
1864
+ var t = _dataTables[table_id];
1865
+ if (!t) return { valid: false, errors: [{ code: 'table_not_registered' }] };
1866
+ var errors = [];
1867
+ /* Per-row validators. */
1868
+ (t.schema.validators || []).forEach(function (v) {
1869
+ if (v.kind !== 'row') return;
1870
+ t.current_rows.forEach(function (row) {
1871
+ var cellVal = row[v.column];
1872
+ var ok = _dtCheckOp(cellVal, v.op, v.value);
1873
+ if (!ok) errors.push({
1874
+ code: v.code, row_id: row[t.schema.row_id_field],
1875
+ column: v.column, message_i18n: v.message_i18n || null
1876
+ });
1877
+ });
1878
+ });
1879
+ /* Table-level validators. */
1880
+ (t.schema.validators || []).forEach(function (v) {
1881
+ if (v.kind !== 'table') return;
1882
+ if (v.unique_columns) {
1883
+ var seen = Object.create(null);
1884
+ t.current_rows.forEach(function (row) {
1885
+ var key = v.unique_columns.map(function (c) { return row[c]; }).join('|');
1886
+ if (seen[key]) {
1887
+ errors.push({
1888
+ code: v.code, row_id: row[t.schema.row_id_field],
1889
+ message_i18n: v.message_i18n || null
1890
+ });
1891
+ }
1892
+ seen[key] = true;
1893
+ });
1894
+ }
1895
+ if (typeof v.min_rows === 'number' && t.current_rows.length < v.min_rows) {
1896
+ errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1897
+ }
1898
+ if (typeof v.max_rows === 'number' && t.current_rows.length > v.max_rows) {
1899
+ errors.push({ code: v.code, message_i18n: v.message_i18n || null });
1900
+ }
1901
+ });
1902
+ /* Required-column validator (implicit). */
1903
+ t.schema.columns.forEach(function (col) {
1904
+ if (!col.required || col.computed) return;
1905
+ t.current_rows.forEach(function (row) {
1906
+ var v = row[col.key];
1907
+ if (v === null || v === undefined || v === '') {
1908
+ errors.push({
1909
+ code: 'required_missing', row_id: row[t.schema.row_id_field],
1910
+ column: col.key, message_i18n: { en: 'Required column missing' }
1911
+ });
1912
+ }
1913
+ });
1914
+ });
1915
+ return { valid: errors.length === 0, errors: errors };
1916
+ }
1917
+
1918
+ function _dtCheckOp(cellVal, op, value) {
1919
+ switch (op) {
1920
+ case 'gt': return typeof cellVal === 'number' && cellVal > value;
1921
+ case 'gte': return typeof cellVal === 'number' && cellVal >= value;
1922
+ case 'lt': return typeof cellVal === 'number' && cellVal < value;
1923
+ case 'lte': return typeof cellVal === 'number' && cellVal <= value;
1924
+ case 'eq': return cellVal === value;
1925
+ case 'neq': return cellVal !== value;
1926
+ case 'in': return Array.isArray(value) && value.indexOf(cellVal) >= 0;
1927
+ case 'matches': return typeof cellVal === 'string' && new RegExp(value).test(cellVal);
1928
+ default: return true;
1929
+ }
1930
+ }
1931
+
1932
+ function dt_select(table_id, target) {
1933
+ var t = _dataTables[table_id];
1934
+ if (!t || t.schema.subkind === 'matrix') return { selected_count: 0 };
1935
+ var ids = [];
1936
+ if (target === null || target === 'none') {
1937
+ ids = [];
1938
+ } else if (target === 'all' || target === 'visible') {
1939
+ ids = t.current_rows.map(function (r) { return r[t.schema.row_id_field]; });
1940
+ } else if (Array.isArray(target)) {
1941
+ ids = target.slice();
1942
+ } else if (target && target.column && target.op) {
1943
+ ids = t.current_rows
1944
+ .filter(function (r) { return _dtCheckOp(r[target.column], target.op, target.value); })
1945
+ .map(function (r) { return r[t.schema.row_id_field]; });
1946
+ } else if (typeof target === 'string') {
1947
+ ids = [target];
1948
+ }
1949
+ t.selected = new Set(ids);
1950
+ _dtEmit('nac:dt:selection_changed', {
1951
+ table_id: t.schema.table_id,
1952
+ selected_count: t.selected.size,
1953
+ selected_ids: Array.from(t.selected)
1954
+ });
1955
+ return { selected_count: t.selected.size };
1956
+ }
1957
+
1958
+ function dt_set_cell(table_id, row_slug, col_slug, value) {
1959
+ var t = _dataTables[table_id];
1960
+ if (!t) return { ok: false, error: 'table_not_registered' };
1961
+ if (t.schema.subkind !== 'matrix') {
1962
+ return { ok: false, error: 'use_dt_edit_cell_for_collection' };
1963
+ }
1964
+ /* Validate row/col exist on the axes. */
1965
+ var rowKnown = (t.schema.row_axis.values || [])
1966
+ .some(function (r) { return r.slug === row_slug; });
1967
+ var colKnown = (t.schema.column_axis.values || [])
1968
+ .some(function (c) { return c.slug === col_slug; });
1969
+ if (!rowKnown) return { ok: false, error: 'row_not_in_axis' };
1970
+ if (!colKnown) return { ok: false, error: 'col_not_in_axis' };
1971
+ var existing = null;
1972
+ for (var i = 0; i < t.current_cells.length; i++) {
1973
+ if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
1974
+ existing = t.current_cells[i]; break;
1975
+ }
1976
+ }
1977
+ var oldVal = existing ? existing.value : undefined;
1978
+ if (oldVal === value) return { ok: true, unchanged: true };
1979
+ if (existing) {
1980
+ existing.value = value;
1981
+ } else {
1982
+ t.current_cells.push({ row: row_slug, col: col_slug, value: value });
1983
+ }
1984
+ t.modified = true;
1985
+ _dtEmit('nac:dt:matrix_cell_set', {
1986
+ table_id: t.schema.table_id,
1987
+ row: row_slug, col: col_slug, old: oldVal, new: value, by: _dtBy()
1988
+ });
1989
+ return { ok: true };
1990
+ }
1991
+
1992
+ function dt_get_cell(table_id, row_slug, col_slug) {
1993
+ var t = _dataTables[table_id];
1994
+ if (!t || t.schema.subkind !== 'matrix') return undefined;
1995
+ for (var i = 0; i < t.current_cells.length; i++) {
1996
+ if (t.current_cells[i].row === row_slug && t.current_cells[i].col === col_slug) {
1997
+ return t.current_cells[i].value;
1998
+ }
1999
+ }
2000
+ return undefined;
2001
+ }
2002
+
2003
+ function dt_commit(table_id) {
2004
+ var t = _dataTables[table_id];
2005
+ if (!t) return { ok: false, error: 'table_not_registered' };
2006
+ var v = dt_validate(table_id);
2007
+ if (!v.valid) {
2008
+ _dtEmit('nac:dt:validation_failed', {
2009
+ table_id: t.schema.table_id, errors: v.errors
2010
+ });
2011
+ return { ok: false, errors: v.errors };
2012
+ }
2013
+ /* Build audit diff vs initial_state. */
2014
+ var initial = t.initial_state;
2015
+ var finalState = t.schema.subkind === 'matrix'
2016
+ ? { cells: _dtDeepCopy(t.current_cells) }
2017
+ : { rows: _dtDeepCopy(t.current_rows) };
2018
+ /* Reset modified + replace initial_state so a subsequent
2019
+ discard would revert to THIS state, not the original. */
2020
+ t.initial_state = _dtDeepCopy(finalState);
2021
+ t.modified = false;
2022
+ _dtEmit('nac:dt:committed', {
2023
+ table_id: t.schema.table_id,
2024
+ final_state: finalState,
2025
+ audit_diff: { initial: initial, final: finalState }
2026
+ });
2027
+ return { ok: true, final_state: finalState };
2028
+ }
2029
+
2030
+ function dt_discard(table_id) {
2031
+ var t = _dataTables[table_id];
2032
+ if (!t) return;
2033
+ if (t.schema.subkind === 'matrix') {
2034
+ t.current_cells = _dtDeepCopy(t.initial_state.cells) || [];
2035
+ } else {
2036
+ t.current_rows = _dtDeepCopy(t.initial_state.rows) || [];
2037
+ }
2038
+ t.selected.clear();
2039
+ var prev = t._aggregates_cache;
2040
+ t._aggregates_cache = _dtRecomputeAggregates(t, prev);
2041
+ t.modified = false;
2042
+ _dtEmit('nac:dt:discarded', { table_id: t.schema.table_id });
2043
+ }
2044
+
2045
+ /* describe_v2() extension: surface every registered data-table. */
2046
+ function _dtSummariseAll() {
2047
+ var out = [];
2048
+ Object.keys(_dataTables).forEach(function (id) {
2049
+ var t = _dataTables[id];
2050
+ out.push({
2051
+ table_id: id,
2052
+ scope_owner: t.schema.scope_owner,
2053
+ subkind: t.schema.subkind,
2054
+ schema: {
2055
+ columns: t.schema.columns,
2056
+ row_axis: t.schema.row_axis,
2057
+ column_axis: t.schema.column_axis,
2058
+ supports: t.schema.supports,
2059
+ aggregates: t.schema.aggregates,
2060
+ selection_mode: t.schema.selection_mode,
2061
+ row_id_field: t.schema.row_id_field
2062
+ },
2063
+ current_state: dt_state(id)
2064
+ });
2065
+ });
2066
+ return out;
2067
+ }
2068
+
2069
+ /* Exports for v2.1 data-table primitive. */
2070
+ NAC.registerDataTable = registerDataTable;
2071
+ NAC.unregisterDataTable = unregisterDataTable;
2072
+ NAC.registerDataTableComputed = registerDataTableComputed;
2073
+ NAC.dt_state = dt_state;
2074
+ NAC.dt_add_row = dt_add_row;
2075
+ NAC.dt_remove_row = dt_remove_row;
2076
+ NAC.dt_edit_cell = dt_edit_cell;
2077
+ NAC.dt_read_aggregate = dt_read_aggregate;
2078
+ NAC.dt_validate = dt_validate;
2079
+ NAC.dt_select = dt_select;
2080
+ NAC.dt_set_cell = dt_set_cell;
2081
+ NAC.dt_get_cell = dt_get_cell;
2082
+ NAC.dt_commit = dt_commit;
2083
+ NAC.dt_discard = dt_discard;
2084
+ /* Exposed for tests + describe_v2 extension. */
2085
+ NAC.__v2_dataTables = _dataTables;
2086
+ NAC.__v2_dtSummariseAll = _dtSummariseAll;
2087
+
2088
+ /* Bump version constants */
2089
+ NAC.version_v2 = '2.1.0-rc1';
2090
+ NAC.spec_version_v2 = '2.1';
2091
+
2092
+ document.dispatchEvent(new CustomEvent('nac:v2_installed', {
2093
+ detail: { version: '2.0.0' }, bubbles: true
2094
+ }));
2095
+ })(typeof window !== 'undefined' ? window : globalThis);
2096
+