@cossackframework/renderer 0.9.0 → 0.9.1

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.
@@ -1,6 +1,7 @@
1
1
  // @ts-self-types="./minify-html.d.ts"
2
+ import { RAW_TEXT_TAGS as e, forEachHtmlToken as t } from "./template-analysis.js";
2
3
  //#region src/minify-html.ts
3
- var e = /<(script|style|pre|textarea)\b[^>]*>[\s\S]*?<\/\1>/gi, t = RegExp(`<(${[.../* @__PURE__ */ new Set([
4
+ var n = /* @__PURE__ */ new Set([
4
5
  "area",
5
6
  "base",
6
7
  "br",
@@ -15,23 +16,127 @@ var e = /<(script|style|pre|textarea)\b[^>]*>[\s\S]*?<\/\1>/gi, t = RegExp(`<(${
15
16
  "source",
16
17
  "track",
17
18
  "wbr"
18
- ])].join("|")})(\\s[^>]*)?\\/\\s*>`, "gi"), n = /\s+type\s*=\s*["']text\/(javascript|css)["']/gi, r = /(\w[\w-]*)\s*=\s*["']([a-zA-Z0-9_.-]+)["'](?=(\s|\/?>))/g;
19
- function i(t) {
20
- let r = [];
21
- return {
22
- html: t.replace(e, (e) => {
23
- let t = e.replace(/^<(?:[^>"']|"[^"]*"|'[^']*')*>/, (e) => e.replace(n, ""));
24
- return r.push(t), `\x00PRESERVE_${r.length - 1}\x00`;
25
- }),
26
- blocks: r
19
+ ]), r = /* @__PURE__ */ new Set([
20
+ "base",
21
+ "basefont",
22
+ "bgsound",
23
+ "link",
24
+ "meta",
25
+ "noframes",
26
+ "script",
27
+ "style",
28
+ "title"
29
+ ]), i = /* @__PURE__ */ new Set([
30
+ "pre",
31
+ "listing",
32
+ "xmp",
33
+ "plaintext"
34
+ ]), a = /* @__PURE__ */ new Set(["xmp", "plaintext"]), o = /* @__PURE__ */ new Set([
35
+ "pre",
36
+ "pre-wrap",
37
+ "break-spaces",
38
+ "preserve",
39
+ "preserve-spaces"
40
+ ]), s = /* @__PURE__ */ new Set([
41
+ "whitespace-pre",
42
+ "whitespace-pre-wrap",
43
+ "whitespace-break-spaces"
44
+ ]), c = /^[a-zA-Z0-9_.-]+$/, l = /^<!--(?:\[if\s|\/?CRP|CSA-[SE])/, u = (e) => /(?:<|&[a-zA-Z0-9#]*)$/.test(e), d = (e, t) => {
45
+ let n = t.toLowerCase();
46
+ return e === "script" ? n === "text/javascript" : (e === "style" || e === "link") && n === "text/css";
47
+ }, f = (e) => {
48
+ let t = "", n = 0;
49
+ for (let r = 0; r < e.length;) {
50
+ let i = e.charCodeAt(r);
51
+ if (i !== 32 && i !== 9 && i !== 10 && i !== 13) {
52
+ r++;
53
+ continue;
54
+ }
55
+ let a = r, o = !1;
56
+ for (; a < e.length; a++) {
57
+ let t = e.charCodeAt(a);
58
+ if (t === 10 || t === 13) o = !0;
59
+ else if (t !== 32 && t !== 9) break;
60
+ }
61
+ (a - r > 1 || i === 9 || i === 13) && (t += e.slice(n, r) + (o ? "\n" : " "), n = a), r = a;
62
+ }
63
+ return n === 0 ? e : t + e.slice(n);
64
+ }, p = /^[ \t\n\f\r]+/, m = (e, t) => {
65
+ for (let n of t) {
66
+ if (n.valueStart < 0) continue;
67
+ let t = n.name.toLowerCase();
68
+ if (t !== "style" && t !== "class") continue;
69
+ let r = e.slice(n.valueStart, n.valueEnd).toLowerCase();
70
+ if (t === "style") {
71
+ if (!r.includes("white-space")) continue;
72
+ for (let [, e] of r.matchAll(/(?:^|;)\s*white-space(?:-collapse)?\s*:([^;]*)/g)) if (e.replace("!important", "").trim().split(/\s+/).some((e) => o.has(e))) return !0;
73
+ } else if (r.includes("whitespace-") && r.split(/[ \t\n\f\r]+/).some((e) => s.has(e.slice(e.lastIndexOf(":") + 1).replace(/^!/, "")))) return !0;
74
+ }
75
+ return !1;
76
+ };
77
+ function h(o) {
78
+ let s = "", h = "", g = 0, _ = null, v = () => {
79
+ h &&= (g !== 4 && (h = h.replace(p, ""), h && (g = 4)), s += f(h), "");
80
+ }, y = (e) => {
81
+ switch (g) {
82
+ case 0:
83
+ case 1:
84
+ g = e === "html" ? 1 : e === "head" || r.has(e) ? 2 : 4;
85
+ break;
86
+ case 2:
87
+ case 3:
88
+ e !== "html" && e !== "head" && !r.has(e) && (g = 4);
89
+ break;
90
+ }
91
+ }, b = (e, t, n) => {
92
+ if (t.valueStart < 0) return ` ${t.name}`;
93
+ let r = o.slice(t.valueStart, t.valueEnd), i = t.name.toLowerCase();
94
+ return i === "type" && d(e, r) ? "" : (i === "class" && (r = r.replace(/[ \t\n\f\r]+/g, " ").replace(/^ | $/g, "")), !n && (!t.quote || c.test(r)) ? ` ${t.name}=${r}` : t.quote ? ` ${t.name}=${t.quote}${r}${t.quote}` : ` ${t.name}="${r.replace(/"/g, "&quot;")}"`);
95
+ }, x = (e) => {
96
+ let t = e.attributes.find((t) => t.name.toLowerCase() === "type" && t.valueStart >= 0 && d(e.name, o.slice(t.valueStart, t.valueEnd)));
97
+ if (!t) return o.slice(e.start, e.end);
98
+ let n = t.nameStart;
99
+ for (; n > e.nameEnd && /[ \t\n\f\r]/.test(o[n - 1]);) n--;
100
+ let r = t.valueEnd + +!!t.quote;
101
+ return o.slice(e.start, n) + o.slice(r, e.end);
102
+ }, S = (e) => {
103
+ if (!e.closed || e.attributes.some((e) => e.name.startsWith("="))) return o.slice(e.start, e.end);
104
+ let { name: t, attributes: r } = e, i = e.selfClosing && !n.has(t), a = o.slice(e.start, e.nameEnd);
105
+ return r.forEach((e, n) => {
106
+ a += b(t, e, i && n === r.length - 1);
107
+ }), a + (i ? "/>" : ">");
27
108
  };
28
- }
29
- function a(e, t) {
30
- return e.replace(/\x00PRESERVE_(\d+)\x00/g, (e, n) => t[parseInt(n, 10)]);
31
- }
32
- function o(e) {
33
- let { html: o, blocks: s } = i(e), c = o.replace(/<!--(?!\[if\s|\/?CRP|CSA-[SE])[\s\S]*?-->/g, "");
34
- return c = c.replace(n, ""), c = c.replace(/\s+/g, " "), c = c.replace(/>\s+</g, "><"), c = c.replace(r, (e, t, n, r) => r === "/>" ? e : `${t}=${n}`), c = c.replace(t, (e, t, n) => `<${t}${n ? n.trimEnd() : ""}>`), c = c.replace(/(>|\x00PRESERVE_\d+\x00)\s+(?=<|\x00PRESERVE_\d+\x00)/g, "$1"), c = a(c, s), c = c.trim(), c;
109
+ return t(o, (t) => {
110
+ if (_) {
111
+ s += o.slice(t.start, t.end), t.type === "end-tag" && t.name === _.name && _.name !== "plaintext" ? (_.raw || --_.depth === 0) && (_ = null) : t.type === "start-tag" && t.name === _.name && !_.raw && _.depth++;
112
+ return;
113
+ }
114
+ switch (t.type) {
115
+ case "text":
116
+ h += o.slice(t.start, t.end);
117
+ break;
118
+ case "comment":
119
+ (l.test(o.slice(t.start, t.end)) || u(h)) && (v(), s += o.slice(t.start, t.end));
120
+ break;
121
+ case "start-tag": {
122
+ v(), y(t.name);
123
+ let { name: r } = t, c = !n.has(r) && (i.has(r) || m(o, t.attributes));
124
+ s += c || e.has(r) ? x(t) : S(t), c && (_ = {
125
+ name: r,
126
+ depth: 1,
127
+ raw: a.has(r)
128
+ });
129
+ break;
130
+ }
131
+ case "end-tag":
132
+ v(), g === 2 && t.name === "head" ? g = 3 : g !== 4 && !r.has(t.name) && (g = 4), s += `${o.slice(t.start, t.nameEnd)}>`;
133
+ break;
134
+ case "raw-text":
135
+ case "other":
136
+ v(), s += o.slice(t.start, t.end);
137
+ break;
138
+ }
139
+ }), v(), s;
35
140
  }
36
141
  //#endregion
37
- export { o as minifyHtml };
142
+ export { h as minifyHtml };
package/dist/server.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { renderToString, escapeHtml } from './cossack-html.js';
2
2
  export { html, svg, nothing, TemplateResult } from './cossack-html.js';
3
- export type { SVGTemplateResult, ValueSanitizer, SanitizerFactory } from './cossack-html.js';
3
+ export type { SVGTemplateResult } from './cossack-html.js';
4
4
  export { css, unsafeCSS, CSSResult } from './css.js';
5
5
  export type { CSSResultGroup } from './css.js';
6
+ export { collectComponentStyles, renderComponentStyles } from './style-runtime.js';
7
+ export type { ComponentStyle } from './style-runtime.js';
6
8
  export { minifyHtml } from './minify-html.js';
package/dist/server.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // @ts-self-types="./server.d.ts"
2
- import { CSSResult as e, css as t, unsafeCSS as n } from "./css.js";
3
- import { TemplateResult as r, escapeHtml as i, html as a, nothing as o, renderToString as s, svg as c } from "./cossack-html.js";
4
- import { minifyHtml as l } from "./minify-html.js";
5
- export { e as CSSResult, r as TemplateResult, t as css, i as escapeHtml, a as html, l as minifyHtml, o as nothing, s as renderToString, c as svg, n as unsafeCSS };
2
+ import { collectComponentStyles as e, renderComponentStyles as t } from "./style-runtime.js";
3
+ import { TemplateResult as n, escapeHtml as r, html as i, nothing as a, renderToString as o, svg as s } from "./cossack-html.js";
4
+ import { CSSResult as c } from "./css-result.js";
5
+ import { css as l, unsafeCSS as u } from "./css.js";
6
+ import { minifyHtml as d } from "./minify-html.js";
7
+ export { c as CSSResult, n as TemplateResult, e as collectComponentStyles, l as css, r as escapeHtml, i as html, d as minifyHtml, a as nothing, t as renderComponentStyles, o as renderToString, s as svg, u as unsafeCSS };
@@ -63,9 +63,10 @@ var t = (e) => e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt
63
63
  }
64
64
  "childNodes" in e && e.childNodes.forEach(o);
65
65
  };
66
- o(r), i.sort((e, t) => t.start - e.start || t.end - e.end);
67
- for (let e of i) n = n.slice(0, e.start) + e.text + n.slice(e.end);
68
- return n;
66
+ o(r), i.sort((e, t) => e.start - t.start || e.end - t.end);
67
+ let s = "", c = 0;
68
+ for (let e of i) e.start > c && (s += n.slice(c, e.start)), s += e.text, c = Math.max(c, e.end);
69
+ return s + n.slice(c);
69
70
  };
70
71
  //#endregion
71
72
  export { n as serializeFormValues };
@@ -0,0 +1,42 @@
1
+ import { type FinalizedStyles } from './style-runtime.js';
2
+ /**
3
+ * Client registry of component stylesheets.
4
+ *
5
+ * Each style root (a Document, or a ShadowRoot that rendered components live
6
+ * in) holds one `<style data-cossack-style="<scope id>">` per scope, with a
7
+ * count of the template instances that use it. In a document the element
8
+ * lives in `<head>`; SSR puts it there too, and the first use adopts it.
9
+ *
10
+ * - Acquisitions resolve their root once their nodes are in a document or
11
+ * shadow root: synchronously at the end of a render that inserted them, so
12
+ * styles exist before `updated()`, layout reads or paint, or at the latest
13
+ * in a microtask.
14
+ * - Releases wait for a macrotask. A client navigation tears down the old
15
+ * page and mounts the new one in one render, but nested components render
16
+ * in the microtasks that follow; waiting until they finished keeps every
17
+ * style the new page also uses, without removing and re-inserting it.
18
+ */
19
+ type StyleRoot = Document | ShadowRoot;
20
+ /** @internal One template instance's claim on a scope's stylesheet. */
21
+ export interface StyleUse {
22
+ readonly styles: FinalizedStyles;
23
+ /** A top-level node of the template instance, used to find its root. */
24
+ anchor: Node;
25
+ /** The root counted for this use; null until resolved or once released. */
26
+ root: StyleRoot | null;
27
+ released: boolean;
28
+ }
29
+ /** @internal Claim a scope's stylesheet for a new template instance. */
30
+ export declare const acquireStyle: (styles: FinalizedStyles, anchor: Node) => StyleUse;
31
+ /** @internal Give up a claim. The style goes, a macrotask later, with the last claim in its root. */
32
+ export declare const releaseStyle: (use: StyleUse) => void;
33
+ /**
34
+ * @internal Re-count a claim whose nodes moved to another root since it was
35
+ * counted (for example a subtree moved into a shadow root).
36
+ */
37
+ export declare const updateStyleRoot: (use: StyleUse) => void;
38
+ /** @internal Count pending claims whose nodes now sit in a document or shadow root. */
39
+ export declare const flushStyleAcquisitions: () => void;
40
+ /** @internal Whether a node is a registry-managed component style element. */
41
+ export declare const isManagedStyle: (node: Node) => boolean;
42
+ export {};
@@ -0,0 +1,73 @@
1
+ // @ts-self-types="./style-registry.d.ts"
2
+ import { COMPONENT_STYLE_ATTRIBUTE as e } from "./style-runtime.js";
3
+ //#region src/style-registry.ts
4
+ var t = /* @__PURE__ */ new WeakMap(), n = /* @__PURE__ */ new WeakSet(), r = /* @__PURE__ */ new Set(), i = [], a = !1, o = !1, s = (e) => e.nodeType === 9, c = (e) => typeof ShadowRoot < "u" && e instanceof ShadowRoot, l = (e, t) => {
5
+ let n = e.getRootNode();
6
+ return s(n) || c(n) ? n : t ? e.ownerDocument : null;
7
+ }, u = (t, { scopeId: r, cssText: i }) => {
8
+ let a = (s(t) ? t : t.ownerDocument).createElement("style");
9
+ if (a.setAttribute(e, r), a.textContent = i, s(t)) (t.head ?? t.documentElement)?.appendChild(a);
10
+ else {
11
+ let e = t.firstChild;
12
+ for (; e && n.has(e);) e = e.nextSibling;
13
+ t.insertBefore(a, e);
14
+ }
15
+ return a;
16
+ }, d = (e, r) => {
17
+ let i = t.get(r);
18
+ i || (i = /* @__PURE__ */ new Map(), t.set(r, i));
19
+ let { scopeId: a } = e.styles, o = i.get(a);
20
+ o || (o = {
21
+ count: 0,
22
+ element: r.querySelector(`style[data-cossack-style="${a}"]`) ?? u(r, e.styles)
23
+ }, n.add(o.element), i.set(a, o)), o.count++, e.root = r;
24
+ }, f = (e) => {
25
+ for (let t of r) {
26
+ let n = l(t.anchor, e);
27
+ n && (r.delete(t), d(t, n));
28
+ }
29
+ }, p = () => {
30
+ o = !1, f(!0);
31
+ let e = i;
32
+ i = [];
33
+ for (let { root: r, scopeId: i } of e) {
34
+ let e = t.get(r), a = e?.get(i);
35
+ !a || --a.count > 0 || (e.delete(i), n.delete(a.element), a.element.remove());
36
+ }
37
+ }, m = () => {
38
+ a || (a = !0, queueMicrotask(() => {
39
+ a = !1, f(!0);
40
+ }));
41
+ }, h = () => {
42
+ o || (o = !0, setTimeout(p, 0));
43
+ }, g = (e, t) => {
44
+ let n = {
45
+ styles: e,
46
+ anchor: t,
47
+ root: null,
48
+ released: !1
49
+ };
50
+ return r.add(n), m(), n;
51
+ }, _ = (e) => {
52
+ if (!e.released) {
53
+ if (e.released = !0, !e.root) {
54
+ r.delete(e);
55
+ return;
56
+ }
57
+ i.push({
58
+ root: e.root,
59
+ scopeId: e.styles.scopeId
60
+ }), e.root = null, h();
61
+ }
62
+ }, v = (e) => {
63
+ if (e.released || !e.root || !e.anchor.isConnected) return;
64
+ let t = e.anchor.getRootNode();
65
+ t === e.root || !(s(t) || c(t)) || (i.push({
66
+ root: e.root,
67
+ scopeId: e.styles.scopeId
68
+ }), d(e, t), h());
69
+ }, y = () => {
70
+ r.size > 0 && f(!1);
71
+ }, b = (e) => n.has(e);
72
+ //#endregion
73
+ export { g as acquireStyle, y as flushStyleAcquisitions, b as isManagedStyle, _ as releaseStyle, v as updateStyleRoot };
@@ -0,0 +1,47 @@
1
+ import type { CSSResultGroup } from './css-result.js';
2
+ export interface FinalizedStyles {
3
+ readonly cssText: string;
4
+ readonly scopeId: string;
5
+ }
6
+ /** One component style scope a render used: its id and its scoped CSS. */
7
+ export interface ComponentStyle {
8
+ readonly scopeId: string;
9
+ readonly cssText: string;
10
+ }
11
+ type StyledClass = Function & {
12
+ styles?: CSSResultGroup;
13
+ };
14
+ type StyleFinalizer = (styles: CSSResultGroup) => FinalizedStyles;
15
+ /** @internal Installed when css`` or unsafeCSS() constructs component styles. */
16
+ export declare const registerStyleFinalizer: (finalizer: StyleFinalizer) => void;
17
+ /** @internal Components without styles never need the CSS parser. */
18
+ export declare const getFinalizedStyles: (componentClass: StyledClass) => FinalizedStyles | null;
19
+ /**
20
+ * @internal The stylesheet for a scope that templates carry, or undefined when
21
+ * there is nothing to emit (unknown scope or empty CSS).
22
+ */
23
+ export declare const stylesForScope: (scopeId: string) => FinalizedStyles | undefined;
24
+ /** @internal Called by SSR for every template rendered in a style scope. */
25
+ export declare const recordStyleScope: (scopeId: string) => void;
26
+ /**
27
+ * Run a synchronous server render and return the component style scopes it
28
+ * used, in first-use order. Components do not inline their styles: emit the
29
+ * returned styles once per page, in `<head>`, with `renderComponentStyles()`.
30
+ *
31
+ * ```ts
32
+ * const { result: body, styles } = collectComponentStyles(() => renderToString(page, { hydrate: true }));
33
+ * const head = renderComponentStyles(styles);
34
+ * ```
35
+ */
36
+ export declare const collectComponentStyles: <T>(render: () => T) => {
37
+ result: T;
38
+ styles: ComponentStyle[];
39
+ };
40
+ /** Attribute naming the scope on every managed component `<style>` element. */
41
+ export declare const COMPONENT_STYLE_ATTRIBUTE = "data-cossack-style";
42
+ /**
43
+ * One `<style data-cossack-style="<scope id>">` element per collected scope.
44
+ * The client adopts these elements on hydration instead of inserting copies.
45
+ */
46
+ export declare const renderComponentStyles: (styles: readonly ComponentStyle[]) => string;
47
+ export {};
@@ -0,0 +1,43 @@
1
+ // @ts-self-types="./style-runtime.d.ts"
2
+ //#region src/style-runtime.ts
3
+ var e, t = /* @__PURE__ */ new WeakMap(), n = /* @__PURE__ */ new Map(), r = (e) => Array.isArray(e) && e.every(r), i = (t) => {
4
+ e = t;
5
+ }, a = (i) => {
6
+ if (t.has(i)) return t.get(i);
7
+ let a = i.styles, o;
8
+ if (a === void 0) o = null;
9
+ else if (e) o = e(a);
10
+ else if (r(a)) o = {
11
+ cssText: "",
12
+ scopeId: "cztntfp"
13
+ };
14
+ else throw TypeError("[cossack/renderer] static styles must contain only CSSResult values returned by css`` or unsafeCSS().");
15
+ return t.set(i, o), o && !n.has(o.scopeId) && n.set(o.scopeId, o), o;
16
+ }, o = (e) => {
17
+ let t = n.get(e);
18
+ return t && t.cssText !== "" ? t : void 0;
19
+ }, s, c = (e) => {
20
+ let t = s;
21
+ if (!t || t.has(e)) return;
22
+ let n = o(e);
23
+ n && t.set(e, {
24
+ scopeId: e,
25
+ cssText: n.cssText
26
+ });
27
+ }, l = (e) => {
28
+ let t = s, n = /* @__PURE__ */ new Map();
29
+ s = n;
30
+ try {
31
+ return {
32
+ result: e(),
33
+ styles: [...n.values()]
34
+ };
35
+ } finally {
36
+ if (s = t, t) for (let [e, r] of n) t.has(e) || t.set(e, r);
37
+ }
38
+ }, u = "data-cossack-style", d = (e) => e.map(({ scopeId: e, cssText: t }) => {
39
+ let n = t.replace(/<\/style/gi, "<\\/style");
40
+ return `<style ${u}="${e.replace(/[^a-z0-9_-]/gi, "")}">${n}</style>`;
41
+ }).join("");
42
+ //#endregion
43
+ export { u as COMPONENT_STYLE_ATTRIBUTE, l as collectComponentStyles, a as getFinalizedStyles, c as recordStyleScope, i as registerStyleFinalizer, d as renderComponentStyles, o as stylesForScope };
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The single HTML tokenizer in the renderer.
3
+ *
4
+ * SSR (`renderToString`) and the client (`compileTemplate`) must agree on what
5
+ * every binding in a template is: child content, part of an attribute, text in
6
+ * a raw-text element, or something inside a comment. They used to run four
7
+ * hand-written scanners that disagreed on `<` in text, comments and raw-text
8
+ * elements. One state machine (`step`) now reads HTML the way the HTML
9
+ * tokenizer does. `analyzeTemplate` drives it over template strings to
10
+ * classify bindings; `tokenizeHtml` drives it over rendered markup for the SSR
11
+ * class merge and `minifyHtml`.
12
+ */
13
+ /** Elements whose content the HTML parser reads as text, not markup. */
14
+ export declare const RAW_TEXT_TAGS: ReadonlySet<string>;
15
+ export type BindingInfo =
16
+ /** Child content. Hydration wraps it in `<!--CRP_i-->`/`<!--/CRP-->`. */
17
+ {
18
+ kind: 'node';
19
+ }
20
+ /**
21
+ * Inside an attribute value. `name` keeps the author's case (the DOM
22
+ * lowercases HTML attribute names). `start` bindings directly follow
23
+ * `name=` or `name="`; `prefixStart` is the index in the (scoped) string
24
+ * where that `name=` text begins. Other attribute bindings interpolate into
25
+ * a value that already started.
26
+ *
27
+ * `directValue` is true when a `.value` set here (directly or through a
28
+ * spread) can be serialized by SSR as a plain `value` attribute: the element
29
+ * is not a <textarea>/<select> and has no static `value` attribute. Other
30
+ * cases need the serializeFormValues pass.
31
+ */
32
+ | AttributeBinding
33
+ /**
34
+ * Text content of a raw-text element (`tag` is lowercase). `first` is true
35
+ * when no text precedes the binding inside the element.
36
+ */
37
+ | {
38
+ kind: 'raw-text';
39
+ tag: string;
40
+ first: boolean;
41
+ }
42
+ /** Inside a comment. The value is dropped by both renderers. */
43
+ | {
44
+ kind: 'comment';
45
+ }
46
+ /** In a tag but not in an attribute value (e.g. `<div ${x}>`). Dropped. */
47
+ | {
48
+ kind: 'element';
49
+ }
50
+ /**
51
+ * A component tag: `<${Card}` opens one and `</${Card}` closes it. `html`
52
+ * compiles component tags into component() results before any renderer
53
+ * sees the template, so the renderers never receive this kind.
54
+ */
55
+ | {
56
+ kind: 'tag';
57
+ closing: boolean;
58
+ };
59
+ export interface AttributeBinding {
60
+ kind: 'attribute';
61
+ name: string;
62
+ start: boolean;
63
+ /**
64
+ * True when the binding is the attribute's whole value (`name=${x}` or
65
+ * `name="${x}"`). False when the value also has static text or other
66
+ * bindings (`name="a ${x}"`, `name="${x}${y}"`): then the attribute is
67
+ * text, and every binding in it adds its value as text.
68
+ */
69
+ whole: boolean;
70
+ quote: '"' | "'" | '';
71
+ prefixStart: number;
72
+ directValue: boolean;
73
+ /**
74
+ * Where the binding's element starts: the `<` is at `tagOffset` in the
75
+ * (scoped) string `tagString`. SSR uses it to find the element's markup.
76
+ */
77
+ tagString: number;
78
+ tagOffset: number;
79
+ /**
80
+ * Where the start tag ends: its `>` is at `tagEndOffset` in the (scoped)
81
+ * string `tagEndString`. Both are -1 when the template ends inside the tag.
82
+ */
83
+ tagEndString: number;
84
+ tagEndOffset: number;
85
+ }
86
+ /** An attribute that contains bindings, used to drop it whole for `nothing`. */
87
+ export interface AttributeGroup {
88
+ readonly indices: readonly number[];
89
+ /** Static text from the whitespace before the name up to the first binding. */
90
+ readonly prefix: string;
91
+ /** Static text after the last binding that still belongs to the attribute. */
92
+ readonly suffixLength: number;
93
+ }
94
+ /**
95
+ * Everything the renderers need to know about a template's static strings.
96
+ * It never depends on values, so one analysis is shared by every render and
97
+ * every instance of the template. It is deeply frozen: a render that tried to
98
+ * write to it would corrupt every later render, so that throws instead.
99
+ */
100
+ export interface TemplateAnalysis {
101
+ /** Template strings with the style scope attribute added to static tags. */
102
+ readonly strings: readonly string[];
103
+ readonly bindings: readonly Readonly<BindingInfo>[];
104
+ /**
105
+ * Indexed by binding: the attribute whose first binding has that index, or
106
+ * undefined. Same length as `bindings`.
107
+ */
108
+ readonly attributeGroups: readonly (AttributeGroup | undefined)[];
109
+ }
110
+ /** @internal Counts analysis runs so tests can verify the cache. */
111
+ export declare const templateAnalysisStats: {
112
+ runs: number;
113
+ };
114
+ /** The shared analysis for a template's strings in a style scope. */
115
+ export declare const getTemplateAnalysis: (input: TemplateStringsArray, scopeId?: string) => TemplateAnalysis;
116
+ /** @internal Tokenizer states, shared with the template parser. */
117
+ export declare const enum State {
118
+ Data = 0,
119
+ TagName = 1,
120
+ BeforeAttrName = 2,
121
+ AttrName = 3,
122
+ AfterAttrName = 4,
123
+ BeforeAttrValue = 5,
124
+ AttrValueQuoted = 6,
125
+ AttrValueUnquoted = 7,
126
+ EndTag = 8,
127
+ Comment = 9,
128
+ BogusComment = 10,
129
+ RawText = 11
130
+ }
131
+ /** @internal */
132
+ export declare const isSpace: (ch: string | undefined) => ch is "\t" | "\n" | "\f" | "\r" | " ";
133
+ /** @internal */
134
+ export interface Tokenizer {
135
+ state: State;
136
+ /** Lowercase name of the most recent start tag. Kept after the tag ends. */
137
+ tagName: string;
138
+ /** Lowercase name of the raw-text element whose text is being read. */
139
+ rawTextTag: string;
140
+ quote: '"' | "'";
141
+ /**
142
+ * The last two characters seen inside a comment, seeded with the opening
143
+ * dashes so `<!-->` and `<!--->` close the way the HTML tokenizer does.
144
+ */
145
+ commentTail: string;
146
+ }
147
+ /** @internal */
148
+ export declare const createTokenizer: () => Tokenizer;
149
+ /**
150
+ * Advance the tokenizer over `str[j]`. Returns the index of the next character
151
+ * to read: `j + 1`, `j + 4` after `<!--`, the end of a run of characters that
152
+ * cannot change the state (text, raw text, quoted values, comment bodies), or
153
+ * `j` when the character must be read again in the new state (it ended a tag
154
+ * name, an attribute name or an unquoted value). Callers compare the state
155
+ * before and after a step to see what the characters did.
156
+ * @internal
157
+ */
158
+ export declare const step: (t: Tokenizer, str: string, j: number) => number;
159
+ /**
160
+ * Tokenize template strings and classify every binding.
161
+ *
162
+ * When `scopeId` is given, ` data-cossack-scope="<id>"` is inserted after the
163
+ * name of every opening tag that appears in the static strings (not inside
164
+ * comments or raw text, and never inside nested values).
165
+ */
166
+ export declare const analyzeTemplate: (input: readonly string[], scopeId?: string) => TemplateAnalysis;
167
+ /** An attribute of a start tag. Offsets index the tokenized source. */
168
+ export interface HtmlAttribute {
169
+ /** As written. */
170
+ readonly name: string;
171
+ readonly nameStart: number;
172
+ readonly nameEnd: number;
173
+ /** Value bounds without quotes; both -1 when there is no `=`. */
174
+ readonly valueStart: number;
175
+ readonly valueEnd: number;
176
+ readonly quote: '"' | "'" | '';
177
+ }
178
+ /** One token of rendered markup. `start`/`end` index the tokenized source. */
179
+ export type HtmlToken = {
180
+ readonly type: 'text';
181
+ readonly start: number;
182
+ readonly end: number;
183
+ }
184
+ /** Text of a raw-text element (`tag` is lowercase). */
185
+ | {
186
+ readonly type: 'raw-text';
187
+ readonly start: number;
188
+ readonly end: number;
189
+ readonly tag: string;
190
+ } | {
191
+ readonly type: 'start-tag';
192
+ readonly start: number;
193
+ readonly end: number;
194
+ /** Lowercase tag name; the source keeps the author's case. */
195
+ readonly name: string;
196
+ readonly nameEnd: number;
197
+ readonly attributes: readonly HtmlAttribute[];
198
+ /** The tag ends with `/>`. */
199
+ readonly selfClosing: boolean;
200
+ /** False when the source ends before the tag's `>`. */
201
+ readonly closed: boolean;
202
+ } | {
203
+ readonly type: 'end-tag';
204
+ readonly start: number;
205
+ readonly end: number;
206
+ readonly name: string;
207
+ readonly nameEnd: number;
208
+ }
209
+ /** `<!--` up to and including `-->`. */
210
+ | {
211
+ readonly type: 'comment';
212
+ readonly start: number;
213
+ readonly end: number;
214
+ }
215
+ /** `<!doctype>`, `<?…>`, `</ …>`, or markup the source ends inside. */
216
+ | {
217
+ readonly type: 'other';
218
+ readonly start: number;
219
+ readonly end: number;
220
+ };
221
+ /** Split rendered markup into tokens, using the same tokenizer as templates. */
222
+ export declare const tokenizeHtml: (source: string) => HtmlToken[];
223
+ /** Call `visit` with each token of rendered markup, in order. */
224
+ export declare const forEachHtmlToken: (source: string, visit: (token: HtmlToken) => void) => void;