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;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.nio.charset.*;
023import java.util.*;
024import java.util.concurrent.*;
025import java.util.concurrent.atomic.*;
026import java.util.stream.*;
027
028import org.apache.juneau.commons.utils.*;
029import org.apache.juneau.http.*;
030import org.apache.juneau.http.response.*;
031import org.apache.juneau.rest.server.*;
032import org.apache.juneau.rest.server.util.*;
033
034/**
035 * Mixin that serves the admin-console chrome stylesheet at {@code /juneau-console/chrome.css}.
036 *
037 * <p>
038 * Compose into a host resource via {@link Rest#mixins() @Rest(mixins=ConsoleChromeMixin.class)} (see
039 * {@code DataTablesMixin} in the {@code juneau-console-datatables} module for the identical asset-serving
040 * pattern this mirrors &mdash; not linked here since that module is not a dependency of this one). The served
041 * response is the static
042 * structural {@code chrome.css} (shipped in this module's classpath) with {@link Theme#OPEN}'s block, then the
043 * selected stock theme's override block if one other than {@code open} was selected, appended as
044 * {@code html:root{}} blocks.
045 *
046 * <h2 class='section'>Mount styles:</h2>
047 * <p>
048 * Both of the following arrangements serve the stylesheets at the {@link #CHROME_CSS_PATH} / {@link #THEME_CSS_DIR}
049 * URLs with no path juggling by the host resource:
050 * <ul>
051 *    <li><b>Composed</b> &mdash; the host resource is mounted wherever the application already mounts it (e.g.
052 *       {@code /rest/*}) and the stylesheets hang off that mount, at
053 *       <code>&lt;host-mount&gt;/juneau-console/chrome.css</code>.
054 *    <li><b>Standalone</b> &mdash; the host resource is registered with the servlet container at url-pattern
055 *       {@code /juneau-console/*} so the stylesheets sit at a fixed site-root URL, independent of which page or tab
056 *       rendered the referencing {@code <link>}.
057 * </ul>
058 * <p>
059 * The two arrangements need different operation paths, because a container mount at {@code /juneau-console/*}
060 * reports {@code servletPath="/juneau-console"} and Juneau resolves an operation's path against the request URI
061 * with {@code contextPath + servletPath} already removed &mdash; leaving only {@code /chrome.css} to match.
062 * Each operation below therefore declares <i>both</i> its prefixed path and the same path minus the
063 * {@code /juneau-console} prefix, so whichever one the arrangement leaves to be matched resolves.
064 *
065 * <h2 class='section'>Theme precedence</h2>
066 * <p>{@link Builder#theme(String)} if set, else {@link Theme#OPEN}. {@link Theme#OPEN}'s block is always appended
067 * first; a selected non-{@code open} stock theme adds exactly one more block.
068 *
069 * <h2 class='section'>Stylesheet load-order band:</h2>
070 * <p>
071 * At equal cascade specificity, whichever of {@code juneau-views.css} and this class's {@code chrome.css} is
072 * declared later in a page's {@code <head>} wins &mdash; the exact ambiguity the {@code overrideBlock} theme block
073 * below is raised to {@code html:root} to make irrelevant. Juneau's own in-tree page emitters (the examples
074 * module) don't rely on that fix alone: they declare a five-position stylesheet/script load-order band,
075 * enforced by a build-time test, so their own asset order is never left to chance in the first place:
076 * <ol>
077 *    <li>vendor stylesheets
078 *    <li>{@code juneau-views.css} &mdash; the views base layer
079 *    <li>first-party widget stylesheets that build on the views layer, e.g. {@code juneau-calendar.css}
080 *    <li>the consumer theme, e.g. this class's {@code chrome.css}
081 *    <li>page-local {@code <style>}
082 * </ol>
083 * <p>
084 * That guard reaches only the pages Juneau itself emits. It says nothing about, and claims no control over, an
085 * arbitrary host application's own document &mdash; a consumer is free to link {@code chrome.css} and
086 * {@code juneau-views.css} in either order, which is precisely why the {@code html:root} fix exists: so the
087 * active theme wins regardless of which order the consumer's links happen to appear in.
088 *
089 * <h2 class='section'>Example:</h2>
090 * <p class='bjava'>
091 *    <jc>// Stock chrome.css (Theme.OPEN tokens), mounted standalone at /juneau-console/*.</jc>
092 *    <ja>@Rest</ja>(mixins=ConsoleChromeMixin.<jk>class</jk>)
093 *    <jk>public class</jk> ConsoleAssetsRest <jk>extends</jk> BasicRestServlet {
094 *       <ja>@Bean</ja>
095 *       <jk>public</jk> ConsoleChromeMixin consoleChrome() {
096 *          <jk>return</jk> ConsoleChromeMixin.<jsm>create</jsm>().build();
097 *       }
098 *    }
099 *
100 *    <jc>// Bake a different stock palette into the served chrome.css.</jc>
101 *    ConsoleChromeMixin.<jsm>create</jsm>().theme(<js>"gray"</js>).build();
102 * </p>
103 *
104 * <p>
105 * Custom palettes aren't configured here. Author them in the FreeMarker chrome with {@code <@theme>}/{@code <@token>}
106 * (see the {@link Theme} example), which emits the stock-theme {@code <link>} plus an inline override block.
107 *
108 * @since 10.0.0
109 */
110// @formatter:off
111@Rest
112@SuppressWarnings({
113   "java:S125", // Comments are explanatory; they are not commented-out code.
114   "java:S1192" // Duplicated "html:root{" selector text is a CSS protocol fragment; a constant would obscure the emitter.
115})
116public class ConsoleChromeMixin {
117
118   /** The URL path at which the chrome stylesheet is served (relative to the host mount). */
119   public static final String CHROME_CSS_PATH = "/juneau-console/chrome.css";
120
121   /** {@link #CHROME_CSS_PATH} minus the {@code /juneau-console} prefix - see the class javadoc's mount-styles section. */
122   static final String CHROME_CSS_PATH_UNPREFIXED = "/chrome.css";
123
124   /** Classpath location of the shipped structural stylesheet. */
125   static final String CHROME_CSS_RESOURCE = "/org/apache/juneau/console/chrome.css";
126
127   /**
128    * The URL directory the shipped stock-theme stylesheets are served under (relative to the host mount), e.g.
129    * {@code /juneau-console/themes/juneau-theme-light-red.css}. A subdirectory of the chrome mount so a
130    * templated {@code {file}} path cannot collide with the fixed {@link #CHROME_CSS_PATH} endpoint. The FTL
131    * {@code <@theme name="…"/>} directive links these; see {@link #themeAssetUrl(RestRequest, String)}.
132    */
133   public static final String THEME_CSS_DIR = "/juneau-console/themes/";
134
135   /** {@link #THEME_CSS_DIR} minus the {@code /juneau-console} prefix - see the class javadoc's mount-styles section. */
136   static final String THEME_CSS_DIR_UNPREFIXED = "/themes/";
137
138   /** Classpath directory the shipped theme stylesheets live in (same package as {@link #CHROME_CSS_RESOURCE}). */
139   static final String THEME_CSS_RESOURCE_DIR = "/org/apache/juneau/console/";
140
141   /** The stock palettes by FTL/builder name, in documented order; the single source for the name list and file allowlist. */
142   private static final Map<String,Theme> STOCK_THEMES = stockThemes();
143
144   /**
145    * The built-in stock-theme names - the kebab-case of the {@link Theme} constants ({@link Theme#OPEN},
146    * {@link Theme#LIGHT_RED}, {@link Theme#LIGHT_BROWN}, {@link Theme#RED}, {@link Theme#GRAY}). Each maps to a
147    * shipped {@code juneau-theme-<name>.css} stylesheet. Consumed by the FTL {@code <@theme>} directive to fail an
148    * unknown name closed, and here to bound the served {@code {file}} to a known stock theme.
149    */
150   public static final List<String> BUILTIN_THEME_NAMES = List.copyOf(STOCK_THEMES.keySet());
151
152   /**
153    * The colour-scheme pin values, in documented order.
154    *
155    * <p>
156    * {@code auto} (the default) follows the browser's {@code prefers-color-scheme}; {@code light} and {@code dark}
157    * pin the page to that scheme. Accepted by {@code <@console scheme="…">}, {@code PageSpec.scheme(String)} and
158    * {@link #schemeHead(RestRequest, String, boolean)}.
159    */
160   public static final List<String> SCHEMES = List.of("auto", "light", "dark");
161
162   /**
163    * The inline pre-paint script that picks the page's colour scheme before first paint.
164    *
165    * <p>
166    * It sets {@code data-jc-scheme} on the root element from, in order: the visitor's stored choice (only when the
167    * root carries {@code data-jc-scheme-toggle}), the server pin ({@code data-jc-scheme-pin}), then the browser's
168    * {@code prefers-color-scheme}. It never throws: storage and media-query failures fall through to the next
169    * source, ending at {@code light}.
170    *
171    * <p>
172    * When the root carries {@code data-jc-theme-selector}, a stored theme pick that is in the root's
173    * {@code data-jc-themes} allow-list also re-points the palette link ({@code data-jc-theme-link}) as soon as the
174    * parser inserts it.
175    *
176    * <p>
177    * The text is a byte-for-byte constant so {@link #SCHEME_SCRIPT_CSP_HASH} is stable. Emit it as the first child
178    * of {@code <head>}, ahead of every stylesheet.
179    */
180   public static final String SCHEME_SCRIPT = String.join("\n",
181      "(function(d){var e=d.documentElement,k=\"juneau-console:scheme\",s=null;",
182      "if(e.hasAttribute(\"data-jc-scheme-toggle\")){try{s=localStorage.getItem(k)}catch(x){}}",
183      "if(s!==\"light\"&&s!==\"dark\"){s=e.getAttribute(\"data-jc-scheme-pin\");}",
184      "if(s!==\"light\"&&s!==\"dark\"){try{s=matchMedia(\"(prefers-color-scheme: dark)\").matches?\"dark\":\"light\"}catch(x){s=\"light\"}}",
185      "e.setAttribute(\"data-jc-scheme\",s);",
186      "if(e.hasAttribute(\"data-jc-theme-selector\")){try{var t=localStorage.getItem(\"juneau-console:theme\"),a=(e.getAttribute(\"data-jc-themes\")||\"\").split(\" \");",
187      "if(t&&a.indexOf(t)>=0){var o=new MutationObserver(function(){var l=d.querySelector(\"link[data-jc-theme-link]\");",
188      "if(l){o.disconnect();var h=l.getAttribute(\"href\");l.setAttribute(\"data-jc-theme-default\",h);l.setAttribute(\"href\",h.replace(/juneau-theme-[a-z-]+\\.css/,\"juneau-theme-\"+t+\".css\"))}});",
189      "o.observe(e,{childList:true,subtree:true});d.addEventListener(\"DOMContentLoaded\",function(){o.disconnect()})}}catch(x){}}",
190      "})(document);");
191
192   /**
193    * The CSP source expression for {@link #SCHEME_SCRIPT}: {@code 'sha256-<base64>'} over its UTF-8 bytes.
194    *
195    * <p>
196    * Add it to a {@code script-src} directive to allow the pre-paint script without a nonce. It covers only the
197    * script. The console shell's inline {@code <style>} (theme override blocks) still needs the request nonce or
198    * {@code 'unsafe-inline'} in {@code style-src}.
199    */
200   public static final String SCHEME_SCRIPT_CSP_HASH = sha256Source(SCHEME_SCRIPT);
201
202   /** The served stock stylesheet file names, derived from {@link #BUILTIN_THEME_NAMES}. */
203   private static final Set<String> ALLOWED_THEME_FILES = Stream.concat(
204         BUILTIN_THEME_NAMES.stream().map(n -> "juneau-theme-" + n + ".css"),
205         // The shared dark neutral layer is a served theme file but not a selectable theme, so it is not in
206         // BUILTIN_THEME_NAMES (theme="dark" must keep failing validation).
207         Stream.of("juneau-theme-dark.css"))
208      .collect(Collectors.toUnmodifiableSet());
209
210   private static Map<String,Theme> stockThemes() {
211      Map<String,Theme> m = m(
212         "open", Theme.OPEN,
213         "light-red", Theme.LIGHT_RED,
214         "light-brown", Theme.LIGHT_BROWN,
215         "red", Theme.RED,
216         "gray", Theme.GRAY
217      );
218      return u(m);
219   }
220
221   /** Content type emitted for the chrome stylesheet. */
222   static final String CONTENT_TYPE = "text/css;charset=utf-8";
223
224   /** {@code Cache-Control} header emitted for the chrome stylesheet (1 day). */
225   static final String CACHE_CONTROL = "max-age=86400, public";
226
227   /** Context-root-absolute path of the console shell script. */
228   public static final String CONSOLE_JS_PATH = "/juneau-console/juneau-console.js";
229
230   /** {@link #CONSOLE_JS_PATH} minus the {@code /juneau-console} prefix - see the class javadoc's mount-styles section. */
231   public static final String CONSOLE_JS_PATH_UNPREFIXED = "/juneau-console.js";
232
233   /** Classpath location of the console shell script. */
234   public static final String CONSOLE_JS_RESOURCE = "/org/apache/juneau/console/juneau-console.js";
235
236   /** Context-root-absolute path of the count-badge script. */
237   public static final String BADGES_JS_PATH = "/juneau-console/juneau-badges.js";
238
239   /** {@link #BADGES_JS_PATH} minus the {@code /juneau-console} prefix. */
240   public static final String BADGES_JS_PATH_UNPREFIXED = "/juneau-badges.js";
241
242   /** Classpath location of the count-badge script. */
243   public static final String BADGES_JS_RESOURCE = "/org/apache/juneau/console/juneau-badges.js";
244
245   /** Context-root-absolute path of the chart-card runtime. */
246   public static final String CHARTS_JS_PATH = "/juneau-console/juneau-charts.js";
247
248   /** {@link #CHARTS_JS_PATH} minus the {@code /juneau-console} prefix. */
249   public static final String CHARTS_JS_PATH_UNPREFIXED = "/juneau-charts.js";
250
251   /** Classpath location of the chart-card runtime. */
252   public static final String CHARTS_JS_RESOURCE = "/org/apache/juneau/console/juneau-charts.js";
253
254   /** Context-root-absolute path of the job-log card runtime. */
255   public static final String JOBLOG_JS_PATH = "/juneau-console/juneau-joblog.js";
256
257   /** {@link #JOBLOG_JS_PATH} minus the {@code /juneau-console} prefix. */
258   public static final String JOBLOG_JS_PATH_UNPREFIXED = "/juneau-joblog.js";
259
260   /** Classpath location of the job-log card runtime. */
261   public static final String JOBLOG_JS_RESOURCE = "/org/apache/juneau/console/juneau-joblog.js";
262
263   /** Context-root-absolute path of the dashboard chrome runtime. */
264   public static final String DASHBOARD_JS_PATH = "/juneau-console/juneau-dashboard.js";
265
266   /** {@link #DASHBOARD_JS_PATH} minus the {@code /juneau-console} prefix. */
267   public static final String DASHBOARD_JS_PATH_UNPREFIXED = "/juneau-dashboard.js";
268
269   /** Classpath resource behind {@link #DASHBOARD_JS_PATH}. */
270   public static final String DASHBOARD_JS_RESOURCE = "/org/apache/juneau/console/juneau-dashboard.js";
271
272   /** Context-root-absolute path of the switcher card runtime. */
273   public static final String SWITCHER_JS_PATH = "/juneau-console/juneau-switcher.js";
274
275   /** {@link #SWITCHER_JS_PATH} minus the {@code /juneau-console} prefix. */
276   public static final String SWITCHER_JS_PATH_UNPREFIXED = "/juneau-switcher.js";
277
278   /** Classpath resource behind {@link #SWITCHER_JS_PATH}. */
279   public static final String SWITCHER_JS_RESOURCE = "/org/apache/juneau/console/juneau-switcher.js";
280
281   /** Context-root-absolute path of the page-contract schema. */
282   public static final String SCHEMA_PATH = "/juneau-console/juneau-page.schema.json";
283
284   /** {@link #SCHEMA_PATH} minus the {@code /juneau-console} prefix. */
285   static final String SCHEMA_PATH_UNPREFIXED = "/juneau-page.schema.json";
286
287   /** Classpath location of the page-contract schema (same file as {@link PageContractSchema#RESOURCE}). */
288   static final String SCHEMA_RESOURCE = "/" + PageContractSchema.RESOURCE;
289
290   static final String JS_CONTENT_TYPE = "text/javascript;charset=utf-8";
291   static final String JSON_CONTENT_TYPE = "application/json;charset=utf-8";
292
293   /**
294    * The framework-authored role-token alias derivations.
295    *
296    * <p>
297    * {@code chrome.css} consumes <i>role</i>-named tokens ({@code --jc-header-bg}, {@code --jc-surface},
298    * {@code --jc-on-accent}, ...); {@link Theme#OPEN} (and every consumer theme) still defines the original
299    * <i>colour</i>-named leaf tokens ({@code --jc-white}, {@code --jc-border-2}, ...). This block bridges the two
300    * by deriving each role token <b>from</b> the legacy token it replaces, so a consumer's existing override of a
301    * legacy token still flows through to every derived role, and a consumer who sets a role token directly
302    * out-ranks the derived default by cascade order (this block is emitted inside the {@code Theme.OPEN} block,
303    * before any active-theme override block).
304    *
305    * <p>
306    * These aliases are <b>permanent</b> (no deprecation window) and are deliberately <i>not</i>
307    * {@link Theme#OPEN} tokens. A {@code var(--jc-*)}-valued token IS legal Theme-layer syntax &mdash;
308    * {@code Theme.Builder} recognizes it as a reference and resolves it to a concrete literal at {@code build()}
309    * time &mdash; but that resolution scope deliberately excludes these role aliases, which are appended here
310    * outside {@code Theme.OPEN}'s token map. Making them {@code Theme.OPEN} tokens instead would resolve each alias
311    * to a <i>fixed literal</i> at composition time, snapshotting the live CSS cascade (the dark-mode /
312    * user-agent overrides that reach these role tokens at use time) into a frozen value &mdash; so
313    * {@code Theme.OPEN} is kept all-literal and the aliases stay here as framework-authored literal text that is
314    * emitted verbatim (never routed through {@code CssValueGrammar}, which exists to validate <i>consumer</i>
315    * input, not the framework's own stylesheet). {@code Theme.OPEN} owns leaf values; this block owns derived
316    * values; no token name is declared by both.
317    *
318    * <p>
319    * {@code --jc-danger-text} and {@code --jc-success-text} are the text-ink roles of the danger and success
320    * colours; the fills keep {@code --jc-danger} and {@code --jc-success}.
321    *
322    * <p>
323    * {@code --jc-header-bg} (and, transitively, {@code --jc-nav-bg}) keys off {@code --jc-white}, not
324    * {@code --jc-chrome-bg}: in the light scheme the header and both page-nav rows (Page Tabs and Page Subtabs)
325    * stay white on every stock theme (the dark layer sets the header background directly), matching
326    * {@link Theme#OPEN}'s blue look. Theme accent still paints the selected-tab
327    * indicator, page-nav floor, and the rest of the page; {@code --jc-chrome-bg} remains the page-chrome
328    * fallback under {@code --jc-page-bg}, the hover fill, and dialog chrome. Pinning header/nav to
329    * {@code --jc-chrome-bg} washed those bars in light-red / light-brown / red / gray. {@code --jc-page-nav-accent}
330    * defaults to {@code --jc-accent} so a consumer can retint the page-nav floor / selected-section bar without
331    * recoloring buttons. {@code --jc-table-header-bg} also keys off {@code --jc-white} so DataTable / views-table
332    * column headers stay white (the original artwork gives {@code table.dataTable thead th} no background), not the page-chrome grey.
333    */
334   static final String OPEN_ROLE_ALIASES = String.join("",
335      "--jc-surface:var(--jc-white);",
336      "--jc-header-bg:var(--jc-white);",
337      "--jc-nav-bg:var(--jc-header-bg);",
338      "--jc-page-nav-accent:var(--jc-accent);",
339      "--jc-control-bg:var(--jc-surface);",
340      "--jc-table-bg:var(--jc-surface);",
341      "--jc-table-row-bg:var(--jc-surface);",
342      "--jc-on-accent:var(--jc-white);",
343      "--jc-on-btn-primary:var(--jc-on-accent);",
344      "--jc-hover-bg:var(--jc-chrome-bg);",
345      // DataTable / views-table headers are white (the original artwork gives `table.dataTable thead th` no background;
346      // the white card shows through). Do not key this off --jc-chrome-bg — that page-chrome grey tints
347      // every column header and is the wrong surface (the detail-table thead grey is a different widget).
348      "--jc-table-header-bg:var(--jc-white);",
349      "--jc-control-border:var(--jc-border-2);",
350      "--jc-header-icon-text:var(--jc-header-icon-color);",
351      "--jc-btn-primary-bg:var(--jc-btn-primary);",
352      "--jc-btn-primary-bg-hover:var(--jc-btn-primary-hover);",
353      // Text roles: danger/success used as ink, so the dark layer can lighten them without touching the fills.
354      "--jc-danger-text:var(--jc-danger);",
355      "--jc-success-text:var(--jc-success);"
356   );
357
358   /**
359    * The names of the role aliases the chrome declares (for example {@code --jc-surface} and
360    * {@code --jc-danger-text}), derived from the same declarations the stylesheet emits.
361    */
362   private static final Set<String> ROLE_ALIAS_NAMES = Arrays.stream(OPEN_ROLE_ALIASES.split(";"))
363      .map(d -> d.substring(0, d.indexOf(':')))
364      .collect(Collectors.toUnmodifiableSet());
365
366   /**
367    * Returns the names of the role aliases the chrome declares, such as {@code --jc-surface},
368    * {@code --jc-danger-text} and {@code --jc-header-bg}.
369    *
370    * <p>
371    * These are the custom properties the chrome derives from the {@link Theme#OPEN} tokens. They are not tokens of
372    * any {@link Theme}, but a page resolves them at run time, so the FreeMarker {@code <@token scheme="dark">}
373    * alias check accepts them as targets.
374    *
375    * @return An unmodifiable set of custom-property names; never <jk>null</jk>.
376    */
377   public static Set<String> roleAliasNames() {
378      return ROLE_ALIAS_NAMES;
379   }
380
381   /** The shipped static chrome.css bytes, read once from the classpath (shared - the static file never varies by theme). */
382   private static volatile String staticCss;
383
384   /**
385    * Read+cache+hash+serve helper for the configured theme/chrome assets, anchored on this class so
386    * {@link ClasspathAssetCache#buildVersion()} resolves this module's own implementation version (see that
387    * class's javadoc's version-anchor section).
388    */
389   private static final ClasspathAssetCache ASSET_CACHE = new ClasspathAssetCache(ConsoleChromeMixin.class);
390
391   private final boolean cacheAssets;
392   private final Theme theme;
393
394   /** Per-mixin-instance cache of the fully-assembled (static + theme blocks) response body, keyed by mount (see {@link #mountKey}). */
395   private final Map<String,byte[]> cachedBodies = new ConcurrentHashMap<>();
396
397   /** Test-only diagnostic: counts every call to {@link #buildBody(RestRequest)} (i.e. every cache miss / every call when caching is disabled). */
398   private final AtomicInteger buildCount = new AtomicInteger();
399
400   /**
401    * No-arg constructor, mirroring {@code FreemarkerMixin()}'s equivalent so a bean-store lookup miss can fall back
402    * to a default-configured instance without relying on {@code BeanInstantiator}'s builder-pattern detection.
403    */
404   public ConsoleChromeMixin() {
405      this(create());
406   }
407
408   /**
409    * Constructor.
410    *
411    * @param builder The builder.
412    */
413   protected ConsoleChromeMixin(Builder builder) {
414      this.cacheAssets = builder.cacheAssets;
415      this.theme = builder.theme;
416   }
417
418   /**
419    * Creates a new builder.
420    *
421    * @return A new builder.
422    */
423   public static Builder create() {
424      return new Builder();
425   }
426
427   /**
428    * [GET /juneau-console/chrome.css] &mdash; serve the admin-console chrome stylesheet.
429    *
430    * @param req The current request, used to key the per-mount body cache.
431    * @return The chrome stylesheet as a CSS {@link HttpResource}.
432    * @throws IOException If the shipped {@code chrome.css} resource could not be read (effectively unreachable
433    *    &mdash; the resource is shipped in the same jar as this class).
434    */
435   @RestGet(
436      path={CHROME_CSS_PATH, CHROME_CSS_PATH_UNPREFIXED},
437      summary="Admin-console chrome stylesheet",
438      description="Structural CSS for the admin-console chrome, with the selected stock theme's tokens appended.",
439      swagger=@OpSwagger(ignore=true)
440   )
441   public HttpResource getChromeCss(RestRequest req) throws IOException {
442      var body = cacheAssets ? cachedBody(req) : buildBody();
443      return ASSET_CACHE.wrap(body, CONTENT_TYPE, CACHE_CONTROL);
444   }
445
446   /**
447    * [GET /juneau-console/themes/{file}] &mdash; serve one of the shipped stock-theme stylesheets.
448    *
449    * <p>
450    * The {@code {file}} segment is fail-closed to the known {@link #BUILTIN_THEME_NAMES} stylesheet filenames, so
451    * this endpoint can never read an arbitrary classpath resource. Each stylesheet is a structure-free
452    * {@code html:root{}} token block (one per {@link Theme} constant); the FTL {@code <@theme name="…"/>} directive
453    * links the winning one after {@code chrome.css} so its tokens override {@code chrome.css}'s baked-in
454    * {@link Theme#OPEN} block.
455    *
456    * @param file The requested stylesheet filename (e.g. {@code juneau-theme-light-red.css}).
457    * @return The theme stylesheet as a CSS {@link HttpResource}.
458    * @throws NotFound If {@code file} is not one of the shipped stylesheet filenames.
459    */
460   @RestGet(
461      path={THEME_CSS_DIR + "{file}", THEME_CSS_DIR_UNPREFIXED + "{file}"},
462      summary="Admin-console stock theme stylesheet",
463      description="One of the shipped juneau-theme-<name>.css stock theme stylesheets (html:root token block), linked by the FTL <@theme> directive.",
464      swagger=@OpSwagger(ignore=true)
465   )
466   public HttpResource getThemeCss(@Path("file") String file) {
467      if (! ALLOWED_THEME_FILES.contains(file))
468         throw new NotFound("Unknown theme stylesheet: " + file);
469      return ASSET_CACHE.serve(THEME_CSS_RESOURCE_DIR + file, CONTENT_TYPE, CACHE_CONTROL);
470   }
471
472   /**
473    * [GET /juneau-console/juneau-console.js] &mdash; serve the console shell.
474    *
475    * @return The script.
476    */
477   @RestGet(
478      path={CONSOLE_JS_PATH, CONSOLE_JS_PATH_UNPREFIXED},
479      summary="Console shell script",
480      description="Renders the #juneau-page contract into header, nav, cards and footer.",
481      swagger=@OpSwagger(ignore=true)
482   )
483   public HttpResource getConsoleJs() {
484      return ASSET_CACHE.serve(CONSOLE_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
485   }
486
487   /**
488    * [GET /juneau-console/juneau-badges.js] &mdash; serve the count-badge script.
489    *
490    * @return The script.
491    */
492   @RestGet(
493      path={BADGES_JS_PATH, BADGES_JS_PATH_UNPREFIXED},
494      summary="Console count-badge script",
495      description="Polls and renders the header.badges entries of the #juneau-page contract.",
496      swagger=@OpSwagger(ignore=true)
497   )
498   public HttpResource getBadgesJs() {
499      return ASSET_CACHE.serve(BADGES_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
500   }
501
502   /**
503    * [GET /juneau-console/juneau-charts.js] &mdash; serve the chart-card runtime.
504    *
505    * @return The script.
506    */
507   @RestGet(
508      path={CHARTS_JS_PATH, CHARTS_JS_PATH_UNPREFIXED},
509      summary="Console chart-card runtime",
510      description="Renders type='chart' cards of the #juneau-page contract as inline SVG.",
511      swagger=@OpSwagger(ignore=true)
512   )
513   public HttpResource getChartsJs() {
514      return ASSET_CACHE.serve(CHARTS_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
515   }
516
517   /**
518    * [GET /juneau-console/juneau-joblog.js] &mdash; serve the job-log card runtime.
519    *
520    * @return The script.
521    */
522   @RestGet(
523      path={JOBLOG_JS_PATH, JOBLOG_JS_PATH_UNPREFIXED},
524      summary="Console job-log card runtime",
525      description="Submits, streams and cancels AsyncJobsMixin jobs for type='job-log' cards.",
526      swagger=@OpSwagger(ignore=true)
527   )
528   public HttpResource getJobLogJs() {
529      return ASSET_CACHE.serve(JOBLOG_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
530   }
531
532   /**
533    * [GET /juneau-console/juneau-dashboard.js] &mdash; serve the dashboard chrome runtime.
534    *
535    * @return The script.
536    */
537   @RestGet(
538      path={DASHBOARD_JS_PATH, DASHBOARD_JS_PATH_UNPREFIXED},
539      summary="Console dashboard chrome runtime",
540      description="The rail, grid, status header, persistence and share links of a PageSpec dashboard.",
541      swagger=@OpSwagger(ignore=true)
542   )
543   public HttpResource getDashboardJs() {
544      return ASSET_CACHE.serve(DASHBOARD_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
545   }
546
547   /**
548    * [GET /juneau-console/juneau-switcher.js] &mdash; serve the switcher card runtime.
549    *
550    * @return The script.
551    */
552   @RestGet(
553      path={SWITCHER_JS_PATH, SWITCHER_JS_PATH_UNPREFIXED},
554      summary="Console switcher card runtime",
555      description="The view selector, sections, persistence and URL state of a switcher card.",
556      swagger=@OpSwagger(ignore=true)
557   )
558   public HttpResource getSwitcherJs() {
559      return ASSET_CACHE.serve(SWITCHER_JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
560   }
561
562   /**
563    * [GET /juneau-console/juneau-page.schema.json] &mdash; serve the page-contract schema.
564    *
565    * @return The schema.
566    */
567   @RestGet(
568      path={SCHEMA_PATH, SCHEMA_PATH_UNPREFIXED},
569      summary="Console page-contract schema",
570      description="JSON Schema 2020-12 for the #juneau-page contract.",
571      swagger=@OpSwagger(ignore=true)
572   )
573   public HttpResource getPageSchema() {
574      return ASSET_CACHE.serve(SCHEMA_RESOURCE, JSON_CONTENT_TYPE, CACHE_CONTROL);
575   }
576
577   /**
578    * Returns a real, browser-fetchable URL for a shipped theme stylesheet, resolved against the request's
579    * <b>context root</b> (not the page resource) and carrying the same {@code ?v=<buildVersion>-<hash8>}
580    * content-sensitive cache-buster {@link #chromeCssUrl(RestRequest)} uses.
581    *
582    * <p>
583    * The console document shell ({@code <@console>} / {@code <@theme>}) emits this as a {@code <link href>} to the
584    * standalone {@code /juneau-console/*} mount. Resolving with {@code context:} rather than {@code servlet:} is
585    * load-bearing: a page resource at {@code /rest/setup} reports that path as its servlet path, so
586    * {@code servlet:/juneau-console/themes/…} would become {@code /rest/setup/juneau-console/themes/…} and 404.
587    * A template-rendering consumer sits downstream of Juneau's {@code servlet:}-rewriting serializer, so it needs
588    * the URL already resolved here.
589    *
590    * @param req The current request, supplying the context path to resolve against.
591    * @param name One of the {@link #BUILTIN_THEME_NAMES}.
592    * @return The context-root-absolute theme-stylesheet URL with the version+content-hash cache-buster appended.
593    */
594   public static String themeAssetUrl(RestRequest req, String name) {
595      var file = "juneau-theme-" + name + ".css";
596      return consoleMountUrl(req, THEME_CSS_DIR + file, THEME_CSS_RESOURCE_DIR + file);
597   }
598
599   /**
600    * Returns a real, browser-fetchable URL for the shipped {@code chrome.css}, resolved against the request's
601    * <b>context root</b> (not the page resource) and carrying the same content-sensitive {@code ?v=…} cache-buster
602    * the theme stylesheets use.
603    *
604    * <p>
605    * The console document shell ({@code <@console>}) emits this as the first stylesheet in its head cascade. See
606    * {@link #themeAssetUrl(RestRequest, String)} for why the resolution is {@code context:} rather than
607    * {@code servlet:}.
608    *
609    * @param req The current request, supplying the context path to resolve against.
610    * @return The context-root-absolute {@code chrome.css} URL with the version+content-hash cache-buster appended.
611    */
612   public static String chromeCssUrl(RestRequest req) {
613      return consoleMountUrl(req, CHROME_CSS_PATH, CHROME_CSS_RESOURCE);
614   }
615
616   /**
617    * Context-root-absolute, cache-busted URL of the console shell script.
618    *
619    * @param req The current request.
620    * @return The URL.
621    */
622   public static String consoleJsUrl(RestRequest req) {
623      return consoleMountUrl(req, CONSOLE_JS_PATH, CONSOLE_JS_RESOURCE);
624   }
625
626   /**
627    * Context-root-absolute, cache-busted URL of the count-badge script.
628    *
629    * @param req The current request.
630    * @return The URL.
631    */
632   public static String badgesJsUrl(RestRequest req) {
633      return consoleMountUrl(req, BADGES_JS_PATH, BADGES_JS_RESOURCE);
634   }
635
636   /**
637    * Context-root-absolute, cache-busted URL of a console card runtime; the resolver of the {@code charts} and
638    * {@code joblog} toolkit packs.
639    *
640    * @param req The current request.
641    * @param path {@link #CHARTS_JS_PATH}, {@link #JOBLOG_JS_PATH}, {@link #DASHBOARD_JS_PATH} or {@link #SWITCHER_JS_PATH}.
642    * @return The URL.
643    * @throws IllegalArgumentException If {@code path} is neither.
644    */
645   public static String consoleAssetUrl(RestRequest req, String path) {
646      if (CHARTS_JS_PATH.equals(path))
647         return consoleMountUrl(req, CHARTS_JS_PATH, CHARTS_JS_RESOURCE);
648      if (JOBLOG_JS_PATH.equals(path))
649         return consoleMountUrl(req, JOBLOG_JS_PATH, JOBLOG_JS_RESOURCE);
650      if (DASHBOARD_JS_PATH.equals(path))
651         return consoleMountUrl(req, DASHBOARD_JS_PATH, DASHBOARD_JS_RESOURCE);
652      if (SWITCHER_JS_PATH.equals(path))
653         return consoleMountUrl(req, SWITCHER_JS_PATH, SWITCHER_JS_RESOURCE);
654      throw iaex("Unknown console asset '%s'.", path);
655   }
656
657   /**
658    * Context-root-absolute URL for an asset on the standalone {@code /juneau-console/*} mount.
659    *
660    * <p>
661    * Always the prefixed path ({@link #CHROME_CSS_PATH} / {@link #THEME_CSS_DIR}), resolved with {@code context:}
662    * so the href is {@code {contextPath}/juneau-console/…} regardless of which page resource rendered the shell.
663    */
664   private static String consoleMountUrl(RestRequest req, String prefixedPath, String resource) {
665      return req.getUriResolver().resolve("context:" + prefixedPath) + ASSET_CACHE.cacheBuster(resource);
666   }
667
668   /**
669    * Maps one of the {@link #BUILTIN_THEME_NAMES} stock names to its {@link Theme} constant.
670    *
671    * <p>
672    * The single place the kebab-case stock name (as written on FTL {@code <@theme name="…">} / the
673    * {@code theme(String)} builder) is resolved to its shipped {@link Theme}, without a second copy of the
674    * name&rarr;theme table.
675    *
676    * @param name One of the {@link #BUILTIN_THEME_NAMES}.
677    * @return The stock {@link Theme} for {@code name}.
678    * @throws IllegalArgumentException If {@code name} is not a built-in stock-theme name.
679    */
680   public static Theme stockTheme(String name) {
681      var t = STOCK_THEMES.get(name);
682      if (t == null)
683         throw iaex("Unknown stock theme name: '%s'.  Built-in themes: %s.", name, String.join(", ", BUILTIN_THEME_NAMES));
684      return t;
685   }
686
687   /**
688    * Returns the fully-assembled response body for the mount the request arrived under, computing (and caching) it
689    * on first call for that mount.
690    *
691    * <p>
692    * The cache is keyed by mount rather than held in a single field so one mixin instance registered under more
693    * than one container mapping (see the class javadoc's mount-styles section) builds and caches its body
694    * independently for each mount it is reached under.
695    */
696   private byte[] cachedBody(RestRequest req) throws IOException {
697      try {
698         return cachedBodies.computeIfAbsent(mountKey(req), k -> {
699            try {
700               return buildBody();
701            } catch (IOException e) {  // HTT: staticCss() is the only throwing call and reads a resource shipped in this jar.
702               throw new UncheckedIOException(e);
703            }
704         });
705      } catch (UncheckedIOException e) {  // HTT: see above - the wrapped read cannot fail in a well-formed jar.
706         throw e.getCause();
707      }
708   }
709
710   /** The request's mount identity: the two request properties every emitted asset URL is derived from. */
711   private static String mountKey(RestRequest req) {
712      return req.getContextPath() + '\n' + req.getServletPath();
713   }
714
715   /**
716    * Builds the response body: the static structural CSS, then {@link Theme#OPEN}'s block, then the selected stock
717    * theme's override block if a non-{@code open} stock theme was selected.
718    */
719   private byte[] buildBody() throws IOException {
720      buildCount.incrementAndGet();
721      var sb = new StringBuilder(staticCss());
722      sb.append('\n').append(openRootBlock());
723      var active = theme == null ? Theme.OPEN : theme;
724      if (! active.getName().equals(Theme.OPEN.getName()))
725         sb.append('\n').append(overrideBlock(active));
726      return sb.toString().getBytes(StandardCharsets.UTF_8);
727   }
728
729   /**
730    * Test-only diagnostic: the number of times this instance has (re)assembled its response body.
731    *
732    * @return The build count.
733    */
734   int debugBuildCount() { return buildCount.get(); }
735
736   /**
737    * Renders a theme's override block: one {@code html:root&#123;...&#125;} carrying the theme's leaf tokens, then its
738    * alias tokens, each in declaration order.
739    *
740    * <p>
741    * The two halves are escaped differently. A leaf is a validated literal and goes through
742    * {@link CssValueEscaper}: a grammar-accepted value can still carry a character such as {@code ;} that would end
743    * the declaration early. An alias is a single anchored {@code var(--jc-name)} reference
744    * ({@link Theme.Builder#alias(String, String)}), in which nothing dangerous is representable, so it is emitted
745    * verbatim. That asymmetry is the reason {@link Theme#getAliases()} stays a map.
746    *
747    * <p>
748    * The block uses the {@code html} type prefix. Two {@code :root} blocks in separately linked stylesheets tie at
749    * specificity {@code (0,0,1,0)} and are resolved by {@code <link>} order, which this framework neither sets
750    * nor observes. {@code html:root} scores {@code (0,0,1,1)}, so a theme override wins in either order.
751    *
752    * <p>
753    * A theme with no leaves and no aliases renders as the empty string. Each declared name is re-checked against
754    * the reserved {@code --jc-chrome-*} namespace (defense in depth; a {@link Theme} built by its builder can't
755    * carry one). This method is public so the FreeMarker {@code <@theme>} directive renders its inline block with
756    * the same code that serves {@code chrome.css}.
757    *
758    * <h4 class='section'>Example:</h4>
759    * <p class='bjava'>
760    *    Theme <jv>theme</jv> = Theme.<jsm>create</jsm>(<js>"corporate"</js>)
761    *       .token(<js>"--jc-accent"</js>, <js>"#b45309"</js>)
762    *       .alias(<js>"--jc-tab-bar-bg"</js>, <js>"var(--jc-card-bg)"</js>)
763    *       .build();
764    *    String <jv>css</jv> = ConsoleChromeMixin.<jsm>overrideBlock</jsm>(<jv>theme</jv>);
765    *    <jc>// html:root{--jc-accent:#b45309;--jc-tab-bar-bg:var(--jc-card-bg);}</jc>
766    * </p>
767    *
768    * @param theme The theme.  Must not be <jk>null</jk>.
769    * @return The override block, or an empty string if the theme declares nothing.
770    */
771   public static String overrideBlock(Theme theme) {
772      if (theme.getTokens().isEmpty() && theme.getAliases().isEmpty())
773         return "";
774      var sb = new StringBuilder("html:root{");
775      for (var e : theme.getTokens().entrySet()) {
776         Theme.rejectReservedChromeDeclaration(e.getKey(), "theme '" + theme.getName() + "' leaf token");
777         sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
778      }
779      for (var e : theme.getAliases().entrySet()) {
780         Theme.rejectReservedChromeDeclaration(e.getKey(), "theme '" + theme.getName() + "' alias");
781         sb.append(e.getKey()).append(':').append(e.getValue()).append(';');
782      }
783      return sb.append('}').toString();
784   }
785
786   /**
787    * The two head insertion points for a colour-scheme-aware page.
788    *
789    * <p>
790    * They are separate because they land in different places: {@link #htmlAttributes()} goes inside the
791    * {@code <html>} start tag, and {@link #head()} goes immediately after {@code <head>}, ahead of every stylesheet.
792    *
793    * @param htmlAttributes The attributes for the {@code <html>} start tag, space-separated with no leading space,
794    *    or an empty string when the page is neither pinned nor toggleable.
795    * @param head The pre-paint script element followed by the dark-layer stylesheet link, newline-terminated.
796    */
797   public record SchemeHead(String htmlAttributes, String head) {}
798
799   /**
800    * Returns the colour-scheme head pieces for a page that does not render through the FreeMarker console directive.
801    *
802    * <p>
803    * A pinned page ({@code light} or {@code dark}) gets {@code data-jc-scheme} and {@code data-jc-scheme-pin} set to
804    * the pin, so it paints in that scheme even with scripts disabled. A toggleable page gets
805    * {@code data-jc-scheme-toggle}, which lets the pre-paint script honour the visitor's stored choice. The head
806    * piece is {@link #SCHEME_SCRIPT} (stamped with the request's CSP nonce when one is set) followed by a link to the
807    * shipped dark layer.
808    *
809    * <h4 class='section'>Example:</h4>
810    * <p class='bjava'>
811    *    SchemeHead <jv>h</jv> = ConsoleChromeMixin.<jsm>schemeHead</jsm>(<jv>req</jv>, <js>"auto"</js>, <jk>true</jk>);
812    *    <jk>var</jk> <jv>attrs</jv> = <jv>h</jv>.htmlAttributes().isEmpty() ? <js>""</js> : <js>" "</js> + <jv>h</jv>.htmlAttributes();
813    *    <jv>out</jv>.write(<js>"&lt;html lang=\"en\""</js> + <jv>attrs</jv> + <js>"&gt;&lt;head&gt;"</js> + <jv>h</jv>.head());
814    * </p>
815    *
816    * <p>
817    * The head piece carries only the scheme script and the dark layer.  It does not replace the page's own links to
818    * the chrome stylesheet and a theme palette, which the caller still emits.
819    *
820    * @param req The current request, supplying the context path and any CSP nonce.
821    * @param pin One of the {@link #SCHEMES}.
822    * @param toggle Whether the visitor may override the scheme with a stored choice.
823    * @return The head pieces.
824    * @throws IllegalArgumentException If {@code pin} is <jk>null</jk> or not one of the {@link #SCHEMES}.
825    */
826   public static SchemeHead schemeHead(RestRequest req, String pin, boolean toggle) {
827      var attrs = schemeHtmlAttributes(pin, toggle);
828      var nonce = req.getAttribute(RestRequest.CSP_NONCE_ATTR).as(String.class).orElse(null);
829      var head = schemeScriptElement(nonce) + "\n<link rel=\"stylesheet\" href=\"" + attrEscape(themeAssetUrl(req, "dark")) + "\">\n";
830      return new SchemeHead(attrs, head);
831   }
832
833   /**
834    * Returns the {@code <html>} start-tag attributes for a scheme pin and toggle flag.
835    *
836    * <p>
837    * The FreeMarker console directive and {@link #schemeHead(RestRequest, String, boolean)} share this so the two
838    * shells stamp identical attributes.
839    *
840    * @param pin One of the {@link #SCHEMES}.
841    * @param toggle Whether the visitor may override the scheme with a stored choice.
842    * @return The attributes, space-separated with no leading space, or an empty string.
843    * @throws IllegalArgumentException If {@code pin} is <jk>null</jk> or not one of the {@link #SCHEMES}.
844    */
845   public static String schemeHtmlAttributes(String pin, boolean toggle) {
846      if (pin == null || ! SCHEMES.contains(pin))
847         throw iaex("Unknown scheme '%s'.  Schemes: %s.", pin, String.join(", ", SCHEMES));
848      var sb = new StringBuilder();
849      if (! "auto".equals(pin))
850         sb.append("data-jc-scheme=\"").append(pin).append("\" data-jc-scheme-pin=\"").append(pin).append('"');
851      if (toggle)
852         sb.append(sb.isEmpty() ? "" : " ").append("data-jc-scheme-toggle");
853      return sb.toString();
854   }
855
856   /**
857    * Returns the {@code <html>} start-tag attributes that switch on the theme selector.
858    *
859    * <p>
860    * {@code data-jc-theme-selector} turns the header control and the stored-pick lookup on; {@code data-jc-themes}
861    * is the space-separated allow-list of {@link #BUILTIN_THEME_NAMES} a stored pick is validated against.
862    *
863    * @return The attributes, space-separated with no leading space.
864    */
865   public static String themeSelectorHtmlAttributes() {
866      return "data-jc-theme-selector data-jc-themes=\"" + String.join(" ", BUILTIN_THEME_NAMES) + "\"";
867   }
868
869   /**
870    * Returns the {@link #SCHEME_SCRIPT} element, carrying {@code nonce} as an attribute when it is not <jk>null</jk>.
871    *
872    * @param nonce The request's CSP nonce, or <jk>null</jk>.
873    * @return The {@code <script>} element, with no trailing newline.
874    */
875   public static String schemeScriptElement(String nonce) {
876      return "<script" + nonceAttr(nonce) + ">" + SCHEME_SCRIPT + "</script>";
877   }
878
879   /**
880    * Returns {@code  nonce="…"} (with a leading space, attribute-escaped) or an empty string for <jk>null</jk>.
881    *
882    * @param nonce The request's CSP nonce, or <jk>null</jk>.
883    * @return The attribute text.
884    */
885   public static String nonceAttr(String nonce) {
886      return nonce == null ? "" : " nonce=\"" + attrEscape(nonce) + "\"";
887   }
888
889   /**
890    * Renders the dark-scheme override rule for app-declared dark tokens.
891    *
892    * <p>
893    * The rule is {@code @media not print{html:root[data-jc-scheme="dark"]{…}}}, so it wins over the light override
894    * block only while the page is dark and never reaches print. Leaves come first, then aliases, each in declaration
895    * order. A leaf must be a literal: a dark leaf that is itself a {@code var()} reference is rejected, because it
896    * would resolve against the light palette. A live link belongs in an alias. Names and values get the same checks
897    * as {@link Theme.Builder}: the name shape, the reserved {@code --jc-chrome-*} namespace, the value grammar, and
898    * one channel per name.
899    *
900    * <h4 class='section'>Example:</h4>
901    * <p class='bjava'>
902    *    String <jv>css</jv> = ConsoleChromeMixin.<jsm>schemeOverrideBlock</jsm>(
903    *       Map.<jsm>of</jsm>(<js>"--jc-link"</js>, <js>"#6cb4ff"</js>), Map.<jsm>of</jsm>(<js>"--jc-focus"</js>, <js>"var(--jc-accent)"</js>));
904    *    <jc>// @media not print{html:root[data-jc-scheme="dark"]{--jc-link:#6cb4ff;--jc-focus:var(--jc-accent);}}</jc>
905    * </p>
906    *
907    * @param tokens The dark leaf tokens by name.  Must not be <jk>null</jk>.
908    * @param aliases The dark aliases by name, each a {@code var(--jc-name)} reference.  Must not be <jk>null</jk>.
909    * @return The rule, or an empty string if both maps are empty.
910    * @throws IllegalArgumentException If a name or value fails validation.
911    */
912   public static String schemeOverrideBlock(Map<String,String> tokens, Map<String,String> aliases) {
913      if (tokens.isEmpty() && aliases.isEmpty())
914         return "";
915      var b = Theme.create("dark");
916      for (var e : tokens.entrySet()) {
917         if (CssValueGrammar.normalize(e.getValue()).toLowerCase(Locale.ROOT).contains("var("))
918            throw iaex("Dark token '%s' is '%s', but dark values must be literals.  Declare a live reference as an alias.", e.getKey(), e.getValue());
919         b.token(e.getKey(), e.getValue());
920      }
921      for (var e : aliases.entrySet())
922         b.alias(e.getKey(), e.getValue());
923      var t = b.build();
924      var sb = new StringBuilder("@media not print{html:root[data-jc-scheme=\"dark\"]{");
925      for (var e : t.getTokens().entrySet())
926         sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
927      for (var e : t.getAliases().entrySet())
928         sb.append(e.getKey()).append(':').append(e.getValue()).append(';');
929      return sb.append("}}").toString();
930   }
931
932   /** Escapes text for a double-quoted HTML attribute value. */
933   private static String attrEscape(String s) {
934      return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
935   }
936
937   /** Returns the CSP {@code 'sha256-…'} source expression for {@code text}'s UTF-8 bytes. */
938   private static String sha256Source(String text) {
939      try {
940         var digest = java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
941         return "'sha256-" + Base64.getEncoder().encodeToString(digest) + "'";
942      } catch (java.security.NoSuchAlgorithmException e) {  // HTT: every Java platform must provide SHA-256.
943         throw new IllegalStateException(e);
944      }
945   }
946
947   /**
948    * Renders {@link Theme#OPEN}'s {@code html:root{}} block with the framework-authored role-token alias
949    * derivations ({@link #OPEN_ROLE_ALIASES}) appended inside the same block, immediately after the leaf tokens.
950    * The aliases are appended as trusted framework literal text (not routed through {@code CssValueEscaper},
951    * which is for consumer-supplied values); folding them into {@code Theme.OPEN}'s block keeps the served
952    * response at exactly one {@code html:root{}} block for the default theme while still placing every derived
953    * default before any active-theme override block. See {@link #overrideBlock(Theme)} for why the selector carries
954    * the {@code html} type prefix.
955    */
956   private static String openRootBlock() {
957      var sb = new StringBuilder();
958      sb.append("html:root{");
959      for (var e : Theme.OPEN.getTokens().entrySet())
960         sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
961      sb.append(OPEN_ROLE_ALIASES);
962      sb.append('}');
963      return sb.toString();
964   }
965
966   /** Returns the shipped static chrome.css text, reading (and caching, process-wide - the static file never varies) it from the classpath on first call. */
967   private static String staticCss() throws IOException {
968      var s = staticCss;
969      if (s == null) {
970         synchronized (ConsoleChromeMixin.class) {
971            s = staticCss;
972            if (s == null) {  // HTT: the "already set" branch is only reachable under a lock-acquisition race - unhittable single-threaded.
973               try (var in = ConsoleChromeMixin.class.getResourceAsStream(CHROME_CSS_RESOURCE)) {
974                  if (in == null)
975                     throw new IOException("Classpath resource not found: " + CHROME_CSS_RESOURCE);
976                  s = IoUtils.read(in);
977               }
978               staticCss = s;
979            }
980         }
981      }
982      return s;
983   }
984
985   /**
986    * Builder for {@link ConsoleChromeMixin}.
987    */
988   public static class Builder {
989      boolean cacheAssets = true;
990      Theme theme;
991
992      /**
993       * Whether to cache the assembled response body after the first request (default <jk>true</jk>).
994       *
995       * @param value The new value.
996       * @return This object.
997       */
998      public Builder cacheAssets(boolean value) {
999         this.cacheAssets = value;
1000         return this;
1001      }
1002
1003      /**
1004       * Selects one of the shipped stock palettes by name (the same names FTL {@code <@theme name="…">} accepts).
1005       *
1006       * <p>
1007       * A custom palette is authored in FTL with {@code <@theme>}/{@code <@token>}.
1008       *
1009       * @param stockName One of the {@link ConsoleChromeMixin#BUILTIN_THEME_NAMES}
1010       *    ({@code open}, {@code light-red}, {@code light-brown}, {@code red}, {@code gray}).
1011       * @return This object.
1012       * @throws IllegalArgumentException If {@code stockName} is not a built-in stock-theme name.
1013       */
1014      public Builder theme(String stockName) {
1015         this.theme = stockTheme(stockName);
1016         return this;
1017      }
1018
1019      /**
1020       * Builds the mixin.
1021       *
1022       * @return A new {@link ConsoleChromeMixin}.
1023       */
1024      public ConsoleChromeMixin build() {
1025         return new ConsoleChromeMixin(this);
1026      }
1027   }
1028}