@ruckc/truss-code 1.46.0 → 1.48.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/README.md CHANGED
@@ -27,6 +27,10 @@ npm install monaco-editor # only if you use the editors
27
27
 
28
28
  `CodeBlock` colours with the small built-in highlighter and only uses Monaco's tokenizers when something else (an editor on the page) has already loaded Monaco, so a read-only block never downloads it. Set `highlighter="monaco"` on a block, or `configureCodeEditor({ highlighter: 'monaco' })` for every read-only view, to always load Monaco for colouring, or `'lite'` to never use it. `copy` adds a Copy button; to render Markdown fences with it, pass `{#snippet code({ lang, text })}<CodeBlock code={text} language={lang} copy />{/snippet}` to `@ruckc/truss-markdown`'s `Markdown`. That package does not depend on this one.
29
29
 
30
+ ## Strict CSP
31
+
32
+ Under `style-src 'self' 'nonce-…'` (no `'unsafe-inline'`) the editors work once a nonce is configured: `setCspNonce(nonce)` from `@ruckc/truss-ui` in the root layout, `configureCsp({ nonce })`, or `<meta property="csp-nonce" nonce="…">`. Monaco 0.57 has no nonce support of its own, so with a nonce present the package wraps `document.createElement('style')` (the element gets the nonce), `setAttribute('style', …)` (becomes a CSSOM assignment) and `innerHTML` / `insertAdjacentHTML` strings that contain `style="…"` (parsed in a policy-free document, with each style attribute moved to the CSSOM). Without a nonce nothing is wrapped. Monaco's own CSS is a normal stylesheet in a production build; in Vite dev, Vite reads its nonce from the same meta tag (or `html.cspNonce`). The Truss documentation has a Content Security Policy page with the details.
33
+
30
34
  ## License
31
35
 
32
36
  MIT
@@ -1,4 +1,10 @@
1
1
  <script lang="ts">
2
+ import { csstext } from './cssvars.js';
3
+ import SsrStyle from './SsrStyle.svelte';
4
+ import { prepareMonacoCsp } from './monaco-csp.js';
5
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
6
+ prepareMonacoCsp();
7
+ const uid = $props.id();
2
8
  import { onMount, onDestroy } from 'svelte';
3
9
  import { Button, Tooltip } from '@ruckc/truss-ui';
4
10
  import type { ClassValue } from 'svelte/elements';
@@ -137,8 +143,9 @@
137
143
  </script>
138
144
 
139
145
  {#snippet block()}
146
+ <SsrStyle {uid} rules={{ '': style }} />
140
147
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
141
- <pre {...rest} bind:this={el} role="region" class={['cb', klass]} class:wrap class:nums={lineNumbers} {style} {onscroll} tabindex="0" aria-label={label}><code>{#each lines as segs, i (i)}<span class="ln">{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="tx">{#each segs as s}<span class={s.role ? `s-${s.role}` : undefined}>{s.text}</span>{/each}{'\n'}</span></span>{/each}</code></pre>
148
+ <pre {...rest} bind:this={el} data-sv={uid} role="region" class={['cb', klass]} class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} {onscroll} tabindex="0" aria-label={label}><code>{#each lines as segs, i (i)}<span class="ln">{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="tx">{#each segs as s}<span class={s.role ? `s-${s.role}` : undefined}>{s.text}</span>{/each}{'\n'}</span></span>{/each}</code></pre>
142
149
  {/snippet}
143
150
 
144
151
  {#if copy}
@@ -5,6 +5,11 @@
5
5
  </script>
6
6
 
7
7
  <script lang="ts">
8
+ import { csstext } from './cssvars.js';
9
+ import SsrStyle from './SsrStyle.svelte';
10
+ import { prepareMonacoCsp } from './monaco-csp.js';
11
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
12
+ prepareMonacoCsp();
8
13
  import { onMount } from 'svelte';
9
14
  import type { HTMLAttributes } from 'svelte/elements';
10
15
  import { Skeleton, matches } from '@ruckc/truss-ui';
@@ -281,7 +286,8 @@
281
286
  });
282
287
  </script>
283
288
 
284
- <div {...rest} class="ce {klass}" style:height={css} {style} data-ready={ready} role="group" aria-label={label} aria-describedby="ce-hint-{id}">
289
+ <SsrStyle uid={id} rules={{ '': `${css ? `height:${css};` : ''}${style ?? ''}` }} />
290
+ <div {...rest} data-sv={id} class="ce {klass}" {@attach csstext(() => `${css ? `height:${css};` : ''}${style ?? ''}`)} data-ready={ready} role="group" aria-label={label} aria-describedby="ce-hint-{id}">
285
291
  <div class="mount" bind:this={host}></div>
286
292
  {#if !ready}
287
293
  <div class="ph">
@@ -5,6 +5,11 @@
5
5
  </script>
6
6
 
7
7
  <script lang="ts">
8
+ import { cssvars } from './cssvars.js';
9
+ import SsrStyle from './SsrStyle.svelte';
10
+ import { prepareMonacoCsp } from './monaco-csp.js';
11
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
12
+ prepareMonacoCsp();
8
13
  import { onMount } from 'svelte';
9
14
  import { Skeleton } from '@ruckc/truss-ui';
10
15
  import type * as Monaco from 'monaco-editor';
@@ -129,7 +134,8 @@
129
134
  });
130
135
  </script>
131
136
 
132
- <div class="de" style:height={css} data-ready={ready} role="group" aria-label={label}>
137
+ <SsrStyle uid={id} rules={{ '': `height:${css}` }} />
138
+ <div class="de" data-sv={id} {@attach cssvars(() => ({ 'height': css }))} data-ready={ready} role="group" aria-label={label}>
133
139
  <div class="mount" bind:this={host}></div>
134
140
  {#if !ready}
135
141
  <div class="ph">
@@ -1,4 +1,7 @@
1
1
  <script lang="ts">
2
+ import { cssvars, csstext } from './cssvars.js';
3
+ import SsrStyle from './SsrStyle.svelte';
4
+ const uid = $props.id();
2
5
  import { onMount, tick, untrack, type Snippet } from 'svelte';
3
6
  import { Button, SegmentedControl, startDrag } from '@ruckc/truss-ui';
4
7
  import {
@@ -588,8 +591,18 @@
588
591
  const sr = (i: number) => (moveAt[i] >= 0 ? (lines[i].type === 'add' ? 'moved here' : 'moved away') : SR[lines[i].type]);
589
592
  </script>
590
593
 
594
+ <SsrStyle
595
+ {uid}
596
+ rules={{
597
+ '': [style, userStyle].join(';'),
598
+ ' .scroll': maxH ? `max-height:${maxH}` : '',
599
+ ' .tbl': `--dv-no:${figures + 1}ch${wrap ? '' : `;--dv-code:calc(${longest + 1}ch + 2 * var(--tr-space-2))`}`,
600
+ ...(virt ? { ' tbody > tr.pad:first-child > td': `height:${offs[win[0]]}px`, ' tbody > tr.pad:last-child > td': `height:${offs[rows.length] - offs[win[1]]}px` } : {}),
601
+ ...(showOv ? Object.fromEntries([...runs.map((r, k) => [` .ov > .mk:nth-child(${k + 1})`, `top:${r.from}%;height:${r.to - r.from}%`]), [' .ov > .thumb', `top:${thumb[0]}%;height:${thumb[1]}%`]]) : {})
602
+ }}
603
+ />
591
604
  <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
592
- <div bind:this={root} class={['dv', cls]} {...rest} style={[style, userStyle].join(';')} role="group" aria-label={name ? `${label}: ${name}` : label} tabindex="0" onkeydown={onkey}>
605
+ <div bind:this={root} data-sv={uid} class={['dv', cls]} {...rest} {@attach csstext(() => [style, userStyle].join(';'))} role="group" aria-label={name ? `${label}: ${name}` : label} tabindex="0" onkeydown={onkey}>
593
606
  {#if toolbar}
594
607
  <div class="bar">
595
608
  <span class="sum" data-testid="summary">
@@ -629,19 +642,19 @@
629
642
  <p class="ph" role="status">No differences.</p>
630
643
  {:else}
631
644
  <div class="view">
632
- <div class="scroll" class:virt class:nowrap={!wrap} bind:this={scroller} bind:clientHeight={vh} {onscroll} style:max-height={maxH} data-virtual={virt}>
633
- <table class="tbl" data-layout={layout} style:--dv-no="{figures + 1}ch" style:--dv-code={wrap ? undefined : `calc(${longest + 1}ch + 2 * var(--tr-space-2))`} aria-label={name ? `Changes in ${name}` : 'Changes'} aria-rowcount={rows.length}>
645
+ <div class="scroll" class:virt class:nowrap={!wrap} bind:this={scroller} bind:clientHeight={vh} {onscroll} {@attach cssvars(() => ({ 'max-height': maxH }))} data-virtual={virt}>
646
+ <table class="tbl" data-layout={layout} {@attach cssvars(() => ({ '--dv-no': `${figures + 1}ch` }))} {@attach cssvars(() => ({ '--dv-code': wrap ? undefined : `calc(${longest + 1}ch + 2 * var(--tr-space-2))` }))} aria-label={name ? `Changes in ${name}` : 'Changes'} aria-rowcount={rows.length}>
634
647
  {#if layout === 'split'}
635
648
  <colgroup>
636
649
  {#each ['old', 'new'] as s (s)}<col class="c-no" /><col class="c-sym" /><col class="c-code" />{/each}
637
650
  </colgroup>
638
651
  {/if}
639
652
  <tbody>
640
- {#if virt}<tr class="pad" aria-hidden="true"><td colspan={cols} style:height="{offs[win[0]]}px"></td></tr>{/if}
653
+ {#if virt}<tr class="pad" aria-hidden="true"><td colspan={cols} {@attach cssvars(() => ({ 'height': `${offs[win[0]]}px` }))}></td></tr>{/if}
641
654
  {#each shown as e, n (e.key)}
642
655
  {@render row(e, win[0] + n)}
643
656
  {/each}
644
- {#if virt}<tr class="pad" aria-hidden="true"><td colspan={cols} style:height="{offs[rows.length] - offs[win[1]]}px"></td></tr>{/if}
657
+ {#if virt}<tr class="pad" aria-hidden="true"><td colspan={cols} {@attach cssvars(() => ({ 'height': `${offs[rows.length] - offs[win[1]]}px` }))}></td></tr>{/if}
645
658
  </tbody>
646
659
  </table>
647
660
  </div>
@@ -656,8 +669,8 @@
656
669
  data-testid="overview"
657
670
  onpointerdown={ovDown}
658
671
  >
659
- {#each runs as r}<span class="mk {r.lane}" style:top="{r.from}%" style:height="{r.to - r.from}%"></span>{/each}
660
- <span class="thumb" style:top="{thumb[0]}%" style:height="{thumb[1]}%"></span>
672
+ {#each runs as r}<span class="mk {r.lane}" {@attach cssvars(() => ({ 'top': `${r.from}%` }))} {@attach cssvars(() => ({ 'height': `${r.to - r.from}%` }))}></span>{/each}
673
+ <span class="thumb" {@attach cssvars(() => ({ 'top': `${thumb[0]}%` }))} {@attach cssvars(() => ({ 'height': `${thumb[1]}%` }))}></span>
661
674
  </div>
662
675
  {/if}
663
676
  </div>
@@ -0,0 +1,9 @@
1
+ <script lang="ts">
2
+ import { cspNonce } from './csp.js';
3
+
4
+ /** @internal A generated `<style>` element that carries the CSP nonce (see `configureCsp`). */
5
+ let { css }: { css: string } = $props();
6
+ const nonce = cspNonce();
7
+ </script>
8
+
9
+ <svelte:element this={'style'} {nonce}>{css}</svelte:element>
@@ -0,0 +1,6 @@
1
+ type $$ComponentProps = {
2
+ css: string;
3
+ };
4
+ declare const GeneratedStyle: import("svelte").Component<$$ComponentProps, {}, "">;
5
+ type GeneratedStyle = ReturnType<typeof GeneratedStyle>;
6
+ export default GeneratedStyle;
@@ -1,4 +1,9 @@
1
1
  <script lang="ts">
2
+ import { csstext } from './cssvars.js';
3
+ import SsrStyle from './SsrStyle.svelte';
4
+ import { prepareMonacoCsp } from './monaco-csp.js';
5
+ // with a CSP nonce configured, Monaco's own styles get it too (a no-op without one)
6
+ prepareMonacoCsp();
2
7
  import { onMount, tick, untrack } from 'svelte';
3
8
  import type { ClassValue } from 'svelte/elements';
4
9
  import { Button, SegmentedControl, Textarea } from '@ruckc/truss-ui';
@@ -357,7 +362,8 @@
357
362
  </script>
358
363
 
359
364
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
360
- <div {...rest} bind:this={root} class={['mv', klass]} {style} role="group" aria-label={name ? `${label}: ${name}` : label} data-narrow={narrow} data-height={sizing} data-binary={binary || undefined} data-deleted={deletedSide} aria-busy={loading || undefined} onkeydown={onkey} aria-describedby="{uid}-help">
365
+ <SsrStyle {uid} rules={{ '': style }} />
366
+ <div {...rest} bind:this={root} data-sv={uid} class={['mv', klass]} {@attach csstext(() => style)} role="group" aria-label={name ? `${label}: ${name}` : label} data-narrow={narrow} data-height={sizing} data-binary={binary || undefined} data-deleted={deletedSide} aria-busy={loading || undefined} onkeydown={onkey} aria-describedby="{uid}-help">
361
367
  <div class="bar">
362
368
  <span class="sum" role="status" data-testid="status" data-done={whole ? !!pick : deleted || (total > 0 && out.resolved === total)}>{status}</span>
363
369
  <span class="grow"></span>
@@ -1,4 +1,7 @@
1
1
  <script lang="ts">
2
+ import { csstext } from './cssvars.js';
3
+ import SsrStyle from './SsrStyle.svelte';
4
+ const uid = $props.id();
2
5
  import type { HTMLAttributes } from 'svelte/elements';
3
6
  import { markLines, type MarkKind } from './patch-text.js';
4
7
 
@@ -26,8 +29,9 @@
26
29
  const style = $derived(maxHeight != null ? `max-height:${typeof maxHeight === 'number' ? maxHeight + 'px' : maxHeight}` : undefined);
27
30
  </script>
28
31
 
32
+ <SsrStyle {uid} rules={{ '': style ?? '' }} />
29
33
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
30
- <pre {...rest} role="region" class="pt" class:wrap class:nums={lineNumbers} {style} tabindex="0" aria-label={label}><code>{#each lines as l, i (i)}<span class={"ln " + l.kind} data-kind={l.kind}>{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="sym">{#if l.mark}<span aria-hidden="true">{l.mark.sym}</span><span class="vh">{l.mark.sr + ": "}</span>{/if}</span><span class="tx">{l.body + '\n'}</span></span>{/each}</code></pre>
34
+ <pre {...rest} data-sv={uid} role="region" class="pt" class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} tabindex="0" aria-label={label}><code>{#each lines as l, i (i)}<span class={"ln " + l.kind} data-kind={l.kind}>{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="sym">{#if l.mark}<span aria-hidden="true">{l.mark.sym}</span><span class="vh">{l.mark.sr + ": "}</span>{/if}</span><span class="tx">{l.body + '\n'}</span></span>{/each}</code></pre>
31
35
 
32
36
  <style>
33
37
  .pt {
@@ -0,0 +1,15 @@
1
+ <script lang="ts">
2
+ import { untrack } from 'svelte';
3
+ import GeneratedStyle from './GeneratedStyle.svelte';
4
+
5
+ /**
6
+ * @internal The first-paint declarations of an element and its descendants as one nonced `<style>` rule per key, `[data-sv=uid]<key>{…}`
7
+ * (key `''` is the element itself), so a server-rendered graph lays out before JavaScript runs and without a `style=` attribute (blocked by a CSP
8
+ * without 'unsafe-inline'). The element carries `data-sv={uid}`; the CSSOM values set after mount override these rules.
9
+ * A copy of the core's `SsrStyle` for the declaration-string case (the packages do not depend on the core).
10
+ */
11
+ let { uid, rules }: { uid: string; rules: Record<string, string> } = $props();
12
+ const css = untrack(() => Object.entries(rules).map(([sel, decl]) => `[data-sv="${uid}"]${sel}{${decl}}`).join(''));
13
+ </script>
14
+
15
+ <GeneratedStyle {css} />
@@ -0,0 +1,7 @@
1
+ type $$ComponentProps = {
2
+ uid: string;
3
+ rules: Record<string, string>;
4
+ };
5
+ declare const SsrStyle: import("svelte").Component<$$ComponentProps, {}, "">;
6
+ type SsrStyle = ReturnType<typeof SsrStyle>;
7
+ export default SsrStyle;
package/dist/csp.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** @internal The nonce without the component context (`configureCsp` or the meta tag): usable outside component initialisation. */
2
+ export declare function ambientNonce(): string | undefined;
3
+ export declare function cspNonce(): string | undefined;
package/dist/csp.js ADDED
@@ -0,0 +1,16 @@
1
+ import { getContext } from 'svelte';
2
+ /**
3
+ * @internal The CSP nonce for a generated `<style>` element, as set by `@ruckc/truss-ui` (`setCspNonce` in the root layout, or `configureCsp`),
4
+ * else `<meta property="csp-nonce" nonce="…">` in the browser. Shares its state with the core through `Symbol.for` / `globalThis`.
5
+ */
6
+ const KEY = Symbol.for('@ruckc/truss-ui:csp-nonce');
7
+ const STATE = Symbol.for('@ruckc/truss-ui:csp');
8
+ /** @internal The nonce without the component context (`configureCsp` or the meta tag): usable outside component initialisation. */
9
+ export function ambientNonce() {
10
+ const state = globalThis[STATE];
11
+ const m = typeof document === 'undefined' ? null : document.querySelector('meta[property="csp-nonce"], meta[name="csp-nonce"]');
12
+ return state?.nonce || m?.nonce || m?.content || undefined;
13
+ }
14
+ export function cspNonce() {
15
+ return getContext(KEY) || ambientNonce();
16
+ }
@@ -0,0 +1,12 @@
1
+ import type { Attachment } from 'svelte/attachments';
2
+ type Value = string | number | null | undefined;
3
+ /**
4
+ * @internal Sets CSS properties (custom properties such as `--size`, or plain ones like `width`) on an element through the CSSOM (`el.style.setProperty`),
5
+ * which a Content-Security-Policy without `style-src 'unsafe-inline'` allows. Unlike `style=` / `style:` it renders nothing in server-rendered markup,
6
+ * so the component's scoped CSS must have a sensible fallback (`var(--x, default)`) for the first paint, or a `SsrStyle` rule must provide it. Runs on the
7
+ * client after mount and re-runs when what `get` reads changes; `null` and `undefined` remove the property.
8
+ */
9
+ export declare function cssvars(get: () => Record<string, Value>): Attachment<HTMLElement | SVGElement>;
10
+ /** @internal Like `cssvars` but for a whole declaration list (`'left: 4px; top: 2px'`), applied with `el.style.cssText` (CSSOM, CSP-safe). */
11
+ export declare function csstext(get: () => string | undefined): Attachment<HTMLElement | SVGElement>;
12
+ export {};
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @internal Sets CSS properties (custom properties such as `--size`, or plain ones like `width`) on an element through the CSSOM (`el.style.setProperty`),
3
+ * which a Content-Security-Policy without `style-src 'unsafe-inline'` allows. Unlike `style=` / `style:` it renders nothing in server-rendered markup,
4
+ * so the component's scoped CSS must have a sensible fallback (`var(--x, default)`) for the first paint, or a `SsrStyle` rule must provide it. Runs on the
5
+ * client after mount and re-runs when what `get` reads changes; `null` and `undefined` remove the property.
6
+ */
7
+ export function cssvars(get) {
8
+ return (el) => {
9
+ const now = get();
10
+ const set = [];
11
+ for (const k in now) {
12
+ const v = now[k];
13
+ if (v == null)
14
+ continue;
15
+ el.style.setProperty(k, String(v));
16
+ set.push(k);
17
+ }
18
+ return () => {
19
+ for (const k of set)
20
+ el.style.removeProperty(k);
21
+ };
22
+ };
23
+ }
24
+ /** @internal Like `cssvars` but for a whole declaration list (`'left: 4px; top: 2px'`), applied with `el.style.cssText` (CSSOM, CSP-safe). */
25
+ export function csstext(get) {
26
+ return (el) => {
27
+ const css = get();
28
+ // an empty value leaves the element without a style attribute
29
+ if (css)
30
+ el.style.cssText = css;
31
+ return () => {
32
+ if (css)
33
+ el.style.cssText = '';
34
+ };
35
+ };
36
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Strict-CSP support for Monaco (`style-src 'self' 'nonce-…'`, no `'unsafe-inline'`). Monaco 0.57 knows no nonce: it creates `<style>`
3
+ * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
+ * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
+ *
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
+ * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
+ * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
12
+ */
13
+ /** Wraps Monaco's style creation so that it works under a nonce-only `style-src`. Idempotent; a later call replaces the nonce. Returns `uninstallMonacoCsp`. */
14
+ export declare function installMonacoCsp(nonce: string | undefined): () => void;
15
+ /** Restores the browser's own functions. Meant for tests; Monaco is global, so the editors leave the wrappers installed. */
16
+ export declare function uninstallMonacoCsp(): void;
17
+ /** Whether the wrappers are installed. */
18
+ export declare const monacoCspInstalled: () => boolean;
19
+ /** Called while a component initialises: installs the wrappers when the page has a CSP nonce (`setCspNonce`, `configureCsp` or the `csp-nonce` meta tag). A no-op without one. */
20
+ export declare function prepareMonacoCsp(): void;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Strict-CSP support for Monaco (`style-src 'self' 'nonce-…'`, no `'unsafe-inline'`). Monaco 0.57 knows no nonce: it creates `<style>`
3
+ * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
+ * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
+ *
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
+ * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
+ * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
12
+ */
13
+ import { cspNonce } from './csp.js';
14
+ let current;
15
+ const HAS_STYLE = /\sstyle\s*=/i;
16
+ /** Parses `html` in a policy-free document and replaces every `style="…"` attribute with the equivalent CSSOM declarations. */
17
+ function toFragment(html) {
18
+ // DOMParser documents have no browsing context, so no CSP applies to the attributes while parsing (a <template> in the page is not exempt)
19
+ const body = new DOMParser().parseFromString(`<!doctype html><body>${html}`, 'text/html').body;
20
+ for (const el of body.querySelectorAll('[style]')) {
21
+ const css = el.getAttribute('style') ?? '';
22
+ el.removeAttribute('style');
23
+ el.style.cssText = css;
24
+ }
25
+ const frag = document.createDocumentFragment();
26
+ frag.append(...body.childNodes);
27
+ return frag;
28
+ }
29
+ /** Wraps Monaco's style creation so that it works under a nonce-only `style-src`. Idempotent; a later call replaces the nonce. Returns `uninstallMonacoCsp`. */
30
+ export function installMonacoCsp(nonce) {
31
+ if (!nonce || typeof document === 'undefined')
32
+ return uninstallMonacoCsp;
33
+ if (current) {
34
+ current.nonce = nonce;
35
+ return uninstallMonacoCsp;
36
+ }
37
+ const undo = {
38
+ setAttribute: Element.prototype.setAttribute,
39
+ innerHTML: Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML'),
40
+ insertAdjacentHTML: Element.prototype.insertAdjacentHTML
41
+ };
42
+ const state = (current = { nonce, undo });
43
+ const rawSet = undo.innerHTML.set;
44
+ const create = document.createElement;
45
+ document.createElement = function (...args) {
46
+ const el = create.apply(this, args);
47
+ if (String(args[0]).toLowerCase() === 'style')
48
+ el.nonce = state.nonce;
49
+ return el;
50
+ };
51
+ Element.prototype.setAttribute = function (name, value) {
52
+ if (String(name).toLowerCase() === 'style' && 'style' in this)
53
+ this.style.cssText = String(value);
54
+ else
55
+ undo.setAttribute.call(this, name, value);
56
+ };
57
+ Object.defineProperty(Element.prototype, 'innerHTML', {
58
+ ...undo.innerHTML,
59
+ set(v) {
60
+ const html = String(v);
61
+ if (!HAS_STYLE.test(html))
62
+ rawSet.call(this, v);
63
+ else
64
+ (this instanceof HTMLTemplateElement ? this.content : this).replaceChildren(toFragment(html));
65
+ }
66
+ });
67
+ Element.prototype.insertAdjacentHTML = function (where, v) {
68
+ const html = String(v);
69
+ if (!HAS_STYLE.test(html))
70
+ return undo.insertAdjacentHTML.call(this, where, v);
71
+ const frag = toFragment(html);
72
+ switch (String(where).toLowerCase()) {
73
+ case 'beforebegin':
74
+ this.before(frag);
75
+ break;
76
+ case 'afterbegin':
77
+ this.prepend(frag);
78
+ break;
79
+ case 'beforeend':
80
+ this.append(frag);
81
+ break;
82
+ default: this.after(frag);
83
+ }
84
+ };
85
+ return uninstallMonacoCsp;
86
+ }
87
+ /** Restores the browser's own functions. Meant for tests; Monaco is global, so the editors leave the wrappers installed. */
88
+ export function uninstallMonacoCsp() {
89
+ if (!current)
90
+ return;
91
+ const { undo } = current;
92
+ current = undefined;
93
+ delete document.createElement;
94
+ Element.prototype.setAttribute = undo.setAttribute;
95
+ Object.defineProperty(Element.prototype, 'innerHTML', undo.innerHTML);
96
+ Element.prototype.insertAdjacentHTML = undo.insertAdjacentHTML;
97
+ }
98
+ /** Whether the wrappers are installed. */
99
+ export const monacoCspInstalled = () => !!current;
100
+ /** Called while a component initialises: installs the wrappers when the page has a CSP nonce (`setCspNonce`, `configureCsp` or the `csp-nonce` meta tag). A no-op without one. */
101
+ export function prepareMonacoCsp() {
102
+ installMonacoCsp(cspNonce());
103
+ }
package/dist/monaco.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { ambientNonce } from './csp.js';
2
+ import { installMonacoCsp } from './monaco-csp.js';
1
3
  import { readTheme, monacoTheme } from './theme.js';
2
4
  let loader;
3
5
  let pending;
@@ -41,6 +43,7 @@ export function loadMonaco() {
41
43
  if (!loader)
42
44
  return Promise.reject(new Error('@ruckc/truss-code: Monaco is not configured. Call setMonacoLoader(() => import("monaco-editor")) or useMonaco() from "@ruckc/truss-code/monaco".'));
43
45
  if (!pending) {
46
+ installMonacoCsp(ambientNonce()); // under a strict style-src Monaco's styles need the nonce (no-op without one)
44
47
  const mine = (pending = loader());
45
48
  mine.then(() => {
46
49
  if (pending !== mine)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-code",
3
- "version": "1.46.0",
3
+ "version": "1.48.0",
4
4
  "description": "Read-only code blocks, diff and merge views, plus an optional Monaco code editor, styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",