npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@3kles/richtext-formats

v1.4.1

Published

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.

Readme

@3kles/richtext-formats

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.

Public API

import {
    importHtml,
    importHtmlFragment,
    exportHtml,
    importPlainText,
    exportPlainText,
    extractSelection,
    exportSelectionHtml,
    exportSelectionPlainText,
} from '@3kles/richtext-formats';

const imported = importHtml('<p>Hello <strong>everyone</strong></p>');
if (imported.ok) {
    const document = imported.value;
    const exported = exportHtml(document);
    // imported.diagnostics describes removals, repairs, and normalization.
    // imported.lossy is true when conversion detects a loss.
}

const fragment = importHtmlFragment('<em>text to insert</em>', {
    onLoss: 'reject',
});
if (fragment.ok) {
    const { document, inline } = fragment.value;
    // Pass document and inline to the insertion transaction.
}

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.

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.

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.

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.

HTML v1 profile

| Model | Accepted or exported HTML | | -------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | Paragraph | p. Import also accepts div as a block container. | | Headings 1 through 6 | h1 through h6 | | Bold, italic, underline, strikethrough, code | strong/b, em/i, u, s/strike/del, code | | Link | a[href][title] with validation of the decoded URL | | Hard break | br | | Nested lists | ul, ol[start], li | | Blockquote | blockquote | | Code block | pre and its text content. code[data-language] or code[class="language-…"] specifies the language. |

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.

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.

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.

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.

Trust boundary and resource limits

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.

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.

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.

| Default HTML limit | Value | | ------------------------------- | --------: | | Source length in UTF-16 units | 8,000,000 | | Nodes | 100,000 | | Depth | 128 | | Text in UTF-16 units | 1,000,000 | | Attributes per element | 32 | | Attribute name and value length | 16,384 | | Output length | 8,000,000 | | Retained diagnostics | 200 |

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.

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.

Tiptap data adapter

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.

import { importTiptapJson } from '@3kles/richtext-formats';

const converted = importTiptapJson(sourceObject, {
    profile: 'tiptap-3-starterkit',
    onLoss: 'reject', // Default policy.
});
if (converted.ok) {
    const nativeDocument = converted.value;
    // Store the source and conversion report separately before activating the document in the host.
}

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 · Link

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.

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.

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.

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.

| Default migration limit | Value | | --------------------------------------------------- | --------------------------: | | JSON container depth | 128, configurable up to 512 | | Source JSON values, including containers and fields | 100,000 | | Total strings and property names in UTF-16 units | 1,000,000 | | Properties per object | 32 | | Length of an attribute name or string value | 16,384 | | Retained diagnostics | 200 |

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

Dependencies and verification

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.

parse5 API · parseFragment · parse5 tree adapters · parse5 license · entities · WHATWG HTML parsing rules

Run these commands from the workspace root.

npx tsc -b projects/richtext-formats/tsconfig.lib.json
npx tsc -p projects/richtext-formats/tsconfig.spec.json
node --test .cache/formats-tests/projects/richtext-formats/src/lib/formats.spec.js
node --test .cache/formats-tests/projects/richtext-formats/src/lib/tiptap-import.spec.js

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.