@3kles/richtext-formats 0.0.0-stage → 1.1.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,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # @3kles/richtext-formats
2
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.
3
+ Convert between the native 3KLES AST, a restricted HTML profile, and plain text. This package is independent of Angular and DOM APIs. Server-side document validation is still required.
4
+
5
+ ## Public API
6
+
7
+ ```ts
8
+ import {
9
+ importHtml,
10
+ importHtmlFragment,
11
+ exportHtml,
12
+ importPlainText,
13
+ exportPlainText,
14
+ extractSelection,
15
+ exportSelectionHtml,
16
+ exportSelectionPlainText,
17
+ } from '@3kles/richtext-formats';
18
+
19
+ const imported = importHtml('<p>Hello <strong>everyone</strong></p>');
20
+ if (imported.ok) {
21
+ const document = imported.value;
22
+ const exported = exportHtml(document);
23
+ // imported.diagnostics describes removals, repairs, and normalization.
24
+ // imported.lossy is true when conversion detects a loss.
25
+ }
26
+
27
+ const fragment = importHtmlFragment('<em>text to insert</em>', {
28
+ onLoss: 'reject',
29
+ });
30
+ if (fragment.ok) {
31
+ const { document, inline } = fragment.value;
32
+ // Pass document and inline to the insertion transaction.
33
+ }
34
+ ```
35
+
36
+ The functions validate `unknown` content inputs and return `FormatResult<T>`. Success includes `value`, `lossy`, and `diagnostics`. Failure contains diagnostics only. The default, `onLoss: 'sanitize'`, retains accepted content and reports removals. `onLoss: 'reject'` rejects any loss warning. Diagnostics use stable codes and paths and omit source attribute values.
37
+
38
+ `FormatOptions` accepts the model limits and additional link policy from `@3kles/richtext-core`, plus `htmlLimits` and `onLoss`. The additional policy can restrict any link destination accepted by the core.
39
+
40
+ `importHtmlFragment` returns `{ document, inline }`. `inline` is true when the source has no accepted block boundary. An explicit paragraph, heading, list, blockquote, or code block keeps the fragment in block form, even when there is only one block. The insertion command uses this metadata to preserve boundaries and the current document's suffix. Conversion leaves editor state untouched.
41
+
42
+ `extractSelection(document, selection)` creates a canonical fragment. `exportSelectionHtml` exports only that fragment, using inline HTML for a selection inside a paragraph or heading. Selections across blocks keep list and blockquote ancestors. Ordered lists start at the number of the first selected item. Positions must belong to the document and follow the UTF-16 boundaries the core validates. Empty and gap selections export an empty string. Node selections support blocks, list items, and line breaks. Invalid structural metadata causes an explicit failure.
43
+
44
+ ## HTML v1 profile
45
+
46
+ | Model | Accepted or exported HTML |
47
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
48
+ | Paragraph | `p`. Import also accepts `div` as a block container. |
49
+ | Headings 1 through 6 | `h1` through `h6` |
50
+ | Bold, italic, underline, strikethrough, code | `strong`/`b`, `em`/`i`, `u`, `s`/`strike`/`del`, `code` |
51
+ | Link | `a[href][title]` with validation of the decoded URL |
52
+ | Hard break | `br` |
53
+ | Nested lists | `ul`, `ol[start]`, `li` |
54
+ | Blockquote | `blockquote` |
55
+ | Code block | `pre` and its text content. `code[data-language]` or `code[class="language-…"]` specifies the language. |
56
+
57
+ Export is deterministic and escapes text and attributes. It emits `strong`, `em`, and `s` as canonical forms. Code blocks use `pre > code` with `data-language` when available. List starts are safe integers, including zero and negative values. Empty lists receive an empty item, and list items begin with a paragraph as required by the core schema.
58
+
59
+ Ordinary HTML flow collapses ASCII whitespace and strips whitespace at block boundaries while preserving nonbreaking spaces and Unicode characters. Code blocks preserve lines and spaces subject to HTML5 parser normalization. Export can add the inert marker `span[data-rt-whitespace="preserve"]` to preserve exact AST spaces and tabs through a round trip. An external HTML consumer needs appropriate CSS to display them. The marker carries no styles. Link titles containing CR, LF, or tabs use numeric character references in attributes. The profile rejects NUL and isolated surrogates. HTML5 cannot represent NUL faithfully.
60
+
61
+ Unrecognized containers are unwrapped with a diagnostic. Scripts, styles, templates, SVG and MathML content, frames, objects, forms, media, and tables are removed with their subtrees. The converter removes all attributes outside the allowlist, including event handlers, styles, IDs, network attributes, and `srcdoc`. It omits comments and metadata without content. The HTML5 parser may rearrange malformed input before the allowlist runs and reports its repairs. Notices about noncanonical HTML characters are informational because those characters do not always cause model loss.
62
+
63
+ Plain text separates blocks and list items with LF. Import preserves blank lines, including a final blank line, and normalizes CRLF and CR to LF. Both directions reject NUL. Export reports loss of marks, links, and rich structures, including ambiguity between a hard break and a paragraph boundary. Bullets and numbering are omitted. Selection export reads only the selected blocks. Paragraphs needed to reconstruct a valid HTML fragment produce no additional text lines.
64
+
65
+ ## Trust boundary and resource limits
66
+
67
+ `parse5.parseFragment` parses HTML into a JavaScript tree without using `DOMParser`, the live DOM, a third-party editor, or the network. The application renders the validated canonical AST. Use converted HTML strings in an HTML body context only. JavaScript, CSS, URL, and attribute contexts require their own handling. External transformations after conversion can invalidate its guarantees.
68
+
69
+ The core URL policy allows absolute HTTP, HTTPS, and mailto URLs and rejects unsafe characters and control characters after HTML decoding. It checks protocols and characters. Full WHATWG/IDNA host validation and destination checks are outside its scope. Import removes relative links and other protocols without fetching any URL.
70
+
71
+ Complete template destinations such as `${context.url}` are also supported. Each dot-separated segment contains ASCII letters, digits, underscores, or hyphens. Exports preserve the literal template in the link's `href`. The editor and preview expose the text without a live `href`. Resolve template destinations in the consuming application and validate the resulting URLs before presenting the exported HTML as navigable content.
72
+
73
+ | Default HTML limit | Value |
74
+ | ------------------------------- | --------: |
75
+ | Source length in UTF-16 units | 8,000,000 |
76
+ | Nodes | 100,000 |
77
+ | Depth | 128 |
78
+ | Text in UTF-16 units | 1,000,000 |
79
+ | Attributes per element | 32 |
80
+ | Attribute name and value length | 16,384 |
81
+ | Output length | 8,000,000 |
82
+ | Retained diagnostics | 200 |
83
+
84
+ The converter checks source length before parsing. A bounded tree adapter stops node and text allocations at their limits and rejects elements that exceed the attribute and depth budgets. It then walks the tree iteratively to check the limits before recursive conversion. The maximum configurable depth is 512. Canonical schema budgets also apply after conversion. Fatal limit errors are reported even after the warning budget is exhausted. These limits bound work and memory. Runtime still varies, and conversion runs in the same process as the caller.
85
+
86
+ Validate documents again on the server and apply server-side permissions, quotas, and display rules. Keep the canonical JSON and the original source before migration to review any loss. This profile covers the structures above. CSS fidelity, tables, images, forms, and third-party extensions are outside its scope. Automated security, round-trip, and integration browser tests complement broader platform validation and independent security review.
87
+
88
+ ## Tiptap data adapter
89
+
90
+ `importTiptapJson(source, options)` is an original adapter independent of the HTML parser, Tiptap, and ProseMirror. Pass the data object returned by `getJSON()` and select its profile explicitly. The adapter handles source data only, with no editor instance or history. It rejects serialized strings and native envelopes.
91
+
92
+ ```ts
93
+ import { importTiptapJson } from '@3kles/richtext-formats';
94
+
95
+ const converted = importTiptapJson(sourceObject, {
96
+ profile: 'tiptap-3-starterkit',
97
+ onLoss: 'reject', // Default policy.
98
+ });
99
+ if (converted.ok) {
100
+ const nativeDocument = converted.value;
101
+ // Store the source and conversion report separately before activating the document in the host.
102
+ }
103
+ ```
104
+
105
+ The required profile describes `doc`, `paragraph`, `text`, `heading` levels 1 through 6, `hardBreak`, `bulletList`, `orderedList`, `listItem`, `blockquote`, `codeBlock`, and the `bold`, `italic`, `underline`, `strike`, `code`, and `link` marks. This subset of StarterKit 3 was checked against data from the isolated 3.34.0 reference. Source JSON does not automatically include its version, so consumers select the applicable profile. [StarterKit 3](https://tiptap.dev/docs/editor/extensions/functionality/starterkit) · [Link](https://tiptap.dev/docs/editor/extensions/marks/link)
106
+
107
+ Unsupported nodes, marks, properties, and attributes produce diagnostics with source paths. The default `onLoss: 'reject'` returns failure without a partial document. Explicitly set `onLoss: 'sanitize'` to remove an unknown node, including an atomic one, with its **entire subtree** and a warning. Its attributes do not generate replacement text. The result remains `lossy: true`. Both policies reject structurally malformed input. The native schema reports the StarterKit `horizontalRule` node as unsupported.
108
+
109
+ List starts are safe integers. `orderedList.type` values of `null`, an empty string, and `'1'` match native numbering. Other values are reported as losses. The adapter preserves `codeBlock.language` and `link.title` when the native model can represent them. Links follow the core destination rules and can be restricted further by `linkPolicy`. Empty or null link metadata and `target: '_self'` match the model's default behavior. The reference's default JSON includes `target: '_blank'` and nonempty `rel`, which the AST cannot represent. Strict import rejects them, and sanitizing import reports their removal. Nonempty styles or classes and marks on unsupported positions, including `hardBreak` and `codeBlock`, are also reported as losses.
110
+
111
+ An iterative inspection captures own data properties before recursive conversion. It rejects cycles, accessors, hidden or symbol properties, sparse arrays, non-JSON values, and invalid Unicode. The adapter preserves the source. Diagnostic paths identify source fields and omit text, URLs, and attribute values. A host-supplied policy runs as trusted JavaScript in the same process.
112
+
113
+ `migrationLimits` sets the following source limits. `DocumentOptions.limits` then applies to the native model. Counts include each occurrence of a shared object, as after JSON serialization. Depth includes `content`, `marks`, and `attrs` objects and arrays.
114
+
115
+ | Default migration limit | Value |
116
+ | --------------------------------------------------- | --------------------------: |
117
+ | JSON container depth | 128, configurable up to 512 |
118
+ | Source JSON values, including containers and fields | 100,000 |
119
+ | Total strings and property names in UTF-16 units | 1,000,000 |
120
+ | Properties per object | 32 |
121
+ | Length of an attribute name or string value | 16,384 |
122
+ | Retained diagnostics | 200 |
123
+
124
+ Long paragraph and code text counts toward the total text budget. The adapter expects a parsed object. Services receiving bytes must enforce their transport limit **before** `JSON.parse`, then validate again on the server. These tests cover the adapter profile only. Production data migration, application parity, and reverse conversion need separate work. [Migration contracts](../../docs/migration.md)
125
+
126
+ ## Dependencies and verification
127
+
128
+ The runtime graph is `@3kles/richtext-formats → @3kles/richtext-core` and `@3kles/richtext-formats → parse5 8.1.1 → entities ^9.0.0`, resolved here to `entities` 9.0.0. `parse5` is an MIT-licensed HTML5 parser. `entities` is a BSD-2-Clause encoder and decoder. Include both licenses when redistributing them. The stable version and licenses were checked against npm metadata and installed package files on November 17, 2026.
129
+
130
+ [parse5 API](https://parse5.js.org/) · [parseFragment](https://parse5.js.org/functions/parse5.parseFragment.html) · [parse5 tree adapters](https://parse5.js.org/interfaces/parse5.TreeAdapter.html) · [parse5 license](https://github.com/inikulin/parse5/blob/master/LICENSE) · [entities](https://github.com/fb55/entities) · [WHATWG HTML parsing rules](https://html.spec.whatwg.org/multipage/parsing.html)
131
+
132
+ Run these commands from the workspace root.
133
+
134
+ ```sh
135
+ npx tsc -b projects/richtext-formats/tsconfig.lib.json
136
+ npx tsc -p projects/richtext-formats/tsconfig.spec.json
137
+ node --test .cache/formats-tests/projects/richtext-formats/src/lib/formats.spec.js
138
+ node --test .cache/formats-tests/projects/richtext-formats/src/lib/tiptap-import.spec.js
139
+ ```
140
+
141
+ Tests cover HTML and migration JSON blocks and marks, selections and fragments, nested lists, entities, unsafe URLs, malformed input and mutation XSS, limits, cycles and accessors, Unicode, and generated stability and round-trip properties. Workspace checks also include this package. Reference-engine comparisons run in isolated tooling.
@@ -0,0 +1,19 @@
1
+ import type { DocumentNode } from '@3kles/richtext-core';
2
+ import type { FormatDiagnostic, FormatDiagnosticCode, FormatOptions, FormatResult, HtmlLimits } from './types.js';
3
+ export declare class FormatLimitError extends Error {
4
+ }
5
+ export declare class FormatContext {
6
+ readonly options: FormatOptions;
7
+ readonly diagnostics: FormatDiagnostic[];
8
+ readonly limits: HtmlLimits;
9
+ lossy: boolean;
10
+ private truncated;
11
+ private failed;
12
+ constructor(options: FormatOptions);
13
+ add(code: FormatDiagnosticCode, severity: FormatDiagnostic['severity'], path: readonly (string | number)[], message: string): void;
14
+ validate(input: unknown): DocumentNode | undefined;
15
+ private coreDiagnostic;
16
+ finish<T>(value: T): FormatResult<T>;
17
+ failure<T>(): FormatResult<T>;
18
+ }
19
+ export declare function formatOperation<T>(options: FormatOptions, operation: (context: FormatContext) => FormatResult<T>): FormatResult<T>;
package/lib/context.js ADDED
@@ -0,0 +1,85 @@
1
+ import { validateDocument } from '@3kles/richtext-core';
2
+ import { DEFAULT_HTML_LIMITS } from './types.js';
3
+ export class FormatLimitError extends Error {
4
+ }
5
+ export class FormatContext {
6
+ options;
7
+ diagnostics = [];
8
+ limits;
9
+ lossy = false;
10
+ truncated = false;
11
+ failed = false;
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.limits = { ...DEFAULT_HTML_LIMITS, ...options.htmlLimits };
15
+ for (const value of Object.values(this.limits)) {
16
+ if (!Number.isSafeInteger(value) || value < 1) {
17
+ throw new FormatLimitError('Format limits must be positive safe integers.');
18
+ }
19
+ }
20
+ // Conversion uses recursion only after an iterative bounded tree inspection.
21
+ if (this.limits.maxDepth > 512)
22
+ throw new FormatLimitError('HTML depth cannot exceed 512.');
23
+ }
24
+ add(code, severity, path, message) {
25
+ if (severity === 'warning')
26
+ this.lossy = true;
27
+ if (severity === 'error')
28
+ this.failed = true;
29
+ if (this.diagnostics.length >= this.limits.maxDiagnostics) {
30
+ const summarySeverity = this.failed ? 'error' : this.lossy ? 'warning' : 'info';
31
+ if (!this.truncated || this.diagnostics.at(-1)?.severity !== summarySeverity) {
32
+ this.truncated = true;
33
+ this.diagnostics[this.diagnostics.length - 1] = Object.freeze({
34
+ code: 'diagnosticsTruncated',
35
+ severity: summarySeverity,
36
+ path: Object.freeze([]),
37
+ message: 'Additional format diagnostics were omitted.',
38
+ });
39
+ }
40
+ return;
41
+ }
42
+ this.diagnostics.push(Object.freeze({ code, severity, path: Object.freeze([...path]), message }));
43
+ }
44
+ validate(input) {
45
+ const result = validateDocument(input, this.options);
46
+ for (const diagnostic of result.diagnostics)
47
+ this.coreDiagnostic(diagnostic);
48
+ return result.ok ? result.value : undefined;
49
+ }
50
+ coreDiagnostic(diagnostic) {
51
+ this.add(diagnostic.severity === 'error' ? 'invalidDocument' : 'normalized', diagnostic.severity, diagnostic.path, diagnostic.message);
52
+ }
53
+ finish(value) {
54
+ if (this.failed || (this.lossy && this.options.onLoss === 'reject')) {
55
+ return this.failure();
56
+ }
57
+ return Object.freeze({
58
+ ok: true,
59
+ value,
60
+ lossy: this.lossy,
61
+ diagnostics: Object.freeze([...this.diagnostics]),
62
+ });
63
+ }
64
+ failure() {
65
+ return Object.freeze({ ok: false, diagnostics: Object.freeze([...this.diagnostics]) });
66
+ }
67
+ }
68
+ export function formatOperation(options, operation) {
69
+ let context;
70
+ try {
71
+ context = new FormatContext(options);
72
+ return operation(context);
73
+ }
74
+ catch (error) {
75
+ const diagnostic = Object.freeze({
76
+ code: error instanceof FormatLimitError ? 'resourceLimit' : 'invalidInput',
77
+ severity: 'error',
78
+ path: Object.freeze([]),
79
+ message: error instanceof FormatLimitError ? error.message : 'The format operation could not accept this input.',
80
+ });
81
+ // A fatal error remains visible even after the warning budget is exhausted.
82
+ return Object.freeze({ ok: false, diagnostics: Object.freeze([...(context?.diagnostics ?? []), diagnostic]) });
83
+ }
84
+ }
85
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/lib/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,OAAO,gBAAiB,SAAQ,KAAK;CAAG;AAE9C,MAAM,OAAO,aAAa;IAOD;IANZ,WAAW,GAAuB,EAAE,CAAC;IACrC,MAAM,CAAa;IAC5B,KAAK,GAAG,KAAK,CAAC;IACN,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEvB,YAAqB,OAAsB;QAAtB,YAAO,GAAP,OAAO,CAAe;QACvC,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,mBAAmB,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;QAChE,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;gBAC5C,MAAM,IAAI,gBAAgB,CAAC,+CAA+C,CAAC,CAAC;YAChF,CAAC;QACL,CAAC;QACD,6EAA6E;QAC7E,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,GAAG;YAAE,MAAM,IAA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G,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC;QACrC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACtB,MAAM,UAAU,GAAqB,MAAM,CAAC,MAAM,CAAC;YAC/C,IAAI,EAAE,KAAK,YAAY,gBAAgB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,cAAc;YAC1E,QAAQ,EAAE,OAAO;YACjB,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;YACvB,OAAO,EACH,KAAK,YAAY,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,mDAAmD;SAC9G,CAAC,CAAC;QACH,4EAA4E;QAC5E,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC;IACnH,CAAC;AACL,CAAC","sourcesContent":["import type { Diagnostic, DocumentNode } from '@3kles/richtext-core';\nimport { validateDocument } from '@3kles/richtext-core';\nimport type { FormatDiagnostic, FormatDiagnosticCode, FormatOptions, FormatResult, HtmlLimits } from './types.js';\nimport { DEFAULT_HTML_LIMITS } from './types.js';\n\nexport class FormatLimitError extends Error {}\n\nexport class FormatContext {\n readonly diagnostics: FormatDiagnostic[] = [];\n readonly limits: HtmlLimits;\n lossy = false;\n private truncated = false;\n private failed = false;\n\n constructor(readonly options: FormatOptions) {\n this.limits = { ...DEFAULT_HTML_LIMITS, ...options.htmlLimits };\n for (const value of Object.values(this.limits)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new FormatLimitError('Format limits must be positive safe integers.');\n }\n }\n // Conversion uses recursion only after an iterative bounded tree inspection.\n if (this.limits.maxDepth > 512) throw new FormatLimitError('HTML depth cannot exceed 512.');\n }\n\n add(\n code: FormatDiagnosticCode,\n severity: FormatDiagnostic['severity'],\n path: readonly (string | number)[],\n message: string,\n ): void {\n if (severity === 'warning') this.lossy = true;\n if (severity === 'error') this.failed = true;\n if (this.diagnostics.length >= this.limits.maxDiagnostics) {\n const summarySeverity = this.failed ? 'error' : this.lossy ? 'warning' : 'info';\n if (!this.truncated || this.diagnostics.at(-1)?.severity !== summarySeverity) {\n this.truncated = true;\n this.diagnostics[this.diagnostics.length - 1] = Object.freeze({\n code: 'diagnosticsTruncated',\n severity: summarySeverity,\n path: Object.freeze([]),\n message: 'Additional format diagnostics were omitted.',\n });\n }\n return;\n }\n this.diagnostics.push(Object.freeze({ code, severity, path: Object.freeze([...path]), message }));\n }\n\n validate(input: unknown): DocumentNode | undefined {\n const result = validateDocument(input, this.options);\n for (const diagnostic of result.diagnostics) this.coreDiagnostic(diagnostic);\n return result.ok ? result.value : undefined;\n }\n\n private coreDiagnostic(diagnostic: Diagnostic): void {\n this.add(\n diagnostic.severity === 'error' ? 'invalidDocument' : 'normalized',\n diagnostic.severity,\n diagnostic.path,\n diagnostic.message,\n );\n }\n\n finish<T>(value: T): FormatResult<T> {\n if (this.failed || (this.lossy && this.options.onLoss === 'reject')) {\n return this.failure();\n }\n return Object.freeze({\n ok: true,\n value,\n lossy: this.lossy,\n diagnostics: Object.freeze([...this.diagnostics]),\n });\n }\n\n failure<T>(): FormatResult<T> {\n return Object.freeze({ ok: false, diagnostics: Object.freeze([...this.diagnostics]) });\n }\n}\n\nexport function formatOperation<T>(\n options: FormatOptions,\n operation: (context: FormatContext) => FormatResult<T>,\n): FormatResult<T> {\n let context: FormatContext | undefined;\n try {\n context = new FormatContext(options);\n return operation(context);\n } catch (error: unknown) {\n const diagnostic: FormatDiagnostic = Object.freeze({\n code: error instanceof FormatLimitError ? 'resourceLimit' : 'invalidInput',\n severity: 'error',\n path: Object.freeze([]),\n message:\n error instanceof FormatLimitError ? error.message : 'The format operation could not accept this input.',\n });\n // A fatal error remains visible even after the warning budget is exhausted.\n return Object.freeze({ ok: false, diagnostics: Object.freeze([...(context?.diagnostics ?? []), diagnostic]) });\n }\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { DocumentNode } from '@3kles/richtext-core';
2
+ import type { FormatContext } from './context.js';
3
+ import type { FormatOptions, FormatResult } from './types.js';
4
+ export declare function escapeHtmlText(text: string): string;
5
+ export declare function escapeHtmlAttribute(text: string): string;
6
+ /** Internal writer accepts only an already validated, canonical model. */
7
+ export declare function writeHtml(document: DocumentNode, context: FormatContext, inline?: boolean): string;
8
+ export declare function exportHtml(document: unknown, options?: FormatOptions): FormatResult<string>;
@@ -0,0 +1,128 @@
1
+ import { FormatLimitError, formatOperation } from './context.js';
2
+ export function escapeHtmlText(text) {
3
+ if (text.includes('\0'))
4
+ throw new TypeError('HTML cannot represent NUL without loss.');
5
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
6
+ }
7
+ export function escapeHtmlAttribute(text) {
8
+ return escapeHtmlText(text)
9
+ .replaceAll('"', '&quot;')
10
+ .replaceAll("'", '&#39;')
11
+ .replaceAll('\r', '&#13;')
12
+ .replaceAll('\n', '&#10;')
13
+ .replaceAll('\t', '&#9;');
14
+ }
15
+ class HtmlWriter {
16
+ context;
17
+ parts = [];
18
+ length = 0;
19
+ constructor(context) {
20
+ this.context = context;
21
+ }
22
+ append(value) {
23
+ this.length += value.length;
24
+ if (this.length > this.context.limits.maxOutputLength)
25
+ throw new FormatLimitError('HTML output length exceeds its limit.');
26
+ this.parts.push(value);
27
+ }
28
+ mark(mark) {
29
+ switch (mark.type) {
30
+ case 'bold':
31
+ return ['<strong>', '</strong>'];
32
+ case 'italic':
33
+ return ['<em>', '</em>'];
34
+ case 'underline':
35
+ return ['<u>', '</u>'];
36
+ case 'strike':
37
+ return ['<s>', '</s>'];
38
+ case 'code':
39
+ return ['<code>', '</code>'];
40
+ case 'link': {
41
+ const title = mark.title === undefined ? '' : ` title="${escapeHtmlAttribute(mark.title)}"`;
42
+ return [`<a href="${escapeHtmlAttribute(mark.href)}"${title}>`, '</a>'];
43
+ }
44
+ }
45
+ }
46
+ inline(nodes) {
47
+ for (const node of nodes) {
48
+ if (node.type === 'hardBreak') {
49
+ this.append('<br>');
50
+ continue;
51
+ }
52
+ const tags = (node.marks ?? []).map((mark) => this.mark(mark));
53
+ for (const [open] of tags)
54
+ this.append(open);
55
+ // This inert marker retains AST whitespace on reimport; it never enables HTML/CSS execution.
56
+ const preserve = /[\t\f ]/u.test(node.text);
57
+ if (preserve)
58
+ this.append('<span data-rt-whitespace="preserve">');
59
+ this.append(escapeHtmlText(node.text));
60
+ if (preserve)
61
+ this.append('</span>');
62
+ for (const [, close] of [...tags].reverse())
63
+ this.append(close);
64
+ }
65
+ }
66
+ block(node) {
67
+ switch (node.type) {
68
+ case 'paragraph':
69
+ this.append('<p>');
70
+ this.inline(node.children);
71
+ this.append('</p>');
72
+ return;
73
+ case 'heading':
74
+ this.append(`<h${node.level}>`);
75
+ this.inline(node.children);
76
+ this.append(`</h${node.level}>`);
77
+ return;
78
+ case 'codeBlock': {
79
+ const language = node.language === undefined ? '' : ` data-language="${escapeHtmlAttribute(node.language)}"`;
80
+ this.append(`<pre><code${language}>`);
81
+ for (const child of node.children)
82
+ this.append(escapeHtmlText(child.text));
83
+ this.append('</code></pre>');
84
+ return;
85
+ }
86
+ case 'blockquote':
87
+ this.append('<blockquote>');
88
+ for (const child of node.children)
89
+ this.block(child);
90
+ this.append('</blockquote>');
91
+ return;
92
+ case 'bulletList':
93
+ case 'orderedList': {
94
+ const ordered = node.type === 'orderedList';
95
+ this.append(ordered ? `<ol start="${node.start}">` : '<ul>');
96
+ for (const item of node.children) {
97
+ this.append('<li>');
98
+ for (const child of item.children)
99
+ this.block(child);
100
+ this.append('</li>');
101
+ }
102
+ this.append(ordered ? '</ol>' : '</ul>');
103
+ return;
104
+ }
105
+ }
106
+ }
107
+ result() {
108
+ return this.parts.join('');
109
+ }
110
+ }
111
+ /** Internal writer accepts only an already validated, canonical model. */
112
+ export function writeHtml(document, context, inline = false) {
113
+ const writer = new HtmlWriter(context);
114
+ const first = document.children[0];
115
+ if (inline && document.children.length === 1 && first && (first.type === 'paragraph' || first.type === 'heading'))
116
+ writer.inline(first.children);
117
+ else
118
+ for (const block of document.children)
119
+ writer.block(block);
120
+ return writer.result();
121
+ }
122
+ export function exportHtml(document, options = {}) {
123
+ return formatOperation(options, (context) => {
124
+ const validated = context.validate(document);
125
+ return validated ? context.finish(writeHtml(validated, context)) : context.failure();
126
+ });
127
+ }
128
+ //# sourceMappingURL=html-export.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html-export.js","sourceRoot":"","sources":["../../src/lib/html-export.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAGjE,MAAM,UAAU,cAAc,CAAC,IAAY;IACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,yCAAyC,CAAC,CAAC;IACxF,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACzF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC5C,OAAO,cAAc,CAAC,IAAI,CAAC;SACtB,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC;SACzB,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;SACxB,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC;SACzB,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC;SACzB,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,UAAU;IAIiB;IAHZ,KAAK,GAAa,EAAE,CAAC;IAC9B,MAAM,GAAG,CAAC,CAAC;I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CAAC;AACP,CAAC","sourcesContent":["import type { BlockNode, DocumentNode, InlineNode, Mark } from '@3kles/richtext-core';\nimport type { FormatContext } from './context.js';\nimport { FormatLimitError, formatOperation } from './context.js';\nimport type { FormatOptions, FormatResult } from './types.js';\n\nexport function escapeHtmlText(text: string): string {\n if (text.includes('\\0')) throw new TypeError('HTML cannot represent NUL without loss.');\n return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nexport function escapeHtmlAttribute(text: string): string {\n return escapeHtmlText(text)\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&#39;')\n .replaceAll('\\r', '&#13;')\n .replaceAll('\\n', '&#10;')\n .replaceAll('\\t', '&#9;');\n}\n\nclass HtmlWriter {\n private readonly parts: string[] = [];\n private length = 0;\n\n constructor(private readonly context: FormatContext) {}\n\n private append(value: string): void {\n this.length += value.length;\n if (this.length > this.context.limits.maxOutputLength)\n throw new FormatLimitError('HTML output length exceeds its limit.');\n this.parts.push(value);\n }\n\n private mark(mark: Mark): readonly [string, string] {\n switch (mark.type) {\n case 'bold':\n return ['<strong>', '</strong>'];\n case 'italic':\n return ['<em>', '</em>'];\n case 'underline':\n return ['<u>', '</u>'];\n case 'strike':\n return ['<s>', '</s>'];\n case 'code':\n return ['<code>', '</code>'];\n case 'link': {\n const title = mark.title === undefined ? '' : ` title=\"${escapeHtmlAttribute(mark.title)}\"`;\n return [`<a href=\"${escapeHtmlAttribute(mark.href)}\"${title}>`, '</a>'];\n }\n }\n }\n\n inline(nodes: readonly InlineNode[]): void {\n for (const node of nodes) {\n if (node.type === 'hardBreak') {\n this.append('<br>');\n continue;\n }\n const tags = (node.marks ?? []).map((mark) => this.mark(mark));\n for (const [open] of tags) this.append(open);\n // This inert marker retains AST whitespace on reimport; it never enables HTML/CSS execution.\n const preserve = /[\\t\\f ]/u.test(node.text);\n if (preserve) this.append('<span data-rt-whitespace=\"preserve\">');\n this.append(escapeHtmlText(node.text));\n if (preserve) this.append('</span>');\n for (const [, close] of [...tags].reverse()) this.append(close);\n }\n }\n\n block(node: BlockNode): void {\n switch (node.type) {\n case 'paragraph':\n this.append('<p>');\n this.inline(node.children);\n this.append('</p>');\n return;\n case 'heading':\n this.append(`<h${node.level}>`);\n this.inline(node.children);\n this.append(`</h${node.level}>`);\n return;\n case 'codeBlock': {\n const language =\n node.language === undefined ? '' : ` data-language=\"${escapeHtmlAttribute(node.language)}\"`;\n this.append(`<pre><code${language}>`);\n for (const child of node.children) this.append(escapeHtmlText(child.text));\n this.append('</code></pre>');\n return;\n }\n case 'blockquote':\n this.append('<blockquote>');\n for (const child of node.children) this.block(child);\n this.append('</blockquote>');\n return;\n case 'bulletList':\n case 'orderedList': {\n const ordered = node.type === 'orderedList';\n this.append(ordered ? `<ol start=\"${node.start}\">` : '<ul>');\n for (const item of node.children) {\n this.append('<li>');\n for (const child of item.children) this.block(child);\n this.append('</li>');\n }\n this.append(ordered ? '</ol>' : '</ul>');\n return;\n }\n }\n }\n\n result(): string {\n return this.parts.join('');\n }\n}\n\n/** Internal writer accepts only an already validated, canonical model. */\nexport function writeHtml(document: DocumentNode, context: FormatContext, inline = false): string {\n const writer = new HtmlWriter(context);\n const first = document.children[0];\n if (inline && document.children.length === 1 && first && (first.type === 'paragraph' || first.type === 'heading'))\n writer.inline(first.children);\n else for (const block of document.children) writer.block(block);\n return writer.result();\n}\n\nexport function exportHtml(document: unknown, options: FormatOptions = {}): FormatResult<string> {\n return formatOperation(options, (context) => {\n const validated = context.validate(document);\n return validated ? context.finish(writeHtml(validated, context)) : context.failure();\n });\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import type { DocumentNode } from '@3kles/richtext-core';
2
+ import type { FormatOptions, FormatResult, HtmlFragment } from './types.js';
3
+ export declare function importHtmlFragment(input: unknown, options?: FormatOptions): FormatResult<HtmlFragment>;
4
+ export declare function importHtml(input: unknown, options?: FormatOptions): FormatResult<DocumentNode>;