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