@nac3/runtime 2.5.2 → 2.8.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.
@@ -34,13 +34,50 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
34
34
  NacChat.setLang(code)
35
35
  NacChat.snapshotTree() // returns the tree posted to backend
36
36
  NacChat.onAction(kind, fn) // override or extend a kind handler
37
+ NacChat.debug = true // turn the diagnostic log on (OFF by default)
38
+
39
+ THE DIAGNOSTIC LOG IS OFF BY DEFAULT, and that is a deliberate
40
+ change of behaviour made on 2026-11-24. This file carried five
41
+ unconditional console.log calls in published code, and three of them
42
+ printed CONTENT rather than control flow: the language model's reply
43
+ to the user, and -- twice, in the speech path -- the text the
44
+ microphone had just transcribed. An adopter embedding this on a page
45
+ where someone dictates a name, an address or a diagnosis was putting
46
+ that text in the browser console on every utterance, with no switch
47
+ to stop it and nothing in the documentation saying so.
48
+
49
+ What did NOT change: console.warn and console.error still speak
50
+ unconditionally. An adopter has to be able to see that something
51
+ broke; a silent failure is the thing this project argues against.
52
+ Only the diagnostics are behind the switch.
53
+
54
+ To turn them back on, either set NacChat.debug = true at runtime or
55
+ define window.NAC_CHAT_DEBUG = true before this file loads (the
56
+ second form exists because the most useful diagnostics happen during
57
+ init, before anyone has a handle to the object).
37
58
 
38
59
  ASCII-only.
39
60
  =============================================================== */
40
61
  (function (global) {
41
62
  'use strict';
42
63
 
64
+ /* The diagnostic log, off unless asked for. See the header: three of
65
+ these printed user content, so the default has to be quiet. */
66
+ function _dbgEnabled() {
67
+ if (NacChat && NacChat.debug === true) return true;
68
+ return global.NAC_CHAT_DEBUG === true;
69
+ }
70
+ function _dbg() {
71
+ if (!_dbgEnabled()) return;
72
+ if (!global.console || typeof global.console.log !== 'function') return;
73
+ global.console.log.apply(global.console, arguments);
74
+ }
75
+
43
76
  var NacChat = {
77
+ /* Public, additive, and documented in the header. Not a private
78
+ underscore field: an adopter debugging a page needs to be able
79
+ to reach for it without reading the source. */
80
+ debug: false,
44
81
  _endpoint: '/crm/api/v1/yujin/nac-demo',
45
82
  _sessionId: 'sess_' + Math.random().toString(36).slice(2, 10),
46
83
  _lang: 'es',
@@ -290,10 +327,10 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
290
327
  }
291
328
  }
292
329
  } catch (_) {}
293
- console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
330
+ _dbg('[nac-chat] snapshot plugins (' + plugins.length + '):',
294
331
  plugins.map(function (p) { return p.plugin; }).join(', '));
295
332
  if (out.data_tables && out.data_tables.length) {
296
- console.log('[nac-chat] data_tables:',
333
+ _dbg('[nac-chat] data_tables:',
297
334
  out.data_tables.map(function (t) {
298
335
  return t.table_id + ' (' + t.subkind + ')';
299
336
  }).join(', '));
@@ -519,8 +556,12 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
519
556
  returned so 'chat says X but nothing happens' is
520
557
  distinguishable from 'chat dispatched X but it failed
521
558
  silently'. If the LLM only emits a {message} with no
522
- actions, this log makes it obvious. */
523
- console.log('[nac-chat] backend response: message="' + message
559
+ actions, this log makes it obvious.
560
+
561
+ Behind NacChat.debug since 2026-11-24: `message` is the model's
562
+ reply to the user, so this line published user-facing content to
563
+ the console of every page that embedded the client. */
564
+ _dbg('[nac-chat] backend response: message="' + message
524
565
  + '" actions=' + JSON.stringify(actions));
525
566
  if (message) {
526
567
  _bubble('bot', message);
@@ -559,11 +600,11 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
559
600
  if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
560
601
  if (!text) return;
561
602
  if (_isBotEcho(text)) {
562
- console.log('[nac-chat-stt] dropping bot-echo:', text);
603
+ _dbg('[nac-chat-stt] dropping bot-echo:', text);
563
604
  return;
564
605
  }
565
606
  if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
566
- console.log('[nac-chat-stt] dropping during TTS:', text);
607
+ _dbg('[nac-chat-stt] dropping during TTS:', text);
567
608
  return;
568
609
  }
569
610
  NacChat.send(text);
@@ -34,13 +34,50 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
34
34
  NacChat.setLang(code)
35
35
  NacChat.snapshotTree() // returns the tree posted to backend
36
36
  NacChat.onAction(kind, fn) // override or extend a kind handler
37
+ NacChat.debug = true // turn the diagnostic log on (OFF by default)
38
+
39
+ THE DIAGNOSTIC LOG IS OFF BY DEFAULT, and that is a deliberate
40
+ change of behaviour made on 2026-11-24. This file carried five
41
+ unconditional console.log calls in published code, and three of them
42
+ printed CONTENT rather than control flow: the language model's reply
43
+ to the user, and -- twice, in the speech path -- the text the
44
+ microphone had just transcribed. An adopter embedding this on a page
45
+ where someone dictates a name, an address or a diagnosis was putting
46
+ that text in the browser console on every utterance, with no switch
47
+ to stop it and nothing in the documentation saying so.
48
+
49
+ What did NOT change: console.warn and console.error still speak
50
+ unconditionally. An adopter has to be able to see that something
51
+ broke; a silent failure is the thing this project argues against.
52
+ Only the diagnostics are behind the switch.
53
+
54
+ To turn them back on, either set NacChat.debug = true at runtime or
55
+ define window.NAC_CHAT_DEBUG = true before this file loads (the
56
+ second form exists because the most useful diagnostics happen during
57
+ init, before anyone has a handle to the object).
37
58
 
38
59
  ASCII-only.
39
60
  =============================================================== */
40
61
  (function (global) {
41
62
  'use strict';
42
63
 
64
+ /* The diagnostic log, off unless asked for. See the header: three of
65
+ these printed user content, so the default has to be quiet. */
66
+ function _dbgEnabled() {
67
+ if (NacChat && NacChat.debug === true) return true;
68
+ return global.NAC_CHAT_DEBUG === true;
69
+ }
70
+ function _dbg() {
71
+ if (!_dbgEnabled()) return;
72
+ if (!global.console || typeof global.console.log !== 'function') return;
73
+ global.console.log.apply(global.console, arguments);
74
+ }
75
+
43
76
  var NacChat = {
77
+ /* Public, additive, and documented in the header. Not a private
78
+ underscore field: an adopter debugging a page needs to be able
79
+ to reach for it without reading the source. */
80
+ debug: false,
44
81
  _endpoint: '/crm/api/v1/yujin/nac-demo',
45
82
  _sessionId: 'sess_' + Math.random().toString(36).slice(2, 10),
46
83
  _lang: 'es',
@@ -290,10 +327,10 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
290
327
  }
291
328
  }
292
329
  } catch (_) {}
293
- console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
330
+ _dbg('[nac-chat] snapshot plugins (' + plugins.length + '):',
294
331
  plugins.map(function (p) { return p.plugin; }).join(', '));
295
332
  if (out.data_tables && out.data_tables.length) {
296
- console.log('[nac-chat] data_tables:',
333
+ _dbg('[nac-chat] data_tables:',
297
334
  out.data_tables.map(function (t) {
298
335
  return t.table_id + ' (' + t.subkind + ')';
299
336
  }).join(', '));
@@ -519,8 +556,12 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
519
556
  returned so 'chat says X but nothing happens' is
520
557
  distinguishable from 'chat dispatched X but it failed
521
558
  silently'. If the LLM only emits a {message} with no
522
- actions, this log makes it obvious. */
523
- console.log('[nac-chat] backend response: message="' + message
559
+ actions, this log makes it obvious.
560
+
561
+ Behind NacChat.debug since 2026-11-24: `message` is the model's
562
+ reply to the user, so this line published user-facing content to
563
+ the console of every page that embedded the client. */
564
+ _dbg('[nac-chat] backend response: message="' + message
524
565
  + '" actions=' + JSON.stringify(actions));
525
566
  if (message) {
526
567
  _bubble('bot', message);
@@ -559,11 +600,11 @@ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== '
559
600
  if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
560
601
  if (!text) return;
561
602
  if (_isBotEcho(text)) {
562
- console.log('[nac-chat-stt] dropping bot-echo:', text);
603
+ _dbg('[nac-chat-stt] dropping bot-echo:', text);
563
604
  return;
564
605
  }
565
606
  if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
566
- console.log('[nac-chat-stt] dropping during TTS:', text);
607
+ _dbg('[nac-chat-stt] dropping during TTS:', text);
567
608
  return;
568
609
  }
569
610
  NacChat.send(text);
@@ -21,6 +21,8 @@
21
21
  - NAC.registerCatalog(catalog) i18n catalog registration
22
22
  - NAC.locale(code?) locale getter/setter
23
23
  - NAC.setSupportedLocales(arr) extend supported list
24
+ - NAC.registerCatalog(obj[, {replace}]) merge translations; the
25
+ option restores the pre-2.7.0 whole-entry replacement
24
26
  - NAC.setRTLLocales(arr) extend RTL list
25
27
  - NAC.set_provenance_secret(secret) HMAC secret registration
26
28
 
@@ -81,8 +83,39 @@
81
83
 
82
84
  function locale(code) {
83
85
  if (code === undefined) return _currentLocale;
86
+ /* REFUSE an unsupported locale (TF-A08).
87
+
88
+ It used to console.warn and then assign on the next line, which
89
+ is the worst of both: the host is told something is wrong and
90
+ the wrong thing happens anyway. Two consequences followed.
91
+
92
+ First, the state was a lie: NAC.locale() reported a locale the
93
+ runtime does not support, and every t() lookup fell through the
94
+ chain to Spanish without the caller knowing why.
95
+
96
+ Second, and worse because it is silent: an invalid code is not
97
+ in the RTL list either, so `ar` misspelled as `ar-SA` or `arr`
98
+ stopped flipping dir=rtl and the page rendered Arabic
99
+ left-to-right. A typo in a locale code became a layout bug two
100
+ screens away.
101
+
102
+ And the file was already inconsistent with itself:
103
+ setSupportedLocales, setRTLLocales and set_provenance_secret all
104
+ THROW on bad input. This one warned. Nothing explained the
105
+ difference because there was none.
106
+
107
+ The escape hatch is not new and is not invented here:
108
+ setSupportedLocales(arr) has existed since 2.0 and is
109
+ documented at the top of this file as "extend supported list".
110
+ A host that wants an eleventh locale says so, once, instead of
111
+ discovering that a typo half-works. */
84
112
  if (_supported.indexOf(code) < 0) {
85
- console.warn('[NAC v2] locale', code, 'not in supported list');
113
+ throw new Error('[NAC v2] locale: ' + JSON.stringify(code)
114
+ + ' is not a supported locale. Supported: ' + _supported.join(',')
115
+ + '. To add one, call NAC.setSupportedLocales([...]) first --'
116
+ + ' this used to warn and then set it anyway, which left the'
117
+ + ' runtime reporting a locale it cannot resolve and silently'
118
+ + ' stopped RTL from applying.');
86
119
  }
87
120
  _currentLocale = code;
88
121
  /* Auto-apply dir=rtl unless host opted out via setAutoRTL(false). */
@@ -99,11 +132,67 @@
99
132
  detail: { locale: code, autoRTL: _autoRTL }, bubbles: true
100
133
  }));
101
134
  }
102
- function registerCatalog(obj) {
135
+ /* MERGE per locale, do not replace per key (TF-A09).
136
+
137
+ The old body was one line:
138
+
139
+ Object.keys(obj).forEach(function (k) { _catalog[k] = obj[k]; });
140
+
141
+ -- assignment, so registering a key replaced its WHOLE entry. A
142
+ host that had a key in all ten locales and then called
143
+ registerCatalog({ 'save.label': { en: 'Save' } }) -- to correct
144
+ the English, say -- lost the other nine. Nothing was reported,
145
+ because overwriting is what assignment does.
146
+
147
+ What makes it expensive is where the symptom comes out: not here,
148
+ and not in English. t() falls through requested -> es -> en ->
149
+ first available, so the nine missing locales keep RETURNING
150
+ SOMETHING. A French user sees Spanish, three screens away, and
151
+ the cause is a line of boot code that looked like it added a
152
+ translation.
153
+
154
+ The runtime has already decided this question once, in the other
155
+ direction: syncPlugin exists precisely so a caller can REPLACE
156
+ instead of add, because add was the default and replacing needed
157
+ asking for. The catalogue had no equivalent, so it only had the
158
+ destructive half.
159
+
160
+ So: merge by locale, and say so when a value is really being
161
+ overwritten -- an overwrite is sometimes exactly what the host
162
+ means, and silence is what made this hard to find. A caller that
163
+ wants the old semantics asks for them:
164
+
165
+ NAC.registerCatalog(obj, { replace: true }) */
166
+ function registerCatalog(obj, opts) {
103
167
  if (!obj || typeof obj !== 'object') {
104
168
  throw new Error('[NAC v2] registerCatalog requires object');
105
169
  }
106
- Object.keys(obj).forEach(function (k) { _catalog[k] = obj[k]; });
170
+ var replace = !!(opts && opts.replace);
171
+ Object.keys(obj).forEach(function (k) {
172
+ var incoming = obj[k];
173
+ /* A non-object entry has no locales to merge; assign it, which
174
+ is what the old code did and the only thing that makes sense. */
175
+ if (replace || !incoming || typeof incoming !== 'object'
176
+ || !_catalog[k] || typeof _catalog[k] !== 'object') {
177
+ _catalog[k] = incoming;
178
+ return;
179
+ }
180
+ var existing = _catalog[k];
181
+ var merged = {};
182
+ Object.keys(existing).forEach(function (loc) { merged[loc] = existing[loc]; });
183
+ Object.keys(incoming).forEach(function (loc) {
184
+ if (Object.prototype.hasOwnProperty.call(existing, loc)
185
+ && existing[loc] !== incoming[loc]) {
186
+ if (typeof console !== 'undefined' && console.warn) {
187
+ console.warn('[NAC v2] registerCatalog: overwriting ' + k + '.' + loc
188
+ + ' -- the other locales of this key are kept. Pass { replace: true }'
189
+ + ' to drop them on purpose.');
190
+ }
191
+ }
192
+ merged[loc] = incoming[loc];
193
+ });
194
+ _catalog[k] = merged;
195
+ });
107
196
  }
108
197
  function t(key, opts) {
109
198
  opts = opts || {};
@@ -111,7 +200,25 @@
111
200
  var entry = _catalog[key];
112
201
  if (!entry) return opts.fallback || key;
113
202
  if (entry[loc]) return entry[loc];
114
- /* Fallback chain: requested -> es -> en -> first available */
203
+ /* Fallback chain: requested -> es -> en -> first available.
204
+
205
+ 2.7.0 (TF-A10) -- WHY es BEFORE en, written down because for
206
+ two years it was not, and an undocumented resolution order is a
207
+ coin flip an adopter discovers in production. SPEC.md section
208
+ 3 now publishes this chain normatively; this comment says what
209
+ the sentence there cannot.
210
+
211
+ The order is DELIBERATE and it is kept (D-14, owner delegation
212
+ of 2026-11-24). It does NOT contradict "the English is
213
+ normative": that rule is about the SPECIFICATION DOCUMENT, not
214
+ about which string a host's own catalogue serves. Flipping it
215
+ to en-first would change, with no bug fixed, what every adopter
216
+ with a Spanish-authored catalogue and an incomplete locale map
217
+ renders today -- a visible, silent change, which rule 7 of the
218
+ working agreement forbids and nothing in the list asked for.
219
+ A host that wants another order declares its own locales: a
220
+ catalogue covering the 10 locales (which section 8 level 2
221
+ REQUIRES) never reaches this line at all. */
115
222
  if (entry.es) return entry.es;
116
223
  if (entry.en) return entry.en;
117
224
  var firstKey = Object.keys(entry)[0];
@@ -126,6 +233,17 @@
126
233
  else if (Array.isArray(s)) _provenanceSecrets = s.slice();
127
234
  else if (s == null) _provenanceSecrets = [];
128
235
  else throw new Error('[NAC v2] set_provenance_secret expects string|string[]');
236
+ /* 2.7.0 (TF-A17): SPEC.md section 7.2 publishes the HMAC-signed
237
+ manifest example as set_provenance_secret() followed by
238
+ register(). Manifest verification had to land in the CORE
239
+ runtime -- register() lives there and is synchronous -- and the
240
+ core cannot see this closure, so the secret is pushed across.
241
+ Without this line the published example would set a secret the
242
+ verifier never receives, and a correctly signed manifest would
243
+ be recorded as "nobody could tell". */
244
+ if (NAC && typeof NAC.set_manifest_secret === 'function') {
245
+ try { NAC.set_manifest_secret(_provenanceSecrets.slice()); } catch (_) {}
246
+ }
129
247
  /* v2.0-rc3 (Claude T6-F2): warm the crypto path now that we
130
248
  have a secret registered; first agent sign won't pay the
131
249
  cold-start cost. */
@@ -469,7 +587,14 @@
469
587
  if (entry.element) {
470
588
  entry.element.setAttribute('data-nac-id', fullSlug);
471
589
  entry.element.setAttribute('data-nac-parent', chain.join(' '));
472
- if (entry.role) entry.element.setAttribute('role', entry.role);
590
+ /* PND-135: the role the host declared, resolved against the
591
+ vocabulary and written where the protocol reads it. An
592
+ undeclared word is reported instead of planted -- this
593
+ path never threw and must not start: an adopter upgrading
594
+ a minor version does not get an exception. */
595
+ var _regRole = _declaredRole(entry.role);
596
+ if (entry.role && !_regRole) _warnUnderivableRole(fullSlug, entry.element);
597
+ _applyRoleAttr(entry.element, _regRole);
473
598
  if (entry.label_i18n) {
474
599
  var lbl = t.bind(null);
475
600
  var labelText = (function () {
@@ -618,20 +743,227 @@
618
743
  return 'auto_' + (Math.abs(h)).toString(36);
619
744
  }
620
745
 
746
+ /* ---------------------------------------------------------------
747
+ ROLE DERIVATION (rewritten 2026-11-27, PND-135)
748
+
749
+ WHAT IT DID, measured 2026-11-26 against an ERP with 920
750
+ interface modules -- the exact case the brownfield path exists
751
+ for. This function returned four words that NO registry declares:
752
+ `link` for an <a href>, `toggle` for a checkbox, `select` for a
753
+ <select>, and `interactive` for anything else. None of the four
754
+ is in the normative table of SPEC.md section 1, none is one of
755
+ the seven declared aliases of 1.5, and none is in the runtime's
756
+ own known-role set. And autoRegister did not keep them to itself:
757
+ it WROTE them onto the adopter's elements.
758
+
759
+ Why that was not cosmetic. SPEC 1.3 says a NAC-strict runtime
760
+ SHOULD refuse an unknown role at register time, and strict is the
761
+ default since 2.3 -- so the path this project opened in 2.0 to
762
+ adopt a legacy tree produced exactly what the adopter's own
763
+ runtime rejects. It is the same producer/consumer asymmetry 2.8.0
764
+ closed for the 52 roles the tree used and the text did not
765
+ declare, arriving from the other direction.
766
+
767
+ THE DECISION, taken 2026-11-27 and written here rather than in a
768
+ commit message: the four are MAPPED to canonical roles, and
769
+ `interactive` is not mapped at all because it is not a role --
770
+ it is the absence of one. Declaring the four as new roles was
771
+ the wrong half of the fork: a vocabulary that grows every time a
772
+ derivation cannot decide is a vocabulary that means nothing.
773
+
774
+ And the derivation now ASKS instead of asserting: every word it
775
+ is about to return goes through the runtime's own vocabulary
776
+ (NAC.canonical_role + NAC.roles), so a page that declared its
777
+ own role with NAC.register_role() -- the door 2.8.0 opened -- is
778
+ honoured here too, and a word this table gets wrong is caught at
779
+ runtime rather than planted. scripts/check-role-registries.mjs
780
+ confronts the two tables below against the runtime's set as a
781
+ SIXTH registry, so they cannot drift from it in silence.
782
+ --------------------------------------------------------------- */
783
+
784
+ /* ARIA role -> NAC role. Two different vocabularies: the ARIA role
785
+ says what a thing IS to assistive technology, the NAC role says
786
+ what an agent can DO with it, and the old code treated them as
787
+ the same string. Absent from this table = cannot be derived, which
788
+ is a decision and not an omission: `img`, `presentation` and
789
+ `tooltip` have no NAC role, and inventing one for them is what
790
+ this item is about. */
791
+ var _ARIA_TO_NAC = {
792
+ 'button': 'button',
793
+ 'link': 'action',
794
+ 'menuitem': 'action',
795
+ 'menuitemcheckbox': 'option',
796
+ 'menuitemradio': 'option',
797
+ 'checkbox': 'option',
798
+ 'radio': 'option',
799
+ 'switch': 'option',
800
+ 'option': 'option',
801
+ 'textbox': 'field',
802
+ 'searchbox': 'field',
803
+ 'spinbutton': 'field',
804
+ 'combobox': 'combobox',
805
+ 'listbox': 'listbox',
806
+ 'slider': 'slider',
807
+ 'tab': 'tab',
808
+ 'tablist': 'tablist',
809
+ 'tabpanel': 'tabpanel',
810
+ 'dialog': 'modal',
811
+ 'alertdialog': 'confirm-dialog',
812
+ 'status': 'status',
813
+ 'alert': 'status',
814
+ 'progressbar': 'status',
815
+ 'log': 'log',
816
+ 'menu': 'menu',
817
+ 'menubar': 'menu',
818
+ 'navigation': 'navigation',
819
+ 'region': 'region',
820
+ 'group': 'region',
821
+ 'banner': 'banner',
822
+ 'list': 'list',
823
+ 'listitem': 'row',
824
+ 'row': 'row',
825
+ 'tree': 'tree',
826
+ 'treeitem': 'tree-node',
827
+ 'table': 'data-table',
828
+ 'grid': 'data-table',
829
+ 'treegrid': 'data-table'
830
+ };
831
+
832
+ /* Tag (and, for the two tags where the type decides, tag:type) ->
833
+ NAC role. `a` without an href is NOT here: an anchor with no
834
+ destination is not an action, and the old code called it
835
+ `interactive`. */
836
+ var _TAG_TO_NAC = {
837
+ 'button': 'button',
838
+ 'a': 'action',
839
+ 'summary': 'accordion-toggle',
840
+ 'textarea': 'field',
841
+ 'input': 'field',
842
+ 'input:checkbox': 'option',
843
+ 'input:radio': 'option',
844
+ 'input:range': 'slider',
845
+ 'select': 'combobox',
846
+ 'select:multiple': 'listbox'
847
+ };
848
+
849
+ /* Every word the two tables can produce, computed once. It is what
850
+ the derivation falls back to when the runtime is older than 2.8
851
+ and cannot be asked -- never a hand-typed role list, which is the
852
+ defect that made the static lint call conforming pages wrong for
853
+ four minor versions. */
854
+ var _DERIVABLE_ROLES = (function () {
855
+ var out = [];
856
+ [_ARIA_TO_NAC, _TAG_TO_NAC].forEach(function (table) {
857
+ Object.keys(table).forEach(function (k) {
858
+ if (out.indexOf(table[k]) < 0) out.push(table[k]);
859
+ });
860
+ });
861
+ return out;
862
+ })();
863
+
864
+ /* The word, only if the vocabulary declares it. Returns the
865
+ canonical spelling (so a legacy alias arrives resolved) or null,
866
+ and null MEANS null: the caller does not get a guess. */
867
+ function _declaredRole(word) {
868
+ if (!word) return null;
869
+ var w = String(word).toLowerCase();
870
+ try {
871
+ if (typeof NAC.canonical_role === 'function') {
872
+ w = NAC.canonical_role(w) || w;
873
+ }
874
+ if (typeof NAC.roles === 'function') {
875
+ var v = NAC.roles() || {};
876
+ if (Array.isArray(v.canonical) && v.canonical.indexOf(w) >= 0) return w;
877
+ if (Array.isArray(v.registered) && v.registered.some(function (r) {
878
+ return r && (r.role === w || r === w);
879
+ })) return w;
880
+ /* The vocabulary answered, and it does not know this word.
881
+ That is an answer, not a reason to fall through. */
882
+ return null;
883
+ }
884
+ } catch (_) { /* fall through to the table */ }
885
+ return _DERIVABLE_ROLES.indexOf(w) >= 0 ? w : null;
886
+ }
887
+
621
888
  function _deriveRole(el) {
622
- var tag = el.tagName.toLowerCase();
623
- var attrRole = el.getAttribute('role');
624
- if (attrRole) return attrRole;
625
- if (tag === 'button') return 'button';
626
- if (tag === 'a' && el.hasAttribute('href')) return 'link';
889
+ if (!el || !el.getAttribute) return null;
890
+
891
+ /* 1. The protocol's own attribute, first: if the author already
892
+ said what this is, nothing here is a derivation. */
893
+ var declared = el.getAttribute('data-nac-role');
894
+ if (declared) return _declaredRole(declared);
895
+
896
+ /* 2. The ARIA role, through the mapping -- and if it is not in the
897
+ mapping, it still gets its chance at the vocabulary, because
898
+ an earlier version of THIS function wrote NAC roles into the
899
+ ARIA attribute and those trees exist. */
900
+ var aria = el.getAttribute('role');
901
+ if (aria) {
902
+ var a = String(aria).toLowerCase();
903
+ return _declaredRole(_ARIA_TO_NAC[a] || a);
904
+ }
905
+
906
+ /* 3. The element itself. */
907
+ var tag = (el.tagName || '').toLowerCase();
627
908
  if (tag === 'input') {
628
- var t = el.getAttribute('type') || 'text';
629
- if (t === 'checkbox' || t === 'radio') return 'toggle';
630
- return 'field';
909
+ var t = String(el.getAttribute('type') || 'text').toLowerCase();
910
+ return _declaredRole(_TAG_TO_NAC['input:' + t] || _TAG_TO_NAC.input);
911
+ }
912
+ if (tag === 'select') {
913
+ var multi = el.hasAttribute && el.hasAttribute('multiple');
914
+ return _declaredRole(multi ? _TAG_TO_NAC['select:multiple'] : _TAG_TO_NAC.select);
631
915
  }
632
- if (tag === 'textarea') return 'field';
633
- if (tag === 'select') return 'select';
634
- return 'interactive';
916
+ if (tag === 'a') {
917
+ return (el.hasAttribute && el.hasAttribute('href'))
918
+ ? _declaredRole(_TAG_TO_NAC.a) : null;
919
+ }
920
+ if (_TAG_TO_NAC[tag]) return _declaredRole(_TAG_TO_NAC[tag]);
921
+
922
+ /* 4. data-nac-action: the author declared an action on this
923
+ element, so `action` is READ rather than guessed. This is
924
+ what the cards of example-v20-full.php get, and what used to
925
+ come back as `interactive`. */
926
+ if (el.getAttribute('data-nac-action')) return _declaredRole('action');
927
+
928
+ /* 5. Nothing. The caller says so out loud; it does not invent. */
929
+ return null;
930
+ }
931
+
932
+ /* The role goes where the protocol reads it: data-nac-role.
933
+
934
+ Until 2026-11-27 all three registration paths wrote it into the
935
+ ARIA `role` attribute instead -- a category error with two shapes.
936
+ For `button` and `link` it wrote the element's OWN implicit ARIA
937
+ role back onto it, which changes nothing; for `toggle`, `select`,
938
+ `field` and `interactive` it wrote tokens that do not exist in
939
+ WAI-ARIA, which a user agent ignores -- so no assistive technology
940
+ ever saw any of it, while `data-nac-role`, the attribute the
941
+ runtime and the static lint both read, was left empty.
942
+
943
+ Only when absent, like every other attribute these paths write: an
944
+ author who declared a role keeps it. */
945
+ function _applyRoleAttr(el, role) {
946
+ if (!el || !role || !el.setAttribute) return;
947
+ if (!el.getAttribute('data-nac-role')) el.setAttribute('data-nac-role', role);
948
+ }
949
+
950
+ /* A derivation that came back empty is reported, not swallowed: the
951
+ adopter has three ways to answer it (declare data-nac-role, pass
952
+ derive.role, or register the vocabulary this tree uses with
953
+ NAC.register_role) and no way to learn that from silence. */
954
+ function _warnUnderivableRole(slug, el) {
955
+ try {
956
+ document.dispatchEvent(new CustomEvent('nac:autoregister_role_underivable', {
957
+ detail: {
958
+ slug: slug,
959
+ tag: (el && el.tagName) ? el.tagName.toLowerCase() : null,
960
+ aria_role: (el && el.getAttribute) ? (el.getAttribute('role') || null) : null,
961
+ hint: 'no canonical NAC role could be derived: declare data-nac-role, '
962
+ + 'pass derive.role, or NAC.register_role() the vocabulary this tree uses'
963
+ },
964
+ bubbles: true
965
+ }));
966
+ } catch (_) { /* headless (SPEC 19): no document to dispatch on */ }
635
967
  }
636
968
 
637
969
  function _deriveLabel(el) {
@@ -692,6 +1024,11 @@
692
1024
  var role = (opts.derive && opts.derive.role === 'auto')
693
1025
  ? _deriveRole(el)
694
1026
  : (opts.derive && opts.derive.role) || _deriveRole(el);
1027
+ /* An explicit derive.role is the HOST talking, so it is resolved
1028
+ against the vocabulary too rather than trusted blindly -- the
1029
+ same courtesy the derivation gets, for the same reason. */
1030
+ if (role) role = _declaredRole(role);
1031
+ if (!role) _warnUnderivableRole(fullSlug, el);
695
1032
 
696
1033
  var entry = {
697
1034
  slug: fullSlug,
@@ -708,7 +1045,7 @@
708
1045
  if (parentSlug) {
709
1046
  el.setAttribute('data-nac-parent', parentSlug.split(SEPARATOR).join(' '));
710
1047
  }
711
- if (role && !el.getAttribute('role')) el.setAttribute('role', role);
1048
+ _applyRoleAttr(el, role);
712
1049
  if (labelI18n && !el.getAttribute('aria-label')) {
713
1050
  var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
714
1051
  el.setAttribute('aria-label', lab);
@@ -816,6 +1153,9 @@
816
1153
  var role = (rule.derive && rule.derive.role)
817
1154
  ? rule.derive.role(el)
818
1155
  : _deriveRole(el);
1156
+ /* PND-135: a rule's own derive.role goes through the
1157
+ vocabulary like everything else. */
1158
+ role = _declaredRole(role);
819
1159
  var labelI18n = (rule.derive && rule.derive.label_i18n)
820
1160
  ? rule.derive.label_i18n(el)
821
1161
  : (function () { var o={}; o[_currentLocale]=_deriveLabel(el); return o; })();
@@ -833,9 +1173,10 @@
833
1173
  adopted: true,
834
1174
  registered_at: Date.now()
835
1175
  };
1176
+ if (!role) _warnUnderivableRole(fullSlug, el);
836
1177
  _scopes[fullSlug] = entry;
837
1178
  el.setAttribute('data-nac-id', fullSlug);
838
- if (role && !el.getAttribute('role')) el.setAttribute('role', role);
1179
+ _applyRoleAttr(el, role);
839
1180
  if (labelI18n && !el.getAttribute('aria-label')) {
840
1181
  var lab = labelI18n[_currentLocale] || labelI18n.es || labelI18n.en || fullSlug;
841
1182
  el.setAttribute('aria-label', lab);