Texto enriquecido: editor Tiptap, documentos JSON con lista blanca, render HTML/React sin XSS, texto plano e índice
Instalar
genpm add @core/rich-textQué obtienes
- Código en src/lib/rich-text/, 8 archivos. (23,6 kB)
- Reglas de IA en src/lib/rich-text/AGENTS.md, más archivos de reglas para tu IDE.
README
Este paquete no tiene README.
Esto es exactamente lo que lee tu IA cuando trabaja en src/lib/rich-text. No se añade nada más a su contexto.
@core/rich-text — rules for AI agents
Purpose
Rich text stored as JSON (Tiptap/ProseMirror format), never as HTML. RichTextSchema allowlists nodes (paragraphs,
headings, lists, quotes, code, images from @core/media, YouTube/Vimeo embeds), marks and links (site paths, #,
http(s), mailto, tel). Renders to HTML or React with full escaping, plain text, excerpts, reading time and a table of
contents with stable heading ids. Includes a Tiptap editor component. No tables, no collaboration.
Map
index.ts— server API:RichTextSchema,parseDoc,toHtml,RichText(React),toPlainText,excerpt,readingTime,headings.editor.ts—RichTextEditor(client component,'use client'); import it from.../rich-text/editor.jsonly in client code.doc.ts— schema and link rules.html.ts,react.ts— renderers.text.ts— text helpers.
Integration
- Install the npm deps if GenPM did not (
@tiptap/*,react). - In content schemas use
body: RichTextSchema(with @core/content:defineCollection('posts', { schema: z.object({ title: z.string(), body: RichTextSchema }) })). - Render:
<RichText doc={post.body} resolveImage={(a) => a.mediaId ? imgAttrs(mediaById[a.mediaId]) : null} siteHost="example.com" />(load the media rows first; the resolver is synchronous). Non-React:toHtml(doc, options). - Edit:
<RichTextEditor value={doc} onChange={setDoc} onPickImage={openMediaPicker} labels={…} />in a client component. - Search/SEO:
toPlainText(doc)for @core/search bodies andexcerpt(doc)for descriptions. - Verify: a link
javascript:alert(1)is rejected byparseDoc; rendered HTML has no<script>.
Conventions
- Validate every document coming from a client with
parseDoc(or the collection schema) before saving. - Embeds render as plain links by default; use
embeds: 'iframe'only where the site has consent for third-party video. - Pass
labels/embedLabelwith translated texts; defaults are English.
Don't
- Don't store or render HTML from users; don't use
dangerouslySetInnerHTMLwith document content. - Don't add nodes or marks without extending
NodeSchemaand both renderers. - Don't import
editor.tsin server code (it needs the browser).
# @core/rich-text — rules for AI agents
## Purpose
Rich text stored as JSON (Tiptap/ProseMirror format), never as HTML. `RichTextSchema` allowlists nodes (paragraphs,
headings, lists, quotes, code, images from @core/media, YouTube/Vimeo embeds), marks and links (site paths, `#`,
http(s), mailto, tel). Renders to HTML or React with full escaping, plain text, excerpts, reading time and a table of
contents with stable heading ids. Includes a Tiptap editor component. No tables, no collaboration.
## Map
- `index.ts` — server API: `RichTextSchema`, `parseDoc`, `toHtml`, `RichText` (React), `toPlainText`, `excerpt`, `readingTime`, `headings`.
- `editor.ts` — `RichTextEditor` (client component, `'use client'`); import it from `.../rich-text/editor.js` only in client code.
- `doc.ts` — schema and link rules. `html.ts`, `react.ts` — renderers. `text.ts` — text helpers.
## Integration
1. Install the npm deps if GenPM did not (`@tiptap/*`, `react`).
2. In content schemas use `body: RichTextSchema` (with @core/content: `defineCollection('posts', { schema: z.object({ title: z.string(), body: RichTextSchema }) })`).
3. Render: `<RichText doc={post.body} resolveImage={(a) => a.mediaId ? imgAttrs(mediaById[a.mediaId]) : null} siteHost="example.com" />`
(load the media rows first; the resolver is synchronous). Non-React: `toHtml(doc, options)`.
4. Edit: `<RichTextEditor value={doc} onChange={setDoc} onPickImage={openMediaPicker} labels={…} />` in a client component.
5. Search/SEO: `toPlainText(doc)` for @core/search bodies and `excerpt(doc)` for descriptions.
6. Verify: a link `javascript:alert(1)` is rejected by `parseDoc`; rendered HTML has no `<script>`.
## Conventions
- Validate every document coming from a client with `parseDoc` (or the collection schema) before saving.
- Embeds render as plain links by default; use `embeds: 'iframe'` only where the site has consent for third-party video.
- Pass `labels`/`embedLabel` with translated texts; defaults are English.
## Don't
- Don't store or render HTML from users; don't use `dangerouslySetInnerHTML` with document content.
- Don't add nodes or marks without extending `NodeSchema` and both renderers.
- Don't import `editor.ts` in server code (it needs the browser).
El árbol exacto que se inyectará, tras aplicar .genpmignore. Anclado a
// Render a React (Server Components o cliente) con las mismas reglas que `toHtml`: sin innerHTML.
import { createElement as h, Fragment, type ReactNode } from 'react';
import type { Doc, Mark, Node } from './doc.ts';
import { isSafeHref } from './doc.ts';
import { defaultEmbedLabel, embedUrl, isExternal, type RenderOptions } from './html.ts';
import { headingIds } from './text.ts';
const MARK_TAG = { bold: 'strong', italic: 'em', strike: 's', code: 'code', underline: 'u' } as const;
function withMarks(content: ReactNode, marks: Mark[] | undefined, o: RenderOptions, key: number): ReactNode {
let el = content;
for (const m of marks ?? []) {
if (m.type !== 'link') el = h(MARK_TAG[m.type], null, el);
else if (isSafeHref(m.attrs.href)) {
const ext = isExternal(m.attrs.href, o.siteHost);
el = h('a', { href: m.attrs.href, target: m.attrs.target ?? undefined, rel: ext || m.attrs.target ? (o.externalRel ?? 'noopener noreferrer') : undefined }, el);
}
}
return h(Fragment, { key }, el);
}
/** `<RichText doc={post.body} resolveImage={…} />` */
export function RichText(props: { doc: Doc } & RenderOptions): ReactNode {
const { doc, ...o } = props;
const ids = headingIds(doc);
let hi = 0;
const render = (nodes: Node[] | undefined): ReactNode[] => (nodes ?? []).map((n, i) => node(n, i));
const node = (n: Node, key: number): ReactNode => {
switch (n.type) {
case 'text':
return withMarks(n.text, n.marks, o, key);
case 'paragraph':
return h('p', { key }, render(n.content));
case 'heading':
return h(`h${n.attrs.level}`, { key, id: ids[hi++] }, render(n.content));
case 'bulletList':
return h('ul', { key }, render(n.content));
case 'orderedList':
return h('ol', { key, start: n.attrs?.start }, render(n.content));
case 'listItem':
return h('li', { key }, render(n.content));
case 'blockquote':
return h('blockquote', { key }, render(n.content));
case 'codeBlock':
return h('pre', { key }, h('code', { className: n.attrs?.language ? `language-${n.attrs.language}` : undefined }, render(n.content)));
case 'horizontalRule':
return h('hr', { key });
case 'hardBreak':
return h('br', { key });
case 'image': {
const img = o.resolveImage?.(n.attrs) ?? (n.attrs.src && isSafeHref(n.attrs.src) ? { src: n.attrs.src, alt: n.attrs.alt ?? '' } : null);
if (!img) return null;
return h('figure', { key }, h('img', { ...img, srcSet: img.srcSet, loading: 'lazy', decoding: 'async' }), n.attrs.title ? h('figcaption', null, n.attrs.title) : null);
}
case 'embed': {
const mode = o.embeds ?? 'link';
const src = embedUrl(n.attrs.provider, n.attrs.id, mode);
return mode === 'iframe'
? h('div', { key, className: 'embed' }, h('iframe', { src, title: `${n.attrs.provider} video`, loading: 'lazy', allow: 'encrypted-media; picture-in-picture; fullscreen', referrerPolicy: 'strict-origin-when-cross-origin', sandbox: 'allow-scripts allow-same-origin allow-presentation' }))
: h('p', { key, className: 'embed' }, h('a', { href: src, rel: 'noopener noreferrer', target: '_blank' }, (o.embedLabel ?? defaultEmbedLabel)(n.attrs.provider)));
}
}
};
return h(Fragment, null, render(doc.content));
}
Este paquete no declara servidores MCP.
| Versión | Commit | Publicado | Escaneo |
|---|---|---|---|
| 1.0.1 | c21aca7 | hace 7 horas | escaneo superado |
- genpm
- ninguno
- npm
- @tiptap/extension-image ^3.0.0@tiptap/extension-link ^3.0.0@tiptap/pm ^3.0.0@tiptap/react ^3.0.0@tiptap/starter-kit ^3.0.0react ^19.0.0zod ^4.0.0
- propuesta
- GenPM propone el comando npm y solo lo ejecuta si dices que sí.
- escaneo
- escaneo superado · 0 hallazgos
- commit
- v1.0.1 → c21aca7ae36b2292a82698adfcc11126377ccc9c · verificado tras la descarga
- scripts
- Ninguno. GenPM nunca ejecuta código del paquete.
- licencia
- MIT
- Calidad
- 100/100
- Licencia reconocidacumplido
- AGENTS.md explica su propósitocumplido
- AGENTS.md tiene pasos de integracióncumplido
- AGENTS.md lista convenciones o prohibicionescumplido
- Incluye testscumplido
- Escaneo de seguridad superadocumplido
- Publicado en los últimos 6 mesescumplido
- Publicador verificadocumplido
- Resumen y palabras clavecumplido
- reporte
- ¿Ves algo raro?