@segnavia/html 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 modstudio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ import { SanitizeOptions } from "./sanitize.js";
2
+ //#region src/bindings.d.ts
3
+ export declare const BINDINGS: readonly ["value", "href", "src", "each", "when", "present", "width"];
4
+ export declare function bindingNames(prefix: string): Record<(typeof BINDINGS)[number], string>;
5
+ export interface FillOptions extends Pick<SanitizeOptions, 'linkOrigins'> {
6
+ prefix: string;
7
+ data: Record<string, unknown>;
8
+ unavailable?: Iterable<string>;
9
+ }
10
+ export interface Filled {
11
+ html: string;
12
+ unavailable: string[];
13
+ values: string[];
14
+ }
15
+ export declare function hasBindings(html: string, prefix: string): boolean;
16
+ export declare function fill(html: string, options: FillOptions): Filled;
17
+ //#endregion
@@ -0,0 +1,155 @@
1
+ import { elements, parse, sanitize, serialize } from "./sanitize.js";
2
+ import { Text, cloneNode, isTag } from "domhandler";
3
+ //#region src/bindings.ts
4
+ const BINDINGS = [
5
+ "value",
6
+ "href",
7
+ "src",
8
+ "each",
9
+ "when",
10
+ "present",
11
+ "width"
12
+ ];
13
+ function bindingNames(prefix) {
14
+ return Object.fromEntries(BINDINGS.map((binding) => [binding, `data-${prefix}-${binding}`]));
15
+ }
16
+ function atPath(value, path) {
17
+ if (!path) return value;
18
+ const parts = path.split(".");
19
+ let held = value;
20
+ let start = 0;
21
+ if (held && typeof held === "object" && !Array.isArray(held)) for (let length = parts.length; length > 0; length -= 1) {
22
+ const prefix = parts.slice(0, length).join(".");
23
+ if (Object.hasOwn(held, prefix)) {
24
+ held = Reflect.get(held, prefix);
25
+ start = length;
26
+ break;
27
+ }
28
+ }
29
+ return parts.slice(start).reduce((current, part) => {
30
+ if (!current || typeof current !== "object" || Array.isArray(current)) return void 0;
31
+ return Object.hasOwn(current, part) ? Reflect.get(current, part) : void 0;
32
+ }, held);
33
+ }
34
+ function contextAt(stack, path) {
35
+ let depth = 0;
36
+ let rest = path;
37
+ while (rest.startsWith("../")) {
38
+ depth += 1;
39
+ rest = rest.slice(3);
40
+ }
41
+ return {
42
+ context: stack[Math.max(0, stack.length - 1 - depth)],
43
+ rest
44
+ };
45
+ }
46
+ function isPresent(value) {
47
+ if (value === void 0 || value === null || value === false) return false;
48
+ if (typeof value === "number") return value !== 0 && Number.isFinite(value);
49
+ if (typeof value === "string" || Array.isArray(value)) return value.length > 0;
50
+ return true;
51
+ }
52
+ function safeHref(value, origins) {
53
+ try {
54
+ const url = new URL(value);
55
+ return url.protocol === "https:" && origins.has(url.origin);
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ function hasBindings(html, prefix) {
61
+ const names = new Set(Object.values(bindingNames(prefix)));
62
+ return elements(parse(html).children).some((element) => Object.keys(element.attribs).some((name) => names.has(name)));
63
+ }
64
+ function fill(html, options) {
65
+ const names = bindingNames(options.prefix);
66
+ const origins = new Set([...options.linkOrigins ?? []].map((origin) => new URL(origin).origin));
67
+ const unavailable = new Set(options.unavailable ?? []);
68
+ const values = [];
69
+ const document = parse(sanitize(html, { linkOrigins: options.linkOrigins }));
70
+ const resolve = (path, stack) => {
71
+ const { context, rest } = contextAt(stack, path);
72
+ const value = atPath(context, rest);
73
+ if (value === void 0) unavailable.add(path);
74
+ return value;
75
+ };
76
+ const take = (element, name) => {
77
+ const value = element.attribs[name];
78
+ delete element.attribs[name];
79
+ return value;
80
+ };
81
+ const applies = (element, stack) => {
82
+ const context = stack[stack.length - 1];
83
+ const when = take(element, names.when);
84
+ if (when !== void 0 && (!context || typeof context !== "object" || Reflect.get(context, "state") !== when)) return false;
85
+ const present = take(element, names.present);
86
+ return present === void 0 || isPresent(resolve(present, stack));
87
+ };
88
+ const applyWidth = (element, stack) => {
89
+ const width = take(element, names.width);
90
+ if (width === void 0) return;
91
+ const value = resolve(width, stack);
92
+ if (typeof value === "number" && Number.isFinite(value)) element.attribs.style = `width: ${Math.min(100, Math.max(0, value))}%`;
93
+ else unavailable.add(width);
94
+ };
95
+ const applyValue = (element, stack) => {
96
+ const path = take(element, names.value);
97
+ if (path === void 0) return;
98
+ const value = resolve(path, stack);
99
+ element.children = [];
100
+ if (typeof value === "string" || typeof value === "number" && Number.isFinite(value)) {
101
+ const text = new Text(String(value));
102
+ text.parent = element;
103
+ element.children = [text];
104
+ if (element.attribs.dir === void 0) element.attribs.dir = "auto";
105
+ values.push(String(value));
106
+ } else if (value !== void 0) unavailable.add(path);
107
+ };
108
+ const applyUrls = (element, stack) => {
109
+ for (const attribute of ["href", "src"]) {
110
+ const path = take(element, names[attribute]);
111
+ if (path === void 0) continue;
112
+ const value = resolve(path, stack);
113
+ if (typeof value === "string" && (attribute === "href" ? safeHref(value, origins) : /^data:image\//i.test(value))) element.attribs[attribute] = value;
114
+ else {
115
+ delete element.attribs[attribute];
116
+ if (value !== void 0) unavailable.add(path);
117
+ }
118
+ }
119
+ };
120
+ const fillElement = (element, stack) => {
121
+ const each = take(element, names.each);
122
+ if (each !== void 0) {
123
+ const list = resolve(each, stack);
124
+ if (Array.isArray(list)) return list.flatMap((item) => fillElement(cloneNode(element, true), [...stack, item]));
125
+ unavailable.add(each);
126
+ return [];
127
+ }
128
+ if (!applies(element, stack)) return [];
129
+ applyWidth(element, stack);
130
+ applyValue(element, stack);
131
+ applyUrls(element, stack);
132
+ element.children = element.children.flatMap((child) => {
133
+ if (!isTag(child)) return [child];
134
+ return fillElement(child, stack).map((filled) => {
135
+ filled.parent = element;
136
+ return filled;
137
+ });
138
+ });
139
+ return [element];
140
+ };
141
+ document.children = document.children.flatMap((node) => {
142
+ if (!isTag(node)) return [node];
143
+ return fillElement(node, [options.data]).map((filled) => {
144
+ filled.parent = document;
145
+ return filled;
146
+ });
147
+ });
148
+ return {
149
+ html: serialize(document),
150
+ unavailable: [...unavailable],
151
+ values
152
+ };
153
+ }
154
+ //#endregion
155
+ export { BINDINGS, bindingNames, fill, hasBindings };
@@ -0,0 +1,8 @@
1
+ import { REFUSED_ELEMENTS, SanitizeOptions, findActiveContent, sanitize } from "./sanitize.js";
2
+ import { BINDINGS, FillOptions, Filled, bindingNames, fill, hasBindings } from "./bindings.js";
3
+ //#region src/index.d.ts
4
+ export type HtmlKind = 'plain' | 'live-data' | 'scripted' | 'refused';
5
+ export declare function classify(html: string, prefix: string): HtmlKind;
6
+ export declare function searchText(html: string): string;
7
+ //#endregion
8
+ export { BINDINGS, type FillOptions, type Filled, REFUSED_ELEMENTS, type SanitizeOptions, bindingNames, fill, findActiveContent, hasBindings, sanitize };
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ import { REFUSED_ELEMENTS, elements, findActiveContent, parse, sanitize } from "./sanitize.js";
2
+ import { BINDINGS, bindingNames, fill, hasBindings } from "./bindings.js";
3
+ //#region src/index.ts
4
+ function classify(html, prefix) {
5
+ const scripted = elements(parse(html).children).some((element) => element.name.toLowerCase() === "script");
6
+ const bound = hasBindings(html, prefix);
7
+ if (scripted && bound) return "refused";
8
+ if (scripted) return "scripted";
9
+ return bound ? "live-data" : "plain";
10
+ }
11
+ function searchText(html) {
12
+ return html.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
13
+ }
14
+ //#endregion
15
+ export { BINDINGS, REFUSED_ELEMENTS, bindingNames, classify, fill, findActiveContent, hasBindings, sanitize, searchText };
@@ -0,0 +1,11 @@
1
+ import "domhandler";
2
+ //#region src/sanitize.d.ts
3
+ export declare const REFUSED_ELEMENTS: Set<string>;
4
+ export interface SanitizeOptions {
5
+ linkOrigins?: Iterable<string>;
6
+ keepScripts?: boolean;
7
+ refuseElements?: Iterable<string>;
8
+ }
9
+ export declare function findActiveContent(html: string, options?: SanitizeOptions): string[];
10
+ export declare function sanitize(html: string, options?: SanitizeOptions): string;
11
+ //#endregion
@@ -0,0 +1,152 @@
1
+ import { isTag } from "domhandler";
2
+ import render from "dom-serializer";
3
+ import { parseDocument } from "htmlparser2";
4
+ //#region src/sanitize.ts
5
+ const REFUSED_ELEMENTS = /* @__PURE__ */ new Set([
6
+ "script",
7
+ "iframe",
8
+ "frame",
9
+ "frameset",
10
+ "object",
11
+ "embed",
12
+ "applet",
13
+ "base",
14
+ "portal",
15
+ "link",
16
+ "form",
17
+ "input",
18
+ "button",
19
+ "select",
20
+ "textarea"
21
+ ]);
22
+ const REFUSED_SVG_ELEMENTS = /* @__PURE__ */ new Set([
23
+ "script",
24
+ "animate",
25
+ "set",
26
+ "animatetransform",
27
+ "animatemotion",
28
+ "foreignobject"
29
+ ]);
30
+ const REFUSED_ATTRIBUTES = /* @__PURE__ */ new Set([
31
+ "srcdoc",
32
+ "formaction",
33
+ "action"
34
+ ]);
35
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
36
+ "href",
37
+ "xlink:href",
38
+ "src",
39
+ "srcset",
40
+ "poster",
41
+ "background",
42
+ "data",
43
+ "cite",
44
+ "longdesc",
45
+ "ping"
46
+ ]);
47
+ const DATA_IMAGE = /^data:image\/(?:png|jpeg|gif|webp|svg\+xml)(?:[;,])/i;
48
+ function parse(html) {
49
+ return parseDocument(html, {
50
+ lowerCaseAttributeNames: true,
51
+ recognizeSelfClosing: true
52
+ });
53
+ }
54
+ function serialize(node) {
55
+ return render(node, { encodeEntities: "utf8" });
56
+ }
57
+ function elements(nodes) {
58
+ const found = [];
59
+ const walk = (list) => {
60
+ for (const node of list) {
61
+ if (!isTag(node)) continue;
62
+ found.push(node);
63
+ walk(node.children);
64
+ }
65
+ };
66
+ walk(nodes);
67
+ return found;
68
+ }
69
+ function insideSvg(element) {
70
+ for (let parent = element.parent; parent; parent = parent.parent) if (isTag(parent) && parent.name.toLowerCase() === "svg") return true;
71
+ return false;
72
+ }
73
+ function normalizeUrl(value) {
74
+ return [...value].filter((c) => c.charCodeAt(0) > 32 && c.charCodeAt(0) !== 127).join("").toLowerCase();
75
+ }
76
+ function origins(values) {
77
+ const set = /* @__PURE__ */ new Set();
78
+ for (const value of values ?? []) try {
79
+ const url = new URL(value);
80
+ if (url.protocol === "https:") set.add(url.origin.toLowerCase());
81
+ } catch {}
82
+ return set;
83
+ }
84
+ function safeUrl(attribute, value, allowed) {
85
+ const url = normalizeUrl(value);
86
+ if (attribute === "href" || attribute === "xlink:href") {
87
+ if (url.startsWith("#")) return true;
88
+ try {
89
+ const parsed = new URL(url);
90
+ return parsed.protocol === "https:" && allowed.has(parsed.origin);
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+ if (attribute === "srcset") return /^data:image\/(?:png|jpeg|gif|webp|svg\+xml)(?:;[^,]*)?,[^,]*$/i.test(url);
96
+ if (attribute === "src" || attribute === "poster") return DATA_IMAGE.test(url);
97
+ return false;
98
+ }
99
+ function safeStyle(value) {
100
+ const matches = [...value.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)];
101
+ if ((value.match(/url\(/gi)?.length ?? 0) !== matches.length) return false;
102
+ return matches.every((match) => normalizeUrl(match[2] ?? "").startsWith("data:image/"));
103
+ }
104
+ function refusedStyleElement(element) {
105
+ if (element.name.toLowerCase() !== "style") return false;
106
+ const text = element.children.map((child) => "data" in child ? child.data : "").join("");
107
+ return /@import/i.test(text) || !safeStyle(text);
108
+ }
109
+ function refusedElement(element, refused, keepScripts) {
110
+ const name = element.name.toLowerCase();
111
+ if (name === "script") return !keepScripts;
112
+ if (refusedStyleElement(element)) return true;
113
+ if (refused.has(name)) return true;
114
+ if (insideSvg(element) && REFUSED_SVG_ELEMENTS.has(name)) return true;
115
+ return name === "meta" && Object.keys(element.attribs).some((attribute) => attribute.toLowerCase() === "http-equiv");
116
+ }
117
+ function refusedAttribute(name, value, allowed, keepScripts) {
118
+ const attribute = name.toLowerCase();
119
+ if (attribute.startsWith("on")) return !keepScripts;
120
+ return REFUSED_ATTRIBUTES.has(attribute) || URL_ATTRIBUTES.has(attribute) && !safeUrl(attribute, value, allowed) || attribute === "style" && !safeStyle(value);
121
+ }
122
+ function refusedSet(options) {
123
+ return new Set([...REFUSED_ELEMENTS, ...options.refuseElements ?? []].map((name) => name.toLowerCase()));
124
+ }
125
+ function findActiveContent(html, options = {}) {
126
+ const allowed = origins(options.linkOrigins);
127
+ const refused = refusedSet(options);
128
+ const keepScripts = options.keepScripts ?? false;
129
+ const found = [];
130
+ for (const element of elements(parse(html).children)) {
131
+ if (refusedElement(element, refused, keepScripts)) found.push(`<${element.name}>`);
132
+ for (const [name, value] of Object.entries(element.attribs)) if (refusedAttribute(name, value, allowed, keepScripts)) found.push(`${element.name}[${name}]`);
133
+ }
134
+ return found;
135
+ }
136
+ function sanitize(html, options = {}) {
137
+ const allowed = origins(options.linkOrigins);
138
+ const refused = refusedSet(options);
139
+ const keepScripts = options.keepScripts ?? false;
140
+ const document = parse(html);
141
+ const prune = (nodes) => nodes.filter((node) => {
142
+ if (!isTag(node)) return true;
143
+ if (refusedElement(node, refused, keepScripts)) return false;
144
+ for (const [name, value] of Object.entries(node.attribs)) if (refusedAttribute(name, value, allowed, keepScripts)) delete node.attribs[name];
145
+ node.children = prune(node.children);
146
+ return true;
147
+ });
148
+ document.children = prune(document.children);
149
+ return serialize(document);
150
+ }
151
+ //#endregion
152
+ export { REFUSED_ELEMENTS, elements, findActiveContent, parse, sanitize, serialize };
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@segnavia/html",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/modstudio/segnavia.git",
9
+ "directory": "packages/html"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "sideEffects": false,
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "@segnavia/source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "htmlparser2": "^10.0.0",
30
+ "domhandler": "^5.0.3",
31
+ "dom-serializer": "^2.0.0"
32
+ }
33
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.