@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.
package/dist/cli-lint.mjs CHANGED
@@ -1,15 +1,122 @@
1
- // Static lint helper for NAC CLI.
2
- // Plain regex-based; intentionally tolerant of malformed input.
1
+ /* =====================================================================
2
+ cli-lint.mjs -- the static lint behind `nac validate <dir>`.
3
+
4
+ A REAL SOURCE FILE since 2026-11-24 (TF-B04). Until then this module
5
+ did not exist on disk: it was produced by buildCliLint() in
6
+ runtime/build.mjs out of a template string, with every regular
7
+ expression doubly escaped. That made it the single obstacle shared by
8
+ six separate findings -- the role set, the manifest extractor, the DOM
9
+ role rule, and the three rules that did not exist yet -- because
10
+ touching any rule meant editing JavaScript inside a string.
11
+
12
+ THE DECISION, AND ITS BOUND. Moving it here is NOT a refactor of the
13
+ build: runtime/src/cli.mjs and runtime/src/cli-url.mjs are already
14
+ real source files that the build reads and stamps with placeholders.
15
+ This file joins that pattern, and the invariant is written down and
16
+ enforced:
17
+
18
+ the build emits the SAME SIXTEEN artefacts, with the same names,
19
+ and the EXECUTABLE CONTENT of dist/cli-lint.mjs is byte for byte
20
+ what the literal produced.
21
+
22
+ Verified by diffing the artefact across the move: from the first
23
+ import statement onward the two are identical, 5154 bytes each. The
24
+ only difference is this header, which the literal could not carry.
25
+ Saying "byte for byte" without that qualification would have been
26
+ an overclaim, and this file is about not making those.
27
+ runtime/test/battery-coverage.mjs asserts the artefact set, and
28
+ runtime/test/lint-rules.mjs asserts the behaviour.
29
+
30
+ The CANONICAL_ROLES placeholder below is substituted by the build
31
+ with the roles DERIVED from the normative table in SPEC.md section
32
+ 1. Never type that list here: a hand-typed copy of it is what made
33
+ the lint report [ERROR] against conforming pages for four minor
34
+ versions.
35
+
36
+ Plain regex-based; intentionally tolerant of malformed input.
37
+ ===================================================================== */
3
38
 
4
39
  import fs from 'node:fs';
5
40
  import path from 'node:path';
6
41
 
7
- const CANONICAL_ROLES = new Set([
8
- 'plugin','section','region','action','field','option','tab',
9
- 'breadcrumb-item','accordion-toggle','step','pagination-item',
10
- 'confirm-button','sort-control','filter-control','data-table',
11
- 'navigation','confirm-dialog','button'
12
- ]);
42
+ // The canonical roles, DERIVED from the normative table in SPEC.md
43
+ // section 1 by scripts/spec-levels.mjs -- the same module that gives
44
+ // this build its levels and its locales. Until 2026-11-24 this was a
45
+ // hand-typed set of 18 of the 20, missing draggable and drop-target,
46
+ // so the lint reported manifest_role_unknown on pages that follow the
47
+ // specification exactly. Never type this list again.
48
+ const CANONICAL_ROLES = new Set(["plugin","section","region","action","field","option","tab","breadcrumb-item","accordion-toggle","step","pagination-item","confirm-button","sort-control","filter-control","data-table","navigation","confirm-dialog","draggable","drop-target","button","map","map-layer","map-marker","chart","chart-series","chart-point","calendar","calendar-event","tree","tree-node","tree-children","timeline","timeline-item","carousel","carousel-slide","status","log","toast","toast-region","banner","feedback","modal","drawer","bottom-sheet","combobox","listbox","slider","richtext","tablist","tabpanel","stepper","accordion-section","breadcrumb","pagination-control","avatar","presence-indicator","skeleton","empty-state","list","row","menu","label","value","paragraph","canvas"]);
49
+
50
+ // The declared aliases of SPEC.md section 1.5 (v2.8), DERIVED from
51
+ // that section by the same module. Seven spellings this tree had
52
+ // grown for roles that already had a name. They are legal -- the
53
+ // runtime resolves them -- and they are reported, so a tree gets
54
+ // migrated deliberately instead of all at once. Never type this one
55
+ // either: the whole v2.8 release exists because two hand-typed copies
56
+ // of a role list drifted for four minor versions.
57
+ const ROLE_ALIASES = {"treenode":"tree-node","timeline-entry":"timeline-item","input":"field","textbox":"field","panel":"region","fab":"action","dropzone":"drop-target"};
58
+
59
+ // The locales a conformance level requires, DERIVED from SPEC.md
60
+ // section 4.3 by the same module, and substituted by the build. Rule 7
61
+ // below needs them; the URL-mode half of the validator has read them
62
+ // from levels.locales_required since 2.5.0, and the directory mode had
63
+ // no way to ask. Never type this list either.
64
+ const REQUIRED_LOCALES = ["es","en","pt","fr","ja","zh","hi","ar","de","it"];
65
+
66
+ /* THE EXTENSIONS THIS LINT READS (PND-134, measured 2026-11-26 while
67
+ evaluating an ERP whose interface is 983 ASP.NET Razor views).
68
+
69
+ Until 2026-11-27 this list was the literal ['.html', '.htm', '.php']
70
+ typed into the two call sites of walk(). An adopter whose markup
71
+ lives anywhere else -- .cshtml, .jsx/.tsx (and this repository ships
72
+ a React demo), .vue -- ran `nac validate <dir>`, the walk found no
73
+ files, and the lint printed "Total findings: 0". Not "no files I can
74
+ read": zero findings, the same line a conforming tree prints. That
75
+ is a FALSE GREEN, the most expensive defect shape there is, because
76
+ the adopter stops looking.
77
+
78
+ Two things had to change, and the list is the lesser one. A list of
79
+ extensions is always one framework behind, so the lint now also
80
+ REPORTS how many files it read and REFUSES when it read none
81
+ (no_lintable_files, below) -- so the framework this list does not
82
+ know yet produces a refusal naming what the walk accepts and the
83
+ --ext escape hatch, instead of silence.
84
+
85
+ What is in here, and why: the server-rendered and component template
86
+ extensions that CARRY MARKUP. Not .js or .ts -- JSX inside a plain
87
+ .js file is real, but the same extension holds every build script
88
+ and bundle in a tree, and a validator that reads those reports
89
+ findings about code nobody serves. An adopter whose components live
90
+ in .js says so with --ext=.js, which is one word, and gets told
91
+ about that word by the refusal. */
92
+ export const LINT_EXTENSIONS = [
93
+ '.html', '.htm', '.xhtml', // plain markup
94
+ '.php', // including Blade (.blade.php)
95
+ '.cshtml', '.vbhtml', '.razor', // ASP.NET Razor and Blazor
96
+ '.aspx', '.ascx', '.master', // ASP.NET Web Forms
97
+ '.jsx', '.tsx', // React and anything JSX
98
+ '.vue', '.svelte', '.astro', // single-file components
99
+ '.hbs', '.handlebars', '.mustache', // Handlebars / Mustache
100
+ '.ejs', '.erb', '.twig', '.liquid', // the other server templates
101
+ '.njk', '.jinja', '.jinja2', '.j2',
102
+ '.jsp', '.jspx',
103
+ ];
104
+
105
+ /* --ext ADDS, it never replaces. An adopter who names one extension
106
+ must not silently lose the defaults: that would be a second false
107
+ green wearing the shape of an option. A bare `cshtml` is accepted
108
+ alongside `.cshtml` because that is how it gets typed. */
109
+ function resolveExtensions(extra) {
110
+ const out = LINT_EXTENSIONS.slice();
111
+ for (const raw of (Array.isArray(extra) ? extra : [])) {
112
+ if (typeof raw !== 'string') continue;
113
+ const e = raw.trim().toLowerCase();
114
+ if (!e) continue;
115
+ const dotted = e.startsWith('.') ? e : '.' + e;
116
+ if (out.indexOf(dotted) < 0) out.push(dotted);
117
+ }
118
+ return out;
119
+ }
13
120
 
14
121
  function walk(dir, exts) {
15
122
  const out = [];
@@ -17,7 +124,7 @@ function walk(dir, exts) {
17
124
  const st = fs.statSync(p);
18
125
  if (st.isDirectory()) {
19
126
  for (const e of fs.readdirSync(p)) rec(path.join(p, e));
20
- } else if (exts.some(x => p.endsWith(x))) {
127
+ } else if (exts.some(x => p.toLowerCase().endsWith(x))) {
21
128
  out.push(p);
22
129
  }
23
130
  }
@@ -25,6 +132,17 @@ function walk(dir, exts) {
25
132
  return out;
26
133
  }
27
134
 
135
+ /* The walk, exported: what this lint WOULD read under `dir`. The CLI
136
+ needs it to say how many files it read, and `nac plugins` needs the
137
+ same answer -- the two commands reading two different lists is the
138
+ producer/consumer asymmetry this release spent its length removing.
139
+ Paths come back relative to `dir`, which is how every finding
140
+ attributes a file. */
141
+ export function lintableFiles(dir, extraExtensions) {
142
+ const exts = resolveExtensions(extraExtensions);
143
+ return walk(dir, exts).map((f) => path.relative(dir, f));
144
+ }
145
+
28
146
  function extractDomPairs(content) {
29
147
  // Match every (data-nac-id="X", data-nac-role="Y") pair within an
30
148
  // attribute-soup window. The naive approach: for each id match, look
@@ -53,34 +171,357 @@ function extractDomPairs(content) {
53
171
  }
54
172
 
55
173
  function extractManifestEntries(content) {
56
- // Best-effort: find NAC.register({ ... }) and extract elements[].id
57
- // + role. Tolerant of multi-line.
174
+ // Every NAC.register call in the file, in BOTH documented shapes,
175
+ // with the argument list delimited by brace matching rather than by
176
+ // a lazy regex.
177
+ //
178
+ // What this replaced, and why it mattered (TF-B02). The old pattern
179
+ // was /NAC\.register\s*\(\s*\{[\s\S]*?\}\s*\)/g, and it was wrong
180
+ // twice:
181
+ //
182
+ // 1. it required `(` to be followed by `{`, so
183
+ // NAC.register(slug, manifest) -- the two-argument form that
184
+ // runtime/build.mjs itself declares supported -- produced NO
185
+ // MATCH AT ALL. Not a wrong finding: zero findings. All four
186
+ // manifest rules inherited that blindness, so the lint
187
+ // APPROVED what it never looked at, which is the worst way for
188
+ // a validator to be wrong.
189
+ // 2. `[\s\S]*?\}\s*\)` stops at the FIRST `}` followed by `)`, so
190
+ // a manifest with a nested object closing that way was cut
191
+ // short and its remaining elements were never seen.
192
+ //
193
+ // Brace matching fixes both. Strings are tracked so a `}` or a `)`
194
+ // inside a quoted label -- a label_i18n value can contain anything
195
+ // -- does not end the argument list early.
58
196
  const out = [];
59
- const rx = /NAC\.register\s*\(\s*\{[\s\S]*?\}\s*\)/g;
60
- let m;
61
- while ((m = rx.exec(content)) !== null) {
62
- const block = m[0];
197
+ const callRx = /NAC\.register\s*\(/g;
198
+ let call;
199
+ while ((call = callRx.exec(content)) !== null) {
200
+ const open = call.index + call[0].length - 1; // the '(' itself
201
+ const close = matchClose(content, open, '(', ')');
202
+ if (close < 0) continue; // unbalanced: skip, do not guess
203
+ const args = content.slice(open + 1, close);
204
+
205
+ // The manifest is the LAST object literal in the argument list:
206
+ // register({...}) has one, register('slug', {...}) has the slug
207
+ // first. Taking the last one covers both without having to parse
208
+ // the argument list.
209
+ const braceStart = findLastTopLevelBrace(args);
210
+ if (braceStart < 0) continue;
211
+ const braceEnd = matchClose(args, braceStart, '{', '}');
212
+ if (braceEnd < 0) continue;
213
+ const block = args.slice(braceStart, braceEnd + 1);
214
+
215
+ // The slug can come from plugin_slug inside the manifest or from
216
+ // the first argument of the two-argument form. The manifest wins
217
+ // when both are present, because that is what the runtime reads.
218
+ let plugin = '<unknown>';
219
+ const leading = args.slice(0, braceStart);
220
+ const argSlug = /^\s*['"]([^'"]+)['"]\s*,/.exec(leading);
221
+ if (argSlug) plugin = argSlug[1];
63
222
  const slugM = /plugin_slug\s*:\s*['"]([^'"]+)['"]/.exec(block);
64
- const plugin = slugM ? slugM[1] : '<unknown>';
65
- // Each element entry: { id: 'X', role: 'Y', ... }
66
- const elRx = /\{[^{}]*?id\s*:\s*['"]([^'"]+)['"][^{}]*?role\s*:\s*['"]([^'"]+)['"][^{}]*?\}/g;
67
- let em;
68
- while ((em = elRx.exec(block)) !== null) {
69
- out.push({ plugin, id: em[1], role: em[2] });
223
+ if (slugM) plugin = slugM[1];
224
+
225
+ for (const e of elementsOf(block)) {
226
+ out.push({ plugin, id: e.id, role: e.role, labels: e.labels });
227
+ }
228
+ }
229
+ return out;
230
+ }
231
+
232
+ // Walk from an opening delimiter to its match, skipping over quoted
233
+ // strings, template literals and line/block comments.
234
+ function matchClose(src, from, openCh, closeCh) {
235
+ let depth = 0;
236
+ let i = from;
237
+ while (i < src.length) {
238
+ const c = src[i];
239
+ if (c === '"' || c === "'" || c === '`') {
240
+ const q = c;
241
+ i += 1;
242
+ while (i < src.length) {
243
+ if (src[i] === '\\') { i += 2; continue; }
244
+ if (src[i] === q) break;
245
+ i += 1;
246
+ }
247
+ i += 1;
248
+ continue;
249
+ }
250
+ if (c === '/' && src[i + 1] === '/') {
251
+ const nl = src.indexOf('\n', i);
252
+ i = nl < 0 ? src.length : nl + 1;
253
+ continue;
254
+ }
255
+ if (c === '/' && src[i + 1] === '*') {
256
+ const end = src.indexOf('*/', i + 2);
257
+ i = end < 0 ? src.length : end + 2;
258
+ continue;
259
+ }
260
+ if (c === openCh) depth += 1;
261
+ else if (c === closeCh) {
262
+ depth -= 1;
263
+ if (depth === 0) return i;
264
+ }
265
+ i += 1;
266
+ }
267
+ return -1;
268
+ }
269
+
270
+ // The last `{` in the argument list that is not inside another brace,
271
+ // bracket, paren or string: the manifest object of either call shape.
272
+ function findLastTopLevelBrace(args) {
273
+ let depth = 0;
274
+ let last = -1;
275
+ let i = 0;
276
+ while (i < args.length) {
277
+ const c = args[i];
278
+ if (c === '"' || c === "'" || c === '`') {
279
+ const q = c;
280
+ i += 1;
281
+ while (i < args.length) {
282
+ if (args[i] === '\\') { i += 2; continue; }
283
+ if (args[i] === q) break;
284
+ i += 1;
285
+ }
286
+ i += 1;
287
+ continue;
288
+ }
289
+ if (c === '{' || c === '[' || c === '(') {
290
+ if (c === '{' && depth === 0) last = i;
291
+ depth += 1;
292
+ } else if (c === '}' || c === ']' || c === ')') {
293
+ depth -= 1;
294
+ }
295
+ i += 1;
296
+ }
297
+ return last;
298
+ }
299
+
300
+ // Each entry of elements[], with its id, its role and the locales each
301
+ // of its label_i18n blocks declares. Brace-matched one element at a
302
+ // time so a nested actions[] or label_i18n does not truncate it -- the
303
+ // old /\{[^{}]*?id.*?role.*?\}/ pattern could not see past one level,
304
+ // which is the same defect as the call pattern one scale down.
305
+ function elementsOf(block) {
306
+ const arrStart = block.search(/elements\s*:\s*\[/);
307
+ if (arrStart < 0) return [];
308
+ const bracket = block.indexOf('[', arrStart);
309
+ const arrEnd = matchClose(block, bracket, '[', ']');
310
+ if (arrEnd < 0) return [];
311
+ const body = block.slice(bracket + 1, arrEnd);
312
+
313
+ const out = [];
314
+ let i = 0;
315
+ while (i < body.length) {
316
+ if (body[i] !== '{') { i += 1; continue; }
317
+ const end = matchClose(body, i, '{', '}');
318
+ if (end < 0) break;
319
+ const entry = body.slice(i, end + 1);
320
+ const idM = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(entry);
321
+ const roleM = /\brole\s*:\s*['"]([^'"]+)['"]/.exec(entry);
322
+ if (idM && roleM) {
323
+ const labels = [];
324
+ let j = 0;
325
+ while (j < entry.length) {
326
+ const at = entry.indexOf('label_i18n', j);
327
+ if (at < 0) break;
328
+ const ob = entry.indexOf('{', at);
329
+ if (ob < 0) break;
330
+ const oe = matchClose(entry, ob, '{', '}');
331
+ if (oe < 0) break;
332
+ const inner = entry.slice(ob + 1, oe);
333
+ labels.push([...inner.matchAll(/(?:^|[,{\s])([a-z]{2})\s*:/g)].map((m) => m[1]));
334
+ j = oe + 1;
335
+ }
336
+ out.push({ id: idM[1], role: roleM[1], labels });
337
+ }
338
+ i = end + 1;
339
+ }
340
+ return out;
341
+ }
342
+
343
+ /* The manifest inventory of a tree: every element every NAC.register
344
+ call declares, with the file it came from.
345
+
346
+ Exported for `nac plugins <dir>` (TF-B09). The CLI had one
347
+ subcommand, so a protocol whose argument is that a UI becomes
348
+ DISCOVERABLE had no way to ask a tree what it declares -- while the
349
+ extraction it needed was already here, feeding the four manifest
350
+ rules. This adds the walk and the file attribution, nothing else:
351
+ same extractor, so `plugins` and `validate` can never disagree
352
+ about what a file declares. */
353
+ export function manifestInventory(dir, opts) {
354
+ const out = [];
355
+ /* The SAME extension list the lint walks with (PND-134). Two call
356
+ sites with the same literal is how `plugins` and `validate` would
357
+ come to disagree about what a tree contains. */
358
+ for (const file of walk(dir, resolveExtensions(opts && opts.extensions))) {
359
+ let content;
360
+ try { content = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
361
+ const rel = path.relative(dir, file);
362
+ for (const e of extractManifestEntries(content)) {
363
+ out.push({ plugin: e.plugin, id: e.id, role: e.role, file: rel });
70
364
  }
71
365
  }
72
366
  return out;
73
367
  }
74
368
 
75
- export function staticLint(dir) {
369
+ /* The whole answer of a directory run: the files that were READ, the
370
+ extensions the walk accepted, and the findings. staticLint() keeps
371
+ returning the findings alone, because that is what every caller
372
+ since 2.0 expects; this is the shape the CLI needs so it can print
373
+ the file count instead of only a finding count (PND-134). The count
374
+ comes from the same walk that produced the findings -- not from a
375
+ second one that could disagree with it. */
376
+ export function lintTree(dir, opts) {
377
+ const extensions = resolveExtensions(opts && opts.extensions);
378
+ const files = walk(dir, extensions);
379
+ return {
380
+ dir,
381
+ extensions,
382
+ files: files.map((f) => path.relative(dir, f)),
383
+ findings: lintFiles(dir, files, extensions),
384
+ };
385
+ }
386
+
387
+ export function staticLint(dir, opts) {
388
+ const extensions = resolveExtensions(opts && opts.extensions);
389
+ return lintFiles(dir, walk(dir, extensions), extensions);
390
+ }
391
+
392
+ function lintFiles(dir, files, extensions) {
76
393
  const findings = [];
77
- const files = walk(dir, ['.html', '.htm', '.php']);
394
+
395
+ /* THE REFUSAL (PND-134). Zero files read is not zero findings: it
396
+ is the lint saying nothing about a tree it could not open, and
397
+ until 2026-11-27 the two printed the same line. `error`, so the
398
+ exit code fails with it -- a false green that exits 0 is what
399
+ lets an adopter wire this into a pipeline and believe it. */
400
+ if (files.length === 0) {
401
+ findings.push({
402
+ severity: 'error',
403
+ code: 'no_lintable_files',
404
+ file: null,
405
+ message: 'read 0 files under this directory, so this reports nothing about it -- '
406
+ + 'which is NOT the same as a conforming tree. The extensions this lint '
407
+ + 'reads are: ' + extensions.join(' ') + '. If the markup of this tree '
408
+ + 'lives in another extension, name it: nac validate <dir> --ext=.foo,.bar'
409
+ });
410
+ }
411
+
412
+ /* THE PAGE-SCOPED ROLE REGISTRY of SPEC.md 1.4, read PER FILE
413
+ (2026-11-27, PND-132).
414
+
415
+ Until today this read exactly one path -- nac3.roles.json at the
416
+ lint ROOT -- and section 1.4 says the declaration goes "next to
417
+ the markup". The two agree while an adopter lints the directory
418
+ the page lives in, and disagree the moment anyone lints a PARENT
419
+ of it: every register_role call in the tree became
420
+ role_registration_undeclared, at `error`, over a registry that
421
+ was sitting right beside the page. Found by writing the demo that
422
+ exercises register_role end to end: `nac validate demos` -- which
423
+ runtime/test/smoke.mjs runs -- would have reported the demo as
424
+ wrong for doing what section 1.4 asks.
425
+
426
+ So a file's effective registry is every nac3.roles.json on the
427
+ path from the lint root down to that file's own directory, the
428
+ nearest one winning on a conflict. A root registry still applies
429
+ to everything under it, which is the behaviour the old code had
430
+ for the one case it handled.
431
+
432
+ A MISSING registry is the normal case and not a finding: almost
433
+ no page registers a role. A registry that is present and
434
+ unparseable IS one, because the alternative is silently linting
435
+ against an empty registry and reporting every registered role as
436
+ unknown -- the failure mode this release spent its length
437
+ removing. */
438
+ const registries = new Map(); /* dir (relative, '' = root) -> Map(role -> spec) */
439
+ const registryUsed = new Map(); /* same key -> Set(role actually registered below) */
440
+
441
+ function loadRegistry(absDir) {
442
+ const key = path.relative(dir, absDir).split(path.sep).join('/');
443
+ if (registries.has(key)) return key;
444
+ const file = path.join(absDir, 'nac3.roles.json');
445
+ if (!fs.existsSync(file)) { registries.set(key, null); return key; }
446
+ const relFile = (key ? key + '/' : '') + 'nac3.roles.json';
447
+ const map = new Map();
448
+ try {
449
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
450
+ const list = Array.isArray(parsed && parsed.roles) ? parsed.roles : [];
451
+ for (const r of list) {
452
+ if (r && typeof r.role === 'string') map.set(r.role, r);
453
+ }
454
+ if (!list.length) {
455
+ findings.push({
456
+ severity: 'warn',
457
+ code: 'role_registry_empty',
458
+ file: relFile,
459
+ message: relFile + ' is present and declares no roles. If this directory ' +
460
+ 'registers none, delete the file; an empty registry and a missing one ' +
461
+ 'mean the same thing to this lint and only one of them says so.'
462
+ });
463
+ }
464
+ } catch (e) {
465
+ findings.push({
466
+ severity: 'error',
467
+ code: 'role_registry_unreadable',
468
+ file: relFile,
469
+ message: relFile + ' could not be parsed (' + (e && e.message) + '). Linting ' +
470
+ 'against an empty registry would report every registered role as unknown, ' +
471
+ 'so this refuses instead (SPEC.md 1.4).'
472
+ });
473
+ }
474
+ registries.set(key, map);
475
+ registryUsed.set(key, new Set());
476
+ return key;
477
+ }
478
+
479
+ /* Every directory from the lint root down to `absDir`, nearest last,
480
+ so a registry closer to the file overrides one above it. */
481
+ function registryChain(absDir) {
482
+ const steps = [];
483
+ let cur = absDir;
484
+ for (;;) {
485
+ steps.unshift(cur);
486
+ const rel = path.relative(dir, cur);
487
+ if (!rel || rel === '.' || rel.startsWith('..')) break;
488
+ const up = path.dirname(cur);
489
+ if (up === cur) break;
490
+ cur = up;
491
+ }
492
+ return steps.map((d) => loadRegistry(d));
493
+ }
494
+
495
+ function rolesFor(absDir) {
496
+ const out = new Map();
497
+ for (const key of registryChain(absDir)) {
498
+ const m = registries.get(key);
499
+ if (!m) continue;
500
+ for (const [role, spec] of m) out.set(role, spec);
501
+ }
502
+ return out;
503
+ }
504
+
505
+ /* Which registry a register_role call counts as using: the nearest
506
+ one on the chain that declares it. */
507
+ function markUsed(absDir, role) {
508
+ const chain = registryChain(absDir);
509
+ for (let i = chain.length - 1; i >= 0; i--) {
510
+ const m = registries.get(chain[i]);
511
+ if (m && m.has(role)) { registryUsed.get(chain[i]).add(role); return true; }
512
+ }
513
+ return false;
514
+ }
515
+
78
516
  for (const file of files) {
79
517
  let content;
80
518
  try { content = fs.readFileSync(file, 'utf8'); }
81
519
  catch (_) { continue; }
82
520
  const rel = path.relative(dir, file);
83
521
 
522
+ /* PND-132: the registry that applies to THIS file. */
523
+ const registeredRoles = rolesFor(path.dirname(file));
524
+
84
525
  const domPairs = extractDomPairs(content);
85
526
  const manifestEntries = extractManifestEntries(content);
86
527
 
@@ -99,7 +540,18 @@ export function staticLint(dir) {
99
540
 
100
541
  // Rule 2: manifest_role_unknown -- manifest element role outside canonical set.
101
542
  for (const e of manifestEntries) {
102
- if (!CANONICAL_ROLES.has(e.role)) {
543
+ /* v2.8.0: same split as rule 5, on the manifest side. The
544
+ manifest is the one place where a spelling can be fixed
545
+ without touching markup, so it is worth naming separately. */
546
+ if (Object.prototype.hasOwnProperty.call(ROLE_ALIASES, e.role)) {
547
+ findings.push({
548
+ severity: 'warn',
549
+ code: 'manifest_role_legacy_spelling',
550
+ file: rel,
551
+ message: 'plugin "' + e.plugin + '" id="' + e.id + '" declares role="' + e.role +
552
+ '"; the canonical role is "' + ROLE_ALIASES[e.role] + '" (SPEC.md 1.5)'
553
+ });
554
+ } else if (!CANONICAL_ROLES.has(e.role) && !registeredRoles.has(e.role)) {
103
555
  findings.push({
104
556
  severity: 'error',
105
557
  code: 'manifest_role_unknown',
@@ -137,6 +589,248 @@ export function staticLint(dir) {
137
589
  });
138
590
  }
139
591
  }
592
+
593
+ /* ---------------------------------------------------------------
594
+ THE FOUR RULES ADDED 2026-11-24, AND THE SEVERITY EACH CHOSE.
595
+
596
+ Severity is not decoration here. runtime/test/smoke.mjs asserts
597
+ that `nac validate <demos>` reports no [ERROR], so a new rule at
598
+ `error` that fires over the repository's own demo pages would
599
+ break the battery -- and a rule that has to be switched off is
600
+ worse than no rule. Each severity below was picked after
601
+ MEASURING what the rule reports over demos/, and the number is
602
+ recorded with it.
603
+ --------------------------------------------------------------- */
604
+
605
+ /* Rule 5: dom_role_unknown -- a role written in the MARKUP that
606
+ the specification does not declare. severity: warn
607
+
608
+ The gap this closes: rules 2 and 4 iterate manifestEntries, so a
609
+ role that only ever appears as a data-nac-role attribute was
610
+ never compared against anything. Measured 2026-11-24, roles
611
+ invented straight in the markup -- map-marker,
612
+ totalmente-inventado-no-existe -- produced ZERO findings.
613
+
614
+ warn, and deliberately: measured 9 non-canonical DOM roles in
615
+ demos/ (status, input, menu, panel, canvas, list, log) and about
616
+ 14,460 in the published tree, almost all of them code-inline
617
+ from one generator. SPEC.md section 1 says roles outside the
618
+ table are "reserved for future use" and that a NAC-permissive
619
+ runtime MAY treat an unknown role as action -- so this is a real
620
+ finding about vocabulary, not a broken contract. At `error` it
621
+ would turn every existing page red and would force a decision
622
+ about those 14,460 that belongs to the owner, not to a lint. */
623
+ for (const p of domPairs) {
624
+ if (!p.role) continue;
625
+ /* v2.8.0: a declared alias (SPEC.md 1.5) is NOT unknown. Before
626
+ this branch the seven legacy spellings of this tree were
627
+ reported as vocabulary the spec does not declare, which was
628
+ true of the spelling and false of the concept -- and it gave
629
+ the reader no way to tell "this word does not exist" from
630
+ "this word has a canonical form". They are now separate
631
+ codes, and the fix is in the message. */
632
+ if (Object.prototype.hasOwnProperty.call(ROLE_ALIASES, p.role)) {
633
+ findings.push({
634
+ severity: 'warn',
635
+ code: 'dom_role_legacy_spelling',
636
+ file: rel,
637
+ message: 'data-nac-id="' + p.id + '" carries data-nac-role="' + p.role +
638
+ '"; the canonical role is "' + ROLE_ALIASES[p.role] +
639
+ '" (SPEC.md 1.5). The alias resolves at runtime, so nothing is broken ' +
640
+ 'today; migrating the spelling is what keeps one concept to one word.'
641
+ });
642
+ continue;
643
+ }
644
+ if (!CANONICAL_ROLES.has(p.role) && !registeredRoles.has(p.role)) {
645
+ findings.push({
646
+ severity: 'warn',
647
+ code: 'dom_role_unknown',
648
+ file: rel,
649
+ message: 'data-nac-id="' + p.id + '" carries data-nac-role="' + p.role +
650
+ '", which SPEC.md section 1 does not declare'
651
+ });
652
+ }
653
+ }
654
+
655
+ /* Rule 5b: the static half of NAC.register_role (SPEC.md 1.4).
656
+ role_registration_undeclared severity: error
657
+ role_registration_orphan severity: warn
658
+
659
+ THE PROBLEM. A role registered with NAC.register_role() exists
660
+ only while the page is loaded. This lint runs with no page: it
661
+ reads files. So a page that declares its own vocabulary in
662
+ JavaScript is invisible here, and rule 5 would report it as
663
+ wrong for using a role the page itself declares.
664
+
665
+ Making the lint EXECUTE the page it is validating was never an
666
+ option -- a validator that runs its subject has stopped being
667
+ one. So section 1.4 asks for a second declaration this can
668
+ read, a nac3.roles.json next to the markup, and these two codes
669
+ are what stops two declarations of one fact from drifting,
670
+ which is the asymmetry this whole release exists to remove.
671
+
672
+ error on undeclared, and that asymmetry is deliberate: a role
673
+ the lint cannot see makes every OTHER finding about that
674
+ element unreliable, while a declaration nobody uses yet is
675
+ merely untidy. */
676
+ for (const m of content.matchAll(/\bregister_role\s*\(\s*['"]([a-z][a-z0-9-]*)['"]/g)) {
677
+ if (!markUsed(path.dirname(file), m[1])) {
678
+ findings.push({
679
+ severity: 'error',
680
+ code: 'role_registration_undeclared',
681
+ file: rel,
682
+ message: 'this file calls NAC.register_role("' + m[1] + '") and no nac3.roles.json ' +
683
+ 'beside it -- or in any directory between it and the linted root -- declares ' +
684
+ 'it. A static validator cannot see a role declared in JavaScript, so every ' +
685
+ 'finding about an element carrying that role would be unreliable (SPEC.md 1.4).'
686
+ });
687
+ }
688
+ }
689
+
690
+ /* Rule 6: opens_dangling -- data-nac-opens pointing at an id this
691
+ page does not contain. severity: error
692
+
693
+ Why error: measured 0 occurrences in demos/ (5 data-nac-opens,
694
+ all resolving), so it cannot break the battery -- and the defect
695
+ is concrete rather than stylistic. NAC.tree() reports the target
696
+ of data-nac-opens to the agent as if it were reachable, so a
697
+ dangling pointer makes the runtime LIE to the agent, which then
698
+ acts on something that was never there. validate_global() does
699
+ not look at this attribute either: its five buckets are other
700
+ things. Nothing in the project saw it. */
701
+ const paintedIds = new Set(domPairs.map((p) => p.id));
702
+ for (const m of content.matchAll(/data-nac-opens="([^"]+)"/g)) {
703
+ const target = m[1].trim();
704
+ if (!target) continue;
705
+ if (!paintedIds.has(target)) {
706
+ findings.push({
707
+ severity: 'error',
708
+ code: 'opens_dangling',
709
+ file: rel,
710
+ message: 'data-nac-opens="' + target + '" names an id this page does not declare' +
711
+ ' (NAC.tree() reports it to the agent as a valid destination)'
712
+ });
713
+ }
714
+ }
715
+
716
+ /* Rule 7: label_i18n_incomplete -- a label that does not cover the
717
+ locales the conformance levels require. severity: warn
718
+
719
+ The asymmetry this closes: the rule existed only on the side
720
+ that needs a browser. runtime/src/cli-url.mjs implements
721
+ label_i18n_covers_locales against levels.locales_required, and
722
+ the directory mode had four rules, all of them about roles. The
723
+ data was never the obstacle -- the build already derives the
724
+ required locales from SPEC.md section 4.3 and substitutes them
725
+ below, the same way it substitutes the canonical roles.
726
+
727
+ warn, because label coverage is what a conformance LEVEL
728
+ requires (SPEC.md section 8), not what level 1 requires. A page
729
+ that targets level 1 is not wrong for having one locale, and a
730
+ lint that calls it wrong is a lint that gets switched off.
731
+ Measured: 0 label_i18n blocks in demos/, so the severity is not
732
+ what keeps the battery green here -- the argument is. */
733
+ for (const e of manifestEntries) {
734
+ const labels = e.labels || [];
735
+ labels.forEach((locales, n) => {
736
+ const missing = REQUIRED_LOCALES.filter((loc) => locales.indexOf(loc) < 0);
737
+ if (!missing.length) return;
738
+ /* An element can carry more than one label_i18n -- its own,
739
+ plus one per entry of actions[] -- and they are genuinely
740
+ separate findings. Numbering them is what makes two lines
741
+ about the same id readable instead of looking like the same
742
+ finding printed twice. */
743
+ const which = labels.length > 1 ? ' (label ' + (n + 1) + ' of ' + labels.length + ')' : '';
744
+ findings.push({
745
+ severity: 'warn',
746
+ code: 'label_i18n_incomplete',
747
+ file: rel,
748
+ message: 'plugin "' + e.plugin + '" id="' + e.id + '"' + which +
749
+ ' has a label_i18n missing ' + missing.length + ' of the ' +
750
+ REQUIRED_LOCALES.length + ' required locales: ' + missing.join(',')
751
+ });
752
+ });
753
+ }
754
+
755
+ /* Rule 8: drag_type_unsatisfiable -- a draggable whose type no
756
+ drop target on the page accepts. severity: warn
757
+
758
+ The runtime half has been complete since 1.8.0:
759
+ _dragTypesCompatible (js/nac.js:1271) decides it and drag_drop
760
+ consults it, rejecting with reason 'drag_type_mismatch'. What
761
+ was missing is the static half, so a page could declare a drag
762
+ that can never have a destination and nothing would say so until
763
+ an agent tried it.
764
+
765
+ THE THREE SHORTCUTS OF THAT FUNCTION DEFINE WHAT NOT TO REPORT,
766
+ and getting them wrong is how this rule would cry wolf on
767
+ correct pages:
768
+ - an untyped source is compatible with everything, so a
769
+ draggable with no data-nac-drag-type is never a finding;
770
+ - a target whose data-nac-drag-accept is absent or empty, or
771
+ is '*', accepts everything -- so ONE such target on the page
772
+ satisfies every type;
773
+ - '*' inside the comma-separated list does the same.
774
+ Matching is case-insensitive and trimmed, as it is there.
775
+
776
+ warn, not error: a drop target can be rendered after load, so a
777
+ static read cannot prove the destination will never exist. The
778
+ finding is worth raising and not worth failing a build over.
779
+ Measured: 0 drag attributes in demos/. */
780
+ const dragTypes = [...content.matchAll(/data-nac-drag-type="([^"]*)"/g)]
781
+ .map((m) => m[1].trim().toLowerCase()).filter(Boolean);
782
+ if (dragTypes.length) {
783
+ const acceptAttrs = [...content.matchAll(/data-nac-drag-accept="([^"]*)"/g)]
784
+ .map((m) => m[1].trim().toLowerCase());
785
+ /* A drop target with no accept attribute at all accepts
786
+ everything, and it will not appear in acceptAttrs -- so look
787
+ for one directly rather than inferring it from absence. */
788
+ const openTarget = [...content.matchAll(/<[^>]*data-nac-role="drop-target"[^>]*>/g)]
789
+ .some((t) => !/data-nac-drag-accept\s*=/.test(t[0]));
790
+ const wildcard = acceptAttrs.some((a) => a === '' || a === '*'
791
+ || a.split(',').map((x) => x.trim()).indexOf('*') >= 0);
792
+ if (!openTarget && !wildcard) {
793
+ const accepted = new Set();
794
+ for (const a of acceptAttrs) {
795
+ for (const x of a.split(',')) if (x.trim()) accepted.add(x.trim());
796
+ }
797
+ for (const t of [...new Set(dragTypes)]) {
798
+ if (!accepted.has(t)) {
799
+ findings.push({
800
+ severity: 'warn',
801
+ code: 'drag_type_unsatisfiable',
802
+ file: rel,
803
+ message: 'data-nac-drag-type="' + t + '" has no drop target on this page that accepts it' +
804
+ (accepted.size ? ' (targets accept: ' + [...accepted].sort().join(',') + ')'
805
+ : ' (no drop target declares data-nac-drag-accept)')
806
+ });
807
+ }
808
+ }
809
+ }
810
+ }
140
811
  }
812
+ /* The other direction, now per registry (PND-132): a role declared
813
+ for the lint that no page under that registry's directory
814
+ registers. warn, not error -- an unused declaration misleads a
815
+ reader of nac3.roles.json and breaks nothing. */
816
+ for (const [key, map] of registries) {
817
+ if (!map) continue;
818
+ const used = registryUsed.get(key) || new Set();
819
+ const relFile = (key ? key + '/' : '') + 'nac3.roles.json';
820
+ for (const role of map.keys()) {
821
+ if (used.has(role)) continue;
822
+ findings.push({
823
+ severity: 'warn',
824
+ code: 'role_registration_orphan',
825
+ file: relFile,
826
+ message: relFile + ' declares role "' + role + '" and no file under that ' +
827
+ 'directory calls NAC.register_role("' + role + '"). A declaration ' +
828
+ 'nobody uses is a reader believing a role exists on a page where it ' +
829
+ 'does not (SPEC.md 1.4).'
830
+ });
831
+ }
832
+ }
833
+
141
834
  return findings;
142
835
  }
836
+