@cossackframework/renderer 0.8.2 → 0.9.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
@@ -1,12 +1,13 @@
1
1
  # Cossack Renderer Package
2
2
 
3
- Cossack Renderer is a Lit-compatible rendering engine designed for **Light DOM** and **SSR**. It provides a familiar API for building components but focuses on returning HTML strings directly for SSR and managing DOM updates without Shadow DOM isolation.
3
+ Cossack Renderer is a Lit-compatible rendering engine for **Light DOM** and
4
+ **SSR**. It returns HTML strings for SSR and updates the DOM without Shadow DOM
5
+ isolation.
4
6
 
5
7
  ## Installation
6
8
 
7
- This package is included by projects created with `cossack create`, but can
8
- also be used standalone in any project that needs a lightweight rendering
9
- solution.
9
+ Projects created with `cossack create` include this package. You can also use
10
+ it on its own in another project.
10
11
 
11
12
  ```bash
12
13
  pnpm add @cossackframework/renderer
@@ -0,0 +1,88 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "guides": [
4
+ {
5
+ "id": "server-html",
6
+ "title": "Render escaped HTML on the server",
7
+ "summary": "Use the server entrypoint to turn an HTML template into a string.",
8
+ "imports": [
9
+ "@cossackframework/renderer/server"
10
+ ],
11
+ "markdown": "Import html and renderToString from the public server entrypoint. Interpolate text values into html templates. The renderer escapes text rather than interpreting it as markup.\n\nDo not concatenate untrusted text into HTML source or use unsafe raw-HTML helpers for it. Escaping text does not authorize a request or validate application URLs. Server rendering produces an HTML string. It does not attach browser event handlers or hydrate an application.",
12
+ "examples": [
13
+ {
14
+ "id": "escaped-text",
15
+ "language": "typescript",
16
+ "source": "import { html, renderToString } from '@cossackframework/renderer/server';\n\nconst name: string = '<script>alert(1)</script>';\nconst output: string = await renderToString(html`<p>Hello ${name}</p>`);\nif (output.includes('<script>')) throw new Error('Text became executable markup');\nif (!output.includes('&lt;script&gt;')) throw new Error('Text was not escaped');\n"
17
+ }
18
+ ]
19
+ },
20
+ {
21
+ "id": "conditional-templates",
22
+ "title": "Select template branches and optional attributes",
23
+ "summary": "Render conditional content without building HTML strings.",
24
+ "imports": [
25
+ "@cossackframework/renderer",
26
+ "@cossackframework/renderer/server"
27
+ ],
28
+ "markdown": "Use `when` to select a branch and `choose` to match a value with strict equality. Their callbacks run while the template expression is evaluated. Use `nothing` for an empty child value. `ifDefined(undefined)` omits an attribute; other values, including `null`, `false`, and `0`, are serialized as values. HTML escaping does not validate URL schemes or authorize a destination.",
29
+ "examples": [
30
+ {
31
+ "id": "choose-safe-branches",
32
+ "language": "typescript",
33
+ "source": "import { choose, ifDefined, nothing, when } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst status: string = 'ready';\nconst output = await renderToString(html`<main><a href=\"${ifDefined(undefined)}\">Home</a>${when(status !== 'hidden', () => html`<p>${choose(status, [['ready', () => 'Ready'], ['saving', () => 'Saving']], () => nothing)}</p>`, () => nothing)}</main>`);\nif (output !== '<main><a>Home</a><p>Ready</p></main>') throw new Error(`Unexpected conditional output: ${output}`);\n"
34
+ }
35
+ ]
36
+ },
37
+ {
38
+ "id": "keyed-lists",
39
+ "title": "Render lists with stable item keys",
40
+ "summary": "Use keyed repeat for lists whose DOM items should keep their identity.",
41
+ "imports": [
42
+ "@cossackframework/renderer",
43
+ "@cossackframework/renderer/server"
44
+ ],
45
+ "markdown": "`repeat(items, keyFn, templateFn)` gives the browser renderer a stable key for each item so it can retain matching DOM nodes when the list changes. Server rendering emits the initial ordered markup; it does not prove browser node reuse. Use `join` when you need a renderable separator between values. Plain arrays and `map` are enough when item identity does not matter.",
46
+ "examples": [
47
+ {
48
+ "id": "keyed-initial-markup",
49
+ "language": "typescript",
50
+ "source": "import { join, repeat } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst people = [{ id: 'ada', name: 'Ada' }, { id: 'lin', name: 'Lin' }];\nconst output = await renderToString(html`<ol>${repeat(people, person => person.id, person => html`<li data-id=\"${person.id}\">${person.name}</li>`)}</ol><p>${join(people, person => person.name, ', ')}</p>`);\nif (!output.includes('<li data-id=\"ada\">Ada</li><li data-id=\"lin\">Lin</li>')) throw new Error('Initial list order or values are wrong');\nif (!output.endsWith('<p>Ada, Lin</p>')) throw new Error('List separator is missing');\n"
51
+ }
52
+ ]
53
+ },
54
+ {
55
+ "id": "server-form-values",
56
+ "title": "Render current form values before hydration",
57
+ "summary": "Seed input, checkbox, and textarea values in server-rendered HTML.",
58
+ "imports": [
59
+ "@cossackframework/renderer",
60
+ "@cossackframework/renderer/server"
61
+ ],
62
+ "markdown": "Use `.value=${bind(state, path)}` and `.checked=${bind(state, path)}` to render the current field values. `live(value)` supplies the current value when the renderer reconciles an existing DOM property. On the server these helpers only produce initial markup; client rendering or hydration is required for browser write-back. A binding does not validate submitted data or authorize a server action.",
63
+ "examples": [
64
+ {
65
+ "id": "seed-native-controls",
66
+ "language": "typescript",
67
+ "source": "import { bind, live } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst form = { email: 'agent@example.test', active: true, note: '<draft>' };\nconst output = await renderToString(html`<form><input name=\"email\" .value=${bind(form, 'email')}><input name=\"active\" type=\"checkbox\" .checked=${bind(form, 'active')}><textarea name=\"note\" .value=${live(form.note)}></textarea></form>`);\nif (!output.includes('name=\"email\" value=\"agent@example.test\"')) throw new Error('Email value was not rendered');\nif (!output.includes('type=\"checkbox\" checked')) throw new Error('Checked state was not rendered');\nif (!output.includes('&lt;draft&gt;</textarea>')) throw new Error('Textarea text was not escaped');\n"
68
+ }
69
+ ]
70
+ },
71
+ {
72
+ "id": "safe-component-css",
73
+ "title": "Compose component CSS from reviewed values",
74
+ "summary": "Use css tagged templates for static styles and reserve unsafeCSS for trusted values.",
75
+ "imports": [
76
+ "@cossackframework/renderer"
77
+ ],
78
+ "markdown": "`css` accepts numeric interpolations and other `CSSResult` values. It rejects ordinary strings, so use static styles and typed numbers for normal composition. `unsafeCSS` marks a string as trusted CSS; it does not sanitize it. Never pass user input, request data, or other untrusted values to `unsafeCSS`.",
79
+ "examples": [
80
+ {
81
+ "id": "safe-style-composition",
82
+ "language": "typescript",
83
+ "source": "import { css, unsafeCSS } from '@cossackframework/renderer';\n\nconst gap = 8;\nconst surface = css`background-color: #fff;`;\nconst card = css`article { padding: ${gap}px; ${surface} }`;\nif (!card.cssText.includes('padding: 8px')) throw new Error('Numeric CSS interpolation failed');\nif (!card.cssText.includes('background-color: #fff')) throw new Error('CSSResult composition failed');\nlet rejected = false;\ntry { css`color: ${'red'};`; } catch { rejected = true; }\nif (!rejected) throw new Error('A raw string was accepted by css');\nconst reviewedToken = unsafeCSS('var(--brand-color)');\nif (!css`color: ${reviewedToken};`.cssText.includes('var(--brand-color)')) throw new Error('Reviewed CSS token did not compose');\n"
84
+ }
85
+ ]
86
+ }
87
+ ]
88
+ }
@@ -0,0 +1,5 @@
1
+ import type { TemplateResult } from './cossack-html.js';
2
+ /** Import renderer/server explicitly to serialize HTML in a browser. */
3
+ export declare const renderToString: (_result: TemplateResult, _opts?: {
4
+ hydrate?: boolean;
5
+ }) => string;
@@ -0,0 +1,7 @@
1
+ // @ts-self-types="./browser-ssr.d.ts"
2
+ //#region src/browser-ssr.ts
3
+ var e = (e, t = {}) => {
4
+ throw Error("Browser HTML serialization requires @cossackframework/renderer/server. Use render() or hydrate() for DOM updates.");
5
+ };
6
+ //#endregion
7
+ export { e as renderToString };
@@ -0,0 +1,2 @@
1
+ export * from './index.js';
2
+ export { renderToString } from './browser-ssr.js';
@@ -0,0 +1,9 @@
1
+ // @ts-self-types="./browser.d.ts"
2
+ import { isComponentResult as e } from "./component.js";
3
+ import { CSSResult as t, css as n, unsafeCSS as r } from "./css.js";
4
+ import { CossackElement as i, instanceStack as a, popCurrentInstance as o, pushCurrentInstance as s } from "./cossack-element.js";
5
+ import { BindResult as c, CacheResult as l, GuardResult as u, IfDefinedResult as d, KeyResult as f, LiveResult as p, PreventDefaultResult as m, RepeatResult as h, bind as g, cache as _, choose as v, classMap as y, guard as b, ifDefined as x, join as S, key as C, live as w, map as T, preventDefault as E, range as D, repeat as O, resolveField as k, setField as A, styleMap as j, when as M } from "./directives.js";
6
+ import { TemplateResult as N, UnsafeHTMLResult as P, captureRenderDrafts as F, component as I, escapeHtml as L, html as R, hydrate as z, isTemplateResult as B, isUnsafeHTML as V, nothing as H, render as U, svg as W, unsafeHTML as G } from "./cossack-html.js";
7
+ import { createContext as K } from "./context.js";
8
+ import { renderToString as q } from "./browser-ssr.js";
9
+ export { c as BindResult, t as CSSResult, l as CacheResult, i as CossackElement, u as GuardResult, d as IfDefinedResult, f as KeyResult, p as LiveResult, m as PreventDefaultResult, h as RepeatResult, N as TemplateResult, P as UnsafeHTMLResult, g as bind, _ as cache, F as captureRenderDrafts, v as choose, y as classMap, I as component, K as createContext, n as css, L as escapeHtml, b as guard, R as html, z as hydrate, x as ifDefined, a as instanceStack, e as isComponentResult, B as isTemplateResult, V as isUnsafeHTML, S as join, C as key, w as live, T as map, H as nothing, o as popCurrentInstance, E as preventDefault, s as pushCurrentInstance, D as range, U as render, q as renderToString, O as repeat, k as resolveField, A as setField, j as styleMap, W as svg, r as unsafeCSS, G as unsafeHTML, M as when };
@@ -1,4 +1,4 @@
1
- import { TemplateResult } from './cossack-html.js';
1
+ import { TemplateResult, type HydrationDiagnosticMetadata } from './cossack-html.js';
2
2
  import { Context } from './context.js';
3
3
  import type { CSSResultGroup } from './css.js';
4
4
  export type PropertyDeclaration = {
@@ -26,6 +26,8 @@ export declare const instanceStack: CossackElement[];
26
26
  export declare const pushCurrentInstance: (instance: CossackElement) => number;
27
27
  export declare const popCurrentInstance: () => CossackElement | undefined;
28
28
  export declare class CossackElement implements ReactiveControllerHost {
29
+ /** Development-only boundary hints; override to mark intentional client differences. */
30
+ get hydrationMetadata(): HydrationDiagnosticMetadata | undefined;
29
31
  static properties: PropertyDeclarations;
30
32
  static readonly _isCossackElement = true;
31
33
  static components: Record<string, typeof CossackElement>;
@@ -67,6 +69,8 @@ export declare class CossackElement implements ReactiveControllerHost {
67
69
  _finalizeRenderOutput(value: TemplateResult | unknown | null): TemplateResult | unknown | null;
68
70
  private _claimTemplateOwnership;
69
71
  mount(container: HTMLElement, hydrateFirst?: boolean): void;
72
+ /** @internal Attach an owned root without scheduling an unowned initial render. */
73
+ _frameworkAttachRenderRoot(container: HTMLElement, isCurrent: () => boolean, hydrateFirst?: boolean): () => void;
70
74
  addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, _options?: boolean | AddEventListenerOptions): void;
71
75
  removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, _options?: boolean | EventListenerOptions): void;
72
76
  dispatchEvent(event: Event): boolean;
@@ -13,6 +13,7 @@ var o = [], s = (e) => o.push(e), c = () => o.pop(), l = /* @__PURE__ */ new Wea
13
13
  }
14
14
  return n;
15
15
  }, f = (e, t) => n`${e}${t}`, p = class {
16
+ get hydrationMetadata() {}
16
17
  static properties = {};
17
18
  static _isCossackElement = !0;
18
19
  static components = {};
@@ -126,13 +127,15 @@ var o = [], s = (e) => o.push(e), c = () => o.pop(), l = /* @__PURE__ */ new Wea
126
127
  }
127
128
  }
128
129
  mount(e, t = !1) {
129
- let o = t;
130
- this.addRenderListener((t) => {
131
- if (t) {
132
- let s = i(t) ? t : n`${t}`;
133
- o ? (o = !1, r(s, e)) : a(s, e);
134
- }
135
- }), this.requestUpdate();
130
+ this._frameworkAttachRenderRoot(e, () => !0, t), this.requestUpdate();
131
+ }
132
+ _frameworkAttachRenderRoot(e, t, o = !1) {
133
+ let s = o, c = (o) => {
134
+ if (!t()) return;
135
+ let c = i(o) ? o : n`${o}`;
136
+ s ? (s = !1, r(c, e, import.meta.env?.DEV ? this.hydrationMetadata : void 0)) : a(c, e);
137
+ };
138
+ return this.addRenderListener(c), () => this.removeRenderListener(c);
136
139
  }
137
140
  addEventListener(e, t, n) {
138
141
  t && (this.__eventListeners.has(e) || this.__eventListeners.set(e, /* @__PURE__ */ new Set()), this.__eventListeners.get(e).add(t));
@@ -18,10 +18,13 @@ export declare const svg: (strings: TemplateStringsArray, ...values: unknown[])
18
18
  export declare const nothing: unique symbol;
19
19
  export type ValueSanitizer = (value: unknown) => unknown;
20
20
  export type SanitizerFactory = (node: Node, name: string, type: 'property' | 'attribute') => ValueSanitizer;
21
- export declare const component: <T extends CossackElement>(clazz: new () => T, props?: T['props'] & Record<string, unknown>, children?: unknown) => TemplateResult<1>;
21
+ export declare function component<T extends CossackElement>(clazz: new () => T, props: T['props'], children?: unknown): TemplateResult<1>;
22
+ export declare function component<T extends CossackElement>(clazz: new () => T, props?: T['props'], children?: unknown): TemplateResult<1>;
22
23
  export declare const isTemplateResult: (value: unknown) => value is TemplateResult;
24
+ declare const UNSAFE_HTML_BRAND: unique symbol;
23
25
  export declare class UnsafeHTMLResult {
24
26
  readonly value: string;
27
+ readonly [UNSAFE_HTML_BRAND] = true;
25
28
  constructor(value: string);
26
29
  }
27
30
  export declare const unsafeHTML: (value: string) => UnsafeHTMLResult;
@@ -30,6 +33,24 @@ export declare const escapeHtml: (unsafe: unknown) => string;
30
33
  export declare const renderToString: (result: TemplateResult, opts?: {
31
34
  hydrate?: boolean;
32
35
  }) => string;
36
+ /** Development-only context; source files must be project-relative. Values are never captured. */
37
+ export interface HydrationDiagnosticMetadata {
38
+ component?: string;
39
+ source?: {
40
+ file: string;
41
+ line?: number;
42
+ column?: number;
43
+ };
44
+ statePath?: string;
45
+ fields?: Record<number, string>;
46
+ /** Suppress expected differences at this boundary while still reconciling DOM. */
47
+ expectedClientOnly?: boolean;
48
+ }
49
+ /** @internal Local, one-use draft checkpoint. Contains no serializable state or live DOM restoration. */
50
+ export declare const captureRenderDrafts: (container: Node) => {
51
+ restore(current: () => boolean, owners?: Iterable<readonly [CossackElement, CossackElement]>): void;
52
+ discard(): void;
53
+ };
33
54
  export declare const render: (result: TemplateResult, container: Node) => void;
34
55
  /**
35
56
  * Hydrate an existing container whose children were produced by SSR
@@ -41,4 +62,5 @@ export declare const render: (result: TemplateResult, container: Node) => void;
41
62
  * If the existing DOM cannot be confidently matched to the template, falls
42
63
  * back to a full `render()` so behaviour is always correct.
43
64
  */
44
- export declare const hydrate: (result: TemplateResult, container: Node) => void;
65
+ export declare const hydrate: (result: TemplateResult, container: Node, metadata?: HydrationDiagnosticMetadata) => void;
66
+ export {};