001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.console.freemarker;
018
019import static java.nio.charset.StandardCharsets.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021
022import java.io.*;
023import java.nio.file.*;
024import java.util.*;
025import java.util.function.UnaryOperator;
026import java.util.regex.*;
027import java.util.stream.*;
028
029import org.apache.juneau.commons.collections.Maps;
030import org.apache.juneau.rest.server.staticfile.WebJarResolver;
031import org.apache.juneau.console.views.*;
032
033import freemarker.core.*;
034import freemarker.template.*;
035
036/**
037 * Static lint for console FreeMarker templates. Scans each template for console directive calls and reports unknown
038 * directives, unknown attributes, dangling template references, duplicate nav and card ids, non-strict booleans,
039 * removed card types and globals, a chart card whose ECharts WebJar is missing (E-70), and a wrong {@code <@main/>} count, without rendering any page.
040 *
041 * <p>
042 * The attribute sets are the same ones the directives enforce at render time. Interpolated values
043 * ({@code visible="${x}"}) and unquoted expressions ({@code visible=flag}) are skipped; the render-time errors cover
044 * them. Macros defined in the template, in literally {@code <#include>}d templates and in the
045 * {@link #chromeTemplate(String) chrome template} are in scope, as are {@code <@ns.x>} calls on an
046 * {@code <#import … as ns>} namespace.
047 *
048 * <h2 class='section'>Example:</h2>
049 * <p class='bjava'>
050 *    <ja>@Test</ja> <jk>void</jk> templatesLint() {
051 *       List&lt;ConsoleTemplateValidator.Finding&gt; <jv>f</jv> = ConsoleTemplateValidator.<jsm>create</jsm>()
052 *          .templateRoot(Paths.<jsm>get</jsm>(<js>"src/main/resources/templates"</js>))
053 *          .chromeTemplate(<js>"base.ftlh"</js>)
054 *          .allowDirective(<js>"pageHero"</js>)
055 *          .validateAll();
056 *       <jsm>assertTrue</jsm>(<jv>f</jv>.isEmpty(), <jv>f</jv>::toString);
057 *    }
058 * </p>
059 *
060 * @since 10.0.0
061 */
062@SuppressWarnings({
063   "java:S1075", // "/" is the template-name separator, not a file-system path.
064   "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity.
065})
066public final class ConsoleTemplateValidator {
067
068   /**
069    * One lint finding.
070    *
071    * @param template The template name, relative to the root, with {@code /} separators.
072    * @param line The 1-based line.
073    * @param column The 1-based column.
074    * @param rule The rule id, for example {@code unknown-attribute}.
075    * @param message The human-readable message.
076    */
077   public record Finding(String template, int line, int column, String rule, String message) {
078      @Override
079      public String toString() {
080         return template + ":" + line + ":" + column + ": [" + rule + "] " + message;
081      }
082   }
083
084   @SuppressWarnings({
085      "java:S5843", // Tag grammar needs this complexity; it is one regex by design.
086      "java:S5998", // Lint runs on authored templates at build time, never untrusted input.
087      "java:S8786" // Same: the lazy attribute scan is linear on well-formed tags.
088   })
089   private static final Pattern TAG = Pattern.compile("<(/?)@([A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)?)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*?)(/?)>");
090   private static final Pattern ATTR = Pattern.compile("([A-Za-z_]\\w*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'/>]+))");
091   private static final Pattern PAGE_ASSET = Pattern.compile("\\b(init|css)\\s*=\\s*(?:\\[([^\\]]*)\\]|\"([^\"]*)\"|'([^']*)')");
092   private static final Pattern QUOTED = Pattern.compile("\"([^\"]*)\"|'([^']*)'");
093   private static final Pattern MACRO = Pattern.compile("<#macro\\s+([A-Za-z_]\\w*)");
094   private static final Pattern INCLUDE = Pattern.compile("<#include\\s+\"([^\"]+)\"");
095   private static final Pattern IMPORT = Pattern.compile("<#import\\s+\"[^\"]+\"\\s+as\\s+([A-Za-z_]\\w*)");
096   private static final Pattern COMMENT = Pattern.compile("(?s)<#--.*?-->");
097   private static final Pattern GLOBAL = Pattern.compile("\\b(pageBody|pageTab|pageInit|pageCss|pageToolkitCss|pageToolkitJs|pageToolkit|pageThemeCss)\\b");
098   private static final Pattern VIEW_KEY = Pattern.compile("\\bview\\s*:\\s*\\{");
099   private static final Pattern VIEW_VERSION = Pattern.compile("^\\s*[\"']?contractVersion[\"']?\\s*:\\s*[\"']([^\"']*)[\"']");
100   private static final Pattern ASSET_REF = Pattern.compile("\\b(?:src|href)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')");
101   private static final Pattern JUNEAU_ASSET = Pattern.compile("(?:^|/)(?:juneau-[\\w-]+\\.(?:js|css|svg)|juneau-console/chrome\\.css)(?:[?#].*)?$");
102   private static final Set<String> REMOVED_TYPES = Set.of("js", "json", "calendar");
103   private static final Map<String,Set<String>> STRICT = Map.of(NodeDirectiveModel.NAME, Set.of("visible", "selected"), ConsoleDirectiveModel.NAME, Set.of("chrome", "schemeToggle", "themeSelector"));
104   private static final Map<String,Set<String>> DIRECTIVES = directives();
105
106   private static Map<String,Set<String>> directives() {
107      Maps<String,Set<String>> m = mb();
108      m.add(PageDirectiveModel.NAME, PageDirectiveModel.ATTRS);
109      m.add(ConsoleDirectiveModel.NAME, ConsoleDirectiveModel.ATTRS);
110      m.add(MainDirectiveModel.NAME, MainDirectiveModel.ATTRS);
111      m.add(NavigationDirectiveModel.NAME, NavigationDirectiveModel.ATTRS);
112      m.add(NodeDirectiveModel.NAME, NodeDirectiveModel.ATTRS);
113      m.add(ThemeDirectiveModel.NAME, ThemeDirectiveModel.ATTRS);
114      m.add(TokenDirectiveModel.NAME, TokenDirectiveModel.ATTRS);
115      m.add(CardDirectiveModel.NAME, CardDirectiveModel.ATTRS);
116      m.add(TopicDirectiveModel.NAME, TopicDirectiveModel.ATTRS);
117      m.add(BridgeDirectiveModel.NAME, BridgeDirectiveModel.ATTRS);
118      m.add(BadgeDirectiveModel.NAME, BadgeDirectiveModel.ATTRS);
119      m.add(FactsDirectiveModel.NAME, Set.of());
120      for (var s : ConsoleSlotDirectiveModel.SLOT_NAMES)
121         m.add(s, new ConsoleSlotDirectiveModel(s).attrs());
122      return u(m.build());
123   }
124
125   private static final Configuration PARSE_CFG = parseConfig();
126
127   private static Configuration parseConfig() {
128      var c = new Configuration(Configuration.VERSION_2_3_34);
129      c.setRecognizeStandardFileExtensions(true);
130      return c;
131   }
132
133   private Path templateRoot;
134   private String classpathRoot;
135   private String chromeTemplate;
136   private final Set<String> allowed = new TreeSet<>();
137   private UnaryOperator<String> webJarProbe = WebJarResolver::resolvePath;
138   private final ToolkitPackRegistry packs = new ToolkitPackRegistry();
139   private String echartsProblem;         // cached E-70 (or invalid-pack-graph) message; null when the probe passed
140   private String echartsRule;            // the rule id the cached problem is reported under
141   private boolean echartsProbed;
142
143   private ConsoleTemplateValidator() {}
144
145   /** @return A new validator with no roots. */
146   public static ConsoleTemplateValidator create() {
147      return new ConsoleTemplateValidator();
148   }
149
150   /**
151    * @param dir The file-system directory templates are resolved against and {@link #validateAll()} walks.
152    * @return This object.
153    */
154   public ConsoleTemplateValidator templateRoot(Path dir) {
155      templateRoot = dir;
156      return this;
157   }
158
159   /**
160    * @param prefix The classpath prefix templates are resolved against when not found under the template root, for
161    *    example {@code "/templates/"}.
162    * @return This object.
163    */
164   public ConsoleTemplateValidator classpathRoot(String prefix) {
165      classpathRoot = prefix.endsWith("/") ? prefix : prefix + "/";
166      return this;
167   }
168
169   /**
170    * @param name The chrome template the {@code <@page>} directive renders. Its macros are in scope for every template.
171    * @return This object.
172    */
173   public ConsoleTemplateValidator chromeTemplate(String name) {
174      chromeTemplate = name;
175      return this;
176   }
177
178   /**
179    * @param name An adopter-defined directive or macro name to accept, for example {@code "pageHero"}.
180    * @return This object.
181    */
182   public ConsoleTemplateValidator allowDirective(String name) {
183      allowed.add(name);
184      return this;
185   }
186
187   // Package-private (no production caller; the mixin owns its own registry).  Names packs the app's chrome already
188   // loads; a provided "echarts" pack suppresses the missing-webjar rule.
189   // @throws IllegalArgumentException If a name is not a registered pack.
190   ConsoleTemplateValidator providedPacks(String...names) {
191      var list = Arrays.asList(names);
192      packs.requireKnown(list, "providedPacks");
193      packs.provide(list);
194      echartsProbed = false;
195      return this;
196   }
197
198   // Package-private: registers an app-supplied toolkit pack; a replacement "echarts" pack (for example one served
199   // from a CDN) suppresses the missing-webjar rule.
200   // The mixin's registerToolkitPack(String, List, List) overload is deliberately absent: it builds a pack from asset
201   // lists, which cannot change whether the "charts" WebJars resolve, so no lint rule depends on it.
202   ConsoleTemplateValidator registerToolkitPack(ToolkitPack pack) {
203      packs.register(rnn(pack));
204      echartsProbed = false;
205      return this;
206   }
207
208   // Package-private: tests simulate an absent WebJar.
209   ConsoleTemplateValidator webJarProbe(UnaryOperator<String> probe) {
210      webJarProbe = rnn(probe);
211      echartsProbed = false;
212      return this;
213   }
214
215   // The E-70 message when the WebJars the "charts" pack reaches are missing, or null.  Probes the pack the chart card
216   // resolves at runtime (so a replaced "charts" or "echarts" pack is honoured) through the registry's own provided and
217   // replaced-pack knowledge; probed at most once per configuration, not once per chart card.  A broken pack graph
218   // (unknown dependsOn, cycle) is reported as an invalid-pack-graph finding instead of crashing the lint.
219   private String echartsProblem() {
220      if (! echartsProbed) {
221         echartsProblem = null;
222         echartsRule = "missing-webjar";
223         try {
224            packs.checkWebJars(List.of(ToolkitPackRegistry.PACK_CHARTS), webJarProbe);
225         } catch (IllegalStateException e) {
226            echartsProblem = e.getMessage();
227         } catch (IllegalArgumentException e) {
228            echartsProblem = e.getMessage();
229            echartsRule = "invalid-pack-graph";
230         }
231         echartsProbed = true;
232      }
233      return echartsProblem;
234   }
235
236   /**
237    * @param templateName The template to lint, relative to the template root or classpath root.
238    * @return The findings, sorted by line and column. Empty when the template is clean.
239    * @throws IllegalArgumentException If the template cannot be found.
240    */
241   public List<Finding> validate(String templateName) {
242      var src = load(templateName);
243      if (n(src))
244         throw iaex("Template '%s' not found under templateRoot or classpathRoot.", templateName);
245      return validateSource(templateName, src);
246   }
247
248   /**
249    * Lints every {@code *.ftlh} and {@code *.ftl} file under the template root.
250    *
251    * @return The findings, sorted by template, line and column. Empty when every template is clean.
252    * @throws IllegalStateException If no template root is set.
253    */
254   public List<Finding> validateAll() {
255      if (n(templateRoot))
256         throw isex("validateAll() requires templateRoot(Path); a classpath root cannot be listed.");
257      try (Stream<Path> s = Files.walk(templateRoot)) {
258         var names = s.filter(Files::isRegularFile)
259            .map(p -> templateRoot.relativize(p).toString().replace(File.separatorChar, '/'))
260            .filter(n -> n.endsWith(".ftlh") || n.endsWith(".ftl"))
261            .sorted()
262            .toList();
263         var out = new ArrayList<Finding>();
264         for (var n : names)
265            out.addAll(validate(n));
266         return out;
267      } catch (IOException e) {
268         throw new UncheckedIOException(e);
269      }
270   }
271
272   // Package-private: lints a source string as if it were the template with the given name (unit tests).
273   @SuppressWarnings({
274      "java:S3776" // One pass over the directive tags; splitting it would scatter the lint rules.
275   })
276   List<Finding> validateSource(String name, String source) {
277      var out = new ArrayList<Finding>();
278      var lines = lineStarts(source);
279      parse(name, source, out);
280      var text = blankComments(source);
281
282      var macros = new HashSet<String>(allowed);
283      var namespaces = new HashSet<String>();
284      collectScope(name, text, macros, namespaces, new HashSet<>());
285      if (nn(chromeTemplate) && neq(chromeTemplate, name)) {
286         var chrome = load(chromeTemplate);
287         if (n(chrome))
288            throw iaex("Chrome template '%s' not found under templateRoot or classpathRoot.", chromeTemplate);
289         collectScope(chromeTemplate, blankComments(chrome), macros, namespaces, new HashSet<>());
290      }
291
292      var siblings = new ArrayDeque<Set<String>>();
293      siblings.push(new HashSet<>());
294      var cardIds = new HashSet<String>();
295      var navDepth = 0;
296      var templateRefs = new ArrayList<Object[]>();   // each entry pairs a template name with its source offset
297      var consoleAt = -1;
298      var mains = 0;
299
300      var m = TAG.matcher(text);
301      while (m.find()) {
302         var closing = ! m.group(1).isEmpty();
303         var dname = m.group(2);
304         var selfClosing = ! m.group(4).isEmpty();
305         var at = m.start();
306         var known = closing ? null : DIRECTIVES.get(dname);
307         if (closing) {
308            if ((dname.equals(NodeDirectiveModel.NAME) || dname.equals(NavigationDirectiveModel.NAME)) && siblings.size() > 1)
309               siblings.pop();
310            if (dname.equals(NavigationDirectiveModel.NAME) && navDepth > 0)
311               navDepth--;
312         } else if (n(known)) {
313            var dot = dname.indexOf('.');
314            var ok = dot > 0 ? namespaces.contains(dname.substring(0, dot)) : macros.contains(dname);
315            if (! ok)
316               add(out, name, lines, at, "unknown-directive", f("<@%s> is not a console directive, a macro in scope, or allow-listed.", dname));
317         } else {
318            var attrs = attrs(m.group(3));
319            for (var a : attrs.keySet())
320               if (! known.contains(a))
321                  add(out, name, lines, at, "unknown-attribute", f("<@%s> unknown attribute '%s'.", dname, a));
322            for (var a : STRICT.getOrDefault(dname, Set.of())) {
323               var v = attrs.get(a);
324               if (nn(v) && v.literal && !eqa(v.value, "true", "false"))
325                  add(out, name, lines, at, "strict-boolean", f("<@%s> %s= must be true or false; got '%s'.", dname, a, v.value));
326            }
327            var id = attrs.get("id");
328            switch (dname) {
329               case NavigationDirectiveModel.NAME -> {
330                  if (! selfClosing) {
331                     siblings.push(new HashSet<>());
332                     navDepth++;
333                  }
334               }
335               case NodeDirectiveModel.NAME -> {
336                  if (nn(id) && id.literal && ! siblings.peek().add(id.value))
337                     add(out, name, lines, at, "duplicate-id", f("<@node id='%s'> duplicates a sibling id.", id.value));
338                  if (navDepth > 0 && attrs.containsKey("under"))
339                     add(out, name, lines, at, "unknown-attribute", f("<@%s> unknown attribute '%s'.", dname, "under"));
340                  if (! selfClosing)
341                     siblings.push(new HashSet<>());
342               }
343               case CardDirectiveModel.NAME -> {
344                  if (nn(id) && id.literal && ! cardIds.add(id.value))
345                     add(out, name, lines, at, "duplicate-id", f("<@card id='%s'> duplicates an existing card id.", id.value));
346                  var type = attrs.get("type");
347                  if (nn(type) && type.literal && REMOVED_TYPES.contains(type.value))
348                     add(out, name, lines, at, "removed-card-type", f(
349                        "<@card id='%s'> type='%s' was removed in 10.0.0; use type='html' with a <template>, or a registered card type.",
350                        n(id) ? "" : id.value, type.value));
351                  if (nn(type) && type.literal && eq(type.value, "chart")) {
352                     var problem = echartsProblem();
353                     if (nn(problem))
354                        add(out, name, lines, at, echartsRule, problem);
355                  }
356                  var tpl = attrs.get("template");
357                  if (nn(tpl) && tpl.literal)
358                     templateRefs.add(new Object[]{tpl.value, at});
359                  if (nn(type) && type.literal && eq(type.value, "datatables") && ! selfClosing)
360                     checkViewVersion(out, name, lines, text, m.end(), n(id) ? "" : id.value);
361                  if (! selfClosing)
362                     checkCardBody(out, name, lines, at, text, m.end(), id, attrs.get("src"), attrs.get("type"));
363               }
364               case ConsoleDirectiveModel.NAME -> {
365                  if (consoleAt < 0)
366                     consoleAt = at;
367               }
368               case MainDirectiveModel.NAME -> mains++;
369               case PageDirectiveModel.NAME -> checkPageAssets(out, name, lines, at, m.group(3));
370               default -> { /* slots, theme, token, page: nothing beyond the attribute checks above */ }
371            }
372         }
373      }
374
375      for (var r : templateRefs) {
376         var v = (String)r[0];
377         if (! cardIds.contains(v) && ! v.startsWith("header.") && ! v.startsWith("footer."))
378            add(out, name, lines, (Integer)r[1], "dangling-template", f("<@card> template='%s' names no <@card id> or slot in this template.", v));
379      }
380      if (consoleAt >= 0 && mains != 1)
381         add(out, name, lines, consoleAt, "main-count", f("<@console> requires exactly one <@main/>; found '%s'.", mains));
382
383      var g = GLOBAL.matcher(text);
384      while (g.find()) {
385         add(out, name, lines, g.start(), "removed-global", f("'%s' was removed in 10.0.0; %s", g.group(1),
386            eq(g.group(1), "pageToolkit") ? "use jcHasToolkit(\"views\")." : "<@page> captures the page into the contract."));
387      }
388
389      var a = ASSET_REF.matcher(text);
390      while (a.find()) {
391         var url = a.group(nn(a.group(1)) ? 1 : 2);
392         if (! url.contains("${") && ! url.contains("<#") && JUNEAU_ASSET.matcher(url).find())
393            add(out, name, lines, a.start(), "hardcoded-asset-url", f(
394               "Hard-coded Juneau asset URL '%s' is unversioned and goes stale in browser caches; use viewAssetUrl(...), consoleJsUrl(...), chromeCssUrl(...) or themeAssetUrl(...) so it carries ?v= (an adopter's own assets can use assetUrl(...)).", url));
395      }
396
397      out.sort(Comparator.comparingInt(Finding::line).thenComparingInt(Finding::column));
398      return out;
399   }
400
401   // The literal entries of one init=/css= match, or null when the value holds an expression (a call or ${...}).
402   private static List<String> literalPageAssetEntries(Matcher m) {
403      var entries = new ArrayList<String>();
404      if (nn(m.group(2))) {
405         var body = m.group(2);
406         if (body.contains("(") || body.contains("${"))
407            return null;
408         var q = QUOTED.matcher(body);
409         while (q.find())
410            entries.add(q.group(nn(q.group(1)) ? 1 : 2));
411         return entries;
412      }
413      var v = m.group(nn(m.group(3)) ? 3 : 4);
414      if (v.contains("${"))
415         return null;
416      for (var part : v.split(",")) {
417         var t = part.trim();
418         if (! t.isEmpty())
419            entries.add(t);
420      }
421      return entries;
422   }
423
424   // Flags a literal init=/css= entry that is neither absolute nor a context:/servlet: URI.  Lists holding an
425   // expression (a call or ${...}) are skipped: their entries are not literals.
426   private static void checkPageAssets(List<Finding> out, String name, int[] lines, int at, String attrText) {
427      var m = PAGE_ASSET.matcher(attrText);
428      while (m.find()) {
429         var attr = m.group(1);
430         var entries = literalPageAssetEntries(m);
431         if (entries == null)
432            continue;
433         for (var e : entries)
434            if (! FtlAttrLists.isAbsoluteAsset(e))
435               add(out, name, lines, at, "relative-page-asset", f(
436                  "<@page> %s= entry '%s' must be absolute (start with '/') or a context: / servlet: URI.", attr, e));
437      }
438   }
439
440   /**
441    * Flags a literal {@code view.contractVersion} that differs from {@link ViewsMixin#CONTRACT_VERSION} in a
442    * {@code type="datatables"} card body. An omitted version is fine (the runtime injects it); only a pinned, stale
443    * value is reported. Scans the {@code view:{...}} object at its own nesting depth so nested {@code contractVersion}
444    * keys (quickStats, detail, ...) are never mistaken for it.
445    */
446   private static void checkViewVersion(List<Finding> out, String name, int[] lines, String text, int bodyStart, String cardId) {
447      var end = text.indexOf("</@card", bodyStart);
448      var body = text.substring(bodyStart, end < 0 ? text.length() : end);
449      var vm = VIEW_KEY.matcher(body);
450      if (! vm.find())
451         return;
452      var depth = 1;
453      for (var i = vm.end(); i < body.length() && depth > 0; i++) {
454         var c = body.charAt(i);
455         if (c == '{' || c == '[')
456            depth++;
457         else if (c == '}' || c == ']')
458            depth--;
459         else if (depth == 1 && c == 'c') {
460            var v = VIEW_VERSION.matcher(body.substring(i));
461            if (v.find() && neq(v.group(1), ViewsMixin.CONTRACT_VERSION)) {
462               add(out, name, lines, bodyStart + i, "view-contract-version", f(
463                  "<@card id='%s'> view.contractVersion is '%s' but the runtime is '%s'; omit it to track the runtime automatically.",
464                  cardId, v.group(1), ViewsMixin.CONTRACT_VERSION));
465               return;
466            }
467         }
468      }
469   }
470
471   private record Value(String value, boolean literal) {}
472
473   // Mirrors CardTypeRegistry.BASE_KEYS (E-23); visibleWhen is deliberately excluded, same as there.
474   private static final Set<String> RESERVED_BODY_KEYS = Set.of("id", "type", "title", "src", "template", "ref");
475
476   /**
477    * The card-body rules: {@code card-src-and-body} and {@code card-reserved-key}.
478    * Reads the body the same way {@link #checkViewVersion} does, up to the next {@code </@card}.
479    */
480   @SuppressWarnings({
481      "java:S107" // Internal helper whose parameters are the render/validation context.
482   })
483   private static void checkCardBody(List<Finding> out, String name, int[] lines, int at, String text, int bodyStart, Value id, Value src, Value type) {
484      var end = text.indexOf("</@card", bodyStart);
485      var body = text.substring(bodyStart, end < 0 ? text.length() : end);
486      var cardId = n(id) ? "" : id.value;
487      var trimmed = body.trim();
488      // A chart card legitimately takes src= (remote rows) plus a body (kind and options).
489      var chart = nn(type) && type.literal && "chart".equals(type.value);
490      if (! trimmed.isEmpty() && nn(src) && src.literal && ! chart)
491         add(out, name, lines, at, "card-src-and-body", f(
492            "<@card id='%s'> has both src='%s' and a body; use exactly one.", cardId, src.value));
493      if (trimmed.isEmpty() || body.contains("${"))
494         return;
495      var keys = topLevelJson5Keys(trimmed);
496      for (var k : keys)
497         if (RESERVED_BODY_KEYS.contains(k))
498            add(out, name, lines, at, "card-reserved-key", f(
499               "<@card id='%s'> body key '%s' is reserved; set it as an attribute.", cardId, k));
500   }
501
502   // Hand-rolled, like attrs() below: finds JSON5 object keys at brace-depth 0, skipping quoted strings (backslash escapes honored). Not a
503   // general parser — enough to catch literal top-level keys for the two card-body lint rules above.
504   private static Set<String> topLevelJson5Keys(String body) {
505      var s = body.trim();
506      if (s.startsWith("{") && s.endsWith("}"))
507         s = s.substring(1, s.length() - 1);
508      var keys = new LinkedHashSet<String>();
509      var depth = 0;
510      var i = 0;
511      while (i < s.length()) {
512         var c = s.charAt(i);
513         if (c == '"' || c == '\'') {
514            // Honor backslash escapes in both quote styles: skip the escaped character wholesale.
515            var j = i + 1;
516            while (j < s.length() && s.charAt(j) != c)
517               j += s.charAt(j) == '\\' ? 2 : 1;
518            i = j >= s.length() ? s.length() : j + 1;
519         } else if (c == '{' || c == '[') {
520            depth++;
521            i++;
522         } else if (c == '}' || c == ']') {
523            depth--;
524            i++;
525         } else if (depth == 0 && (Character.isLetter(c) || c == '_')) {
526            var start = i;
527            while (i < s.length() && (Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '_'))
528               i++;
529            var word = s.substring(start, i);
530            var j = i;
531            while (j < s.length() && Character.isWhitespace(s.charAt(j)))
532               j++;
533            if (j < s.length() && s.charAt(j) == ':')
534               keys.add(word);
535         } else {
536            i++;
537         }
538      }
539      return keys;
540   }
541
542   private static Map<String,Value> attrs(String s) {
543      var out = new LinkedHashMap<String,Value>();
544      var m = ATTR.matcher(s);
545      while (m.find()) {
546         String v;
547         boolean literal;
548         if (nn(m.group(2)) || nn(m.group(3))) {
549            v = m.group(nn(m.group(2)) ? 2 : 3);
550            literal = ! v.contains("${");
551         } else {
552            v = m.group(4);
553            literal = eqa(v, "true", "false");
554         }
555         out.put(m.group(1), new Value(v, literal));
556      }
557      return out;
558   }
559
560   private void collectScope(String name, String text, Set<String> macros, Set<String> namespaces, Set<String> seen) {
561      if (! seen.add(name))
562         return;
563      var m = MACRO.matcher(text);
564      while (m.find())
565         macros.add(m.group(1));
566      var i = IMPORT.matcher(text);
567      while (i.find())
568         namespaces.add(i.group(1));
569      var inc = INCLUDE.matcher(text);
570      while (inc.find()) {
571         var target = resolve(name, inc.group(1));
572         var src = load(target);
573         if (nn(src))
574            collectScope(target, blankComments(src), macros, namespaces, seen);
575      }
576   }
577
578   private static String resolve(String from, String path) {
579      if (path.startsWith("/"))
580         return path;
581      var slash = from.lastIndexOf('/');
582      return slash < 0 ? path : from.substring(0, slash + 1) + path;
583   }
584
585   // Template root first, then the classpath root, then (for absolute names) the classpath itself.
586   private String load(String name) {
587      var rel = name.startsWith("/") ? name.substring(1) : name;
588      try {
589         if (nn(templateRoot)) {
590            var p = templateRoot.resolve(rel);
591            if (Files.isRegularFile(p))
592               return Files.readString(p, UTF_8);
593         }
594         if (nn(classpathRoot)) {
595            var s = resource(classpathRoot + rel);
596            if (nn(s))
597               return s;
598         }
599         return name.startsWith("/") ? resource(name) : null;
600      } catch (IOException e) {
601         throw new UncheckedIOException(e);
602      }
603   }
604
605   private static String resource(String absPath) throws IOException {
606      var cl = Thread.currentThread().getContextClassLoader();
607      if (n(cl))
608         cl = ConsoleTemplateValidator.class.getClassLoader();
609      try (var in = cl.getResourceAsStream(absPath.substring(1))) {
610         return n(in) ? null : new String(in.readAllBytes(), UTF_8);
611      }
612   }
613
614   @SuppressWarnings({
615      "unused" // the Template is built only so its constructor parses (and may throw)
616   })
617   private static void parse(String name, String source, List<Finding> out) {
618      try {
619         new Template(name, new StringReader(source), PARSE_CFG);
620      } catch (ParseException e) {
621         out.add(new Finding(name, e.getLineNumber(), e.getColumnNumber(), "parse-error", e.getEditorMessage()));
622      } catch (IOException e) {
623         throw new UncheckedIOException(e);
624      }
625   }
626
627   // Replaces each <#-- … --> with spaces (newlines kept), so offsets still map to the original line and column.
628   private static String blankComments(String s) {
629      var sb = new StringBuilder(s);
630      var m = COMMENT.matcher(s);
631      while (m.find())
632         for (var i = m.start(); i < m.end(); i++)
633            if (sb.charAt(i) != '\n')
634               sb.setCharAt(i, ' ');
635      return sb.toString();
636   }
637
638   @SuppressWarnings({
639      "javabugs:S2259" // False positive: validate() throws on a null load() result via n(src), which Sonar's flow analysis does not track as a null guard.
640   })
641   private static int[] lineStarts(String s) {
642      var starts = new ArrayList<Integer>();
643      starts.add(0);
644      for (var i = 0; i < s.length(); i++)
645         if (s.charAt(i) == '\n')
646            starts.add(i + 1);
647      return starts.stream().mapToInt(Integer::intValue).toArray();
648   }
649
650   private static void add(List<Finding> out, String name, int[] lines, int offset, String rule, String message) {
651      var i = Arrays.binarySearch(lines, offset);
652      var line = i >= 0 ? i : -i - 2;
653      out.add(new Finding(name, line + 1, offset - lines[line] + 1, rule, message));
654   }
655}