@ilamanownuk/blog-kit 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.
@@ -0,0 +1,141 @@
1
+ You are an AI coding agent. Install and wire the npm package `@ilamanownuk/blog-kit` into THIS project, following the rules below exactly. Work step by step, and do not stop after the first working screen: finish the whole checklist.
2
+
3
+ # 0. What the package is
4
+
5
+ `@ilamanownuk/blog-kit` is a Tiptap-based rich-text blog kit (RTL/Persian by default) for React 19 / Next.js. Output is a plain HTML string. It ships:
6
+
7
+ - `@ilamanownuk/blog-kit` -> `RichTextEditor` (client component, already has "use client"), `defaultLabels`, `defaultToolbar`, `toVideoEmbedUrl`, `normalizeLinkUrl`, `isAllowedEmbedSrc`, and types.
8
+ - `@ilamanownuk/blog-kit/renderer` -> `RichContent` (works in Server Components; sanitizes again), `sanitizeRichText`.
9
+ - `@ilamanownuk/blog-kit/server` -> `sanitizeRichText`, `hasRichContent`, `richTextToPlain`, `toVideoEmbedUrl`, `normalizeLinkUrl`, `isAllowedEmbedSrc`, `ALL_EMBED_PROVIDERS` (no React; usable in Next server actions and NestJS).
10
+ - `@ilamanownuk/blog-kit/styles.css` -> all CSS (unlayered, so the default look survives resets/Tailwind preflight), themed with `--bk-*` CSS variables. `styles.layered.css` is the same inside `@layer blog-kit` (use only if the project wants plain utilities to override it).
11
+
12
+ Tiptap, lucide-react and sanitize-html are dependencies of the package. Peer deps: react and react-dom >= 19.
13
+
14
+ # 1. Hard rules (never break these)
15
+
16
+ 1. Do NOT install `@tiptap/*` yourself for this feature. The kit brings its own pinned Tiptap. If the project already has `@tiptap/*` only for an old blog editor that you replace, remove them at the end.
17
+ 2. Do NOT sanitize only on the client. ALWAYS call `sanitizeRichText` from `@ilamanownuk/blog-kit/server` on the server before saving (server action or Nest service), and reject empty content with `hasRichContent`.
18
+ 3. Do NOT render stored HTML with a raw `dangerouslySetInnerHTML`. Use `<RichContent html={...} />` from `@ilamanownuk/blog-kit/renderer`.
19
+ 4. The editor is a client component: use it only inside a file with `"use client"` (or a component imported by one). Never import it into a Server Component directly.
20
+ 5. `allowedEmbeds` MUST be identical in the editor, in `sanitizeRichText`, and in `RichContent`. Put the value in ONE shared constant and import it everywhere (e.g. `export const BLOG_EMBEDS = ["aparat", "youtube"] as const;`). Same for `isAllowedImageSrc`.
21
+ 6. Image URLs must be `https://`. `uploadImage` and `mediaApi` must return https URLs. Anything else is dropped by the sanitizer.
22
+ 7. `placeholder` and `allowedEmbeds` are read once on mount; keep them stable (module constants, not inline-created arrays that change).
23
+ 8. Keep existing stored HTML working. Do NOT migrate data unless the old format is not HTML. If the old content is not HTML (Markdown, JSON), say so and ask before converting.
24
+ 9. Do NOT delete or rewrite the old editor/renderer/sanitizer files until the new ones work (typecheck + build pass and the page was verified). Then replace usages and remove the dead duplicated files.
25
+ 10. Style with `--bk-*` variables, `classNames` and `toolbar` props. Do not edit files inside `node_modules`, and do not copy the package's source into the project.
26
+ 11. Match the project's package manager (pnpm / npm / yarn / bun), code style, path aliases and language of UI strings. Do not upgrade unrelated dependencies.
27
+ 12. Do not invent API. Only use props and functions listed in section 4. If something is missing, say so in the final report instead of faking it.
28
+
29
+ # 2. Step 1: inspect the project (report findings briefly before editing)
30
+
31
+ Find and note:
32
+ - Framework and versions: `next` (App Router or Pages?), `react`, `react-dom` (must be >= 19; if lower, STOP and report), TypeScript, path alias (`@/`).
33
+ - Backend style: Next Server Actions, Route Handlers, or a separate NestJS API (check `services/`, `apps/`, monorepo workspaces).
34
+ - Where blog/post content is stored (Prisma schema, Drizzle, Mongoose, ...). Is the content column an HTML string? Where is content created/updated (actions, controllers, services)?
35
+ - Any existing rich-text editor (grep for `tiptap`, `quill`, `draft`, `ckeditor`, `lexical`, `dangerouslySetInnerHTML`, `sanitize-html`) and its renderer and sanitizer.
36
+ - Media/upload system: upload endpoint or action, storage (S3/local), is there a media library table/API with list + upload? What URL format does it return (must be https)?
37
+ - Styling: Tailwind (v3 or v4?), shadcn, CSS variables for theme, dark mode strategy (`.dark` class or other), main CSS entry file, font.
38
+ - Auth: how admin actions are protected (keep that protection on every new server action).
39
+
40
+ # 3. Step 2: do the integration
41
+
42
+ 1. Install: `<pm> add @ilamanownuk/blog-kit` (use the project's package manager).
43
+ 2. Styles: import `@ilamanownuk/blog-kit/styles.css` once, in the global CSS entry or root layout.
44
+ - Tailwind v4 (`@import "tailwindcss"` in CSS): `@import "@ilamanownuk/blog-kit/styles.css";` right after the Tailwind import. (Only if you choose `styles.layered.css`: declare `@layer theme, base, blog-kit, components, utilities;` BEFORE the imports.)
45
+ - Otherwise: `import "@ilamanownuk/blog-kit/styles.css";` in the root layout.
46
+ 3. Create ONE shared constants file (e.g. `src/lib/blog/config.ts`) with `BLOG_EMBEDS` and, if the project restricts image hosts, `isAllowedBlogImageSrc(src)`.
47
+ 4. Server side: in the action/service that creates and updates posts, replace any existing sanitizer with:
48
+ ```ts
49
+ import { sanitizeRichText, hasRichContent, richTextToPlain } from "@ilamanownuk/blog-kit/server";
50
+ const body = sanitizeRichText(input.body, { allowedEmbeds: BLOG_EMBEDS, isAllowedImageSrc });
51
+ if (!hasRichContent(body, { allowedEmbeds: BLOG_EMBEDS, isAllowedImageSrc })) /* return a validation error */;
52
+ const excerpt = input.excerpt?.trim() || richTextToPlain(body).slice(0, 160);
53
+ ```
54
+ Keep auth/permission checks. For NestJS, do this in the service (not the controller) and keep DTO validation.
55
+ 5. Editor: create (or replace) the client component that holds the form field:
56
+ ```tsx
57
+ "use client";
58
+ import { RichTextEditor } from "@ilamanownuk/blog-kit";
59
+ <RichTextEditor value={html} onChange={setHtml} allowedEmbeds={BLOG_EMBEDS} uploadImage={...} mediaApi={...} />
60
+ ```
61
+ If the project uses react-hook-form, wire it with `Controller` (`value={field.value}`, `onChange={field.onChange}`) and pass `invalid={!!fieldState.error}` and `id`.
62
+ 6. Image adapters: connect to the project's EXISTING upload/media system. Do not create a second storage system.
63
+ - Simple upload only: implement `uploadImage(file: File) => Promise<{ url: string; alt?: string }>` by calling the existing upload action/endpoint (build `FormData` with the file). Throw `new Error("<user-facing message>")` on failure; the message is shown in the dialog. Return an https URL (convert storage keys to public URLs if needed).
64
+ - If the project already has a media library with list + upload: implement `mediaApi = { list({ q, page }) , upload(formData) }` as Server Actions (so secrets stay on the server) and map its records to `MediaItem` (see section 4). `list` returns `{ items, total, page, pageSize, error? }`; `upload` receives `FormData` with the file under key `file` and returns `{ items, error? }`. Provide `variants["320"]` for thumbnails if available.
65
+ - If the project already has its own media picker UI: use `renderMediaPicker={({ onSelect, close }) => <ProjectPicker onPick={(m) => onSelect({ url: m.url, alt: m.alt ?? undefined })} onCancel={close} />}`.
66
+ - If there is no upload system at all: skip adapters (users can paste https image URLs) and mention it in the report.
67
+ 7. Rendering: replace the old renderer where posts are displayed with `<RichContent html={post.body} allowedEmbeds={BLOG_EMBEDS} isAllowedImageSrc={...} />`. Wrap with the page's article layout; do not wrap in another `prose` class unless it was already used.
68
+ 8. SEO: where meta description is built from content, use `richTextToPlain(body)`; keep existing metadata logic otherwise.
69
+ 9. Theme: make the editor and content match the project.
70
+ - Map variables to the project's tokens in the global CSS, for example:
71
+ `:root { --bk-accent: var(--primary); --bk-accent-contrast: var(--primary-foreground); --bk-fg: var(--foreground); --bk-bg: var(--background); --bk-border: var(--border); --bk-muted: var(--muted); --bk-surface: var(--card); --bk-radius: var(--radius); --bk-font: var(--font-sans); }`
72
+ (use the project's real token names; if it uses raw hex, copy its brand color to `--bk-accent`).
73
+ - Dark mode: if the project uses a `.dark` class, nothing more is needed (the kit supports `.dark`); if it uses another attribute, set `data-bk-theme="dark"` on `<html>` at the same time. Dialogs render into `<body>`, so the theme must be on `html`/`body`.
74
+ - Prefer the existing look if the project already had a blog style (e.g. a `.rich` class): port its typography values into `--bk-font-size`, `--bk-line-height`, `--bk-h2-size`, `--bk-h3-size`, `--bk-block-gap`, `--bk-link`, etc., then delete the old content styles.
75
+ - Use `classNames` and `toolbar` only if the project needs them.
76
+ 10. Cleanup (only after everything works): remove the old editor component, old renderer, duplicated sanitizer/embed helpers and unused dependencies (`@tiptap/*`, `sanitize-html` if no longer used elsewhere). Keep anything still imported somewhere (grep first). Update tests that imported removed files, or port them.
77
+
78
+ # 4. API reference (complete)
79
+
80
+ ```ts
81
+ // "@ilamanownuk/blog-kit" (client)
82
+ function RichTextEditor(props: {
83
+ value: string; // HTML
84
+ onChange: (html: string) => void; // empty editor => ""
85
+ placeholder?: string;
86
+ invalid?: boolean; // red border
87
+ id?: string; // id of the editable area (for <label htmlFor>)
88
+ className?: string; // extra class on root
89
+ classNames?: Partial<Record<"root"|"toolbar"|"separator"|"button"|"content"|"tableTools"|"popover"|"dialog"|"input"|"label", string>>;
90
+ toolbar?: readonly ToolbarItem[]; // order + visibility; "|" = separator; default = defaultToolbar
91
+ uploadImage?: (file: File) => Promise<{ url: string; alt?: string }>; // enables Upload button; throw Error(message) to show it
92
+ mediaApi?: MediaApi; // built-in media library dialog
93
+ renderMediaPicker?: (p: { onSelect: (img: { url: string; alt?: string }) => void; close: () => void }) => ReactNode; // takes precedence over mediaApi
94
+ resolveImageSrc?: (url: string) => string; // map URL before insertion (must still be https)
95
+ allowedEmbeds?: readonly ("aparat" | "youtube")[]; // default both; MUST equal server option
96
+ labels?: Partial<Labels>; // UI strings (Persian defaults); keys = keys of `defaultLabels`
97
+ dir?: "rtl" | "ltr"; // default "rtl"
98
+ }): JSX.Element;
99
+
100
+ type ToolbarItem = "bold"|"italic"|"underline"|"strike"|"textColor"|"highlight"|"h2"|"h3"|"h4"
101
+ |"right"|"center"|"left"|"justify"|"bullet"|"ordered"|"quote"|"code"|"hr"
102
+ |"link"|"unlink"|"image"|"video"|"table"|"undo"|"redo"|"|";
103
+
104
+ type MediaApi = {
105
+ list: (p: { q?: string; page?: number }) => Promise<{ items: MediaItem[]; total: number; page: number; pageSize: number; error?: string }>;
106
+ upload: (formData: FormData) => Promise<{ items: MediaItem[]; error?: string }>; // file under key "file"
107
+ };
108
+ type MediaItem = {
109
+ id: string; url: string; originalName: string; mimeType: string; sizeBytes: number;
110
+ width: number; height: number; alt: string | null;
111
+ variants: Record<string, { url: string; width: number; height: number }>; // "320" used for grid thumbs
112
+ createdAt: string;
113
+ };
114
+ // also exported: defaultLabels, defaultToolbar, toVideoEmbedUrl, normalizeLinkUrl, isAllowedEmbedSrc, types Labels, EditorClassNames, ToolbarItem, PickedImage, MediaPickerRenderProps, EmbedProvider
115
+
116
+ // "@ilamanownuk/blog-kit/renderer" (server-safe)
117
+ function RichContent(props: {
118
+ html: string; className?: string; dir?: "rtl"|"ltr" /* "rtl" */; lang?: string /* "fa" */;
119
+ allowedEmbeds?: readonly EmbedProvider[]; isAllowedImageSrc?: (src: string) => boolean;
120
+ }): JSX.Element; // renders <div class="bk-rich ...">, always re-sanitizes
121
+
122
+ // "@ilamanownuk/blog-kit/server"
123
+ function sanitizeRichText(html: string, o?: { allowedEmbeds?: readonly EmbedProvider[]; isAllowedImageSrc?: (src: string) => boolean }): string;
124
+ function hasRichContent(html: string, o?: same options): boolean; // text, img, allowed iframe or table
125
+ function richTextToPlain(html: string): string; // tag-free text for excerpts / meta
126
+ ```
127
+
128
+ Sanitizer allowlist: p, br, strong, em, u, s, h2-h4, ul, ol, li, blockquote, pre, code, a, hr, img (https only), table parts, mark, span (only text-align/color/background-color styles), iframe (only allowed embed providers; attributes rebuilt). Links get `rel="noopener noreferrer nofollow"`.
129
+
130
+ CSS variables (`--bk-*`): accent, accent-contrast, fg, muted-fg, bg, surface, muted, border, danger, code-bg, code-fg, code-inline-bg, mark-bg, hr-color, table-border, table-head-bg, backdrop, font, code-font, font-size, line-height, h2-size, h3-size, h4-size, heading-weight, radius, media-radius, block-gap, editor-min-height, editor-padding, toolbar-padding, toolbar-gap, control-size, dialog-width, dialog-wide-width, popover-shadow, dialog-shadow, z-toolbar, z-popover; optional: link, heading-color, quote-border, radius-sm, radius-lg, focus-ring. Dark preset: `[data-bk-theme="dark"]`, `.dark`, or `data-bk-theme="auto"`. Content class: `.bk-rich`; UI classes: `.bk-*`.
131
+
132
+ # 5. Step 3: verify
133
+
134
+ - Run the project's typecheck, lint and build (use existing scripts, e.g. `tsc --noEmit`, `next build`). Fix every error you introduced.
135
+ - Run existing tests; update ones that referenced removed code.
136
+ - If you can run the app, open the admin post form and a published post page: check that the toolbar is styled, RTL works, an image can be inserted (upload and/or library), an Aparat or YouTube link becomes a video, saving stores sanitized HTML, and the public page renders it. Also paste `<script>alert(1)</script><img src=x onerror=alert(1)>` as content through the server path and confirm it is stripped.
137
+ - Check dark mode (if the project has one) and the mobile width.
138
+
139
+ # 6. Final report (keep it short)
140
+
141
+ List: files created/changed/removed, how upload/media adapters were connected (or why skipped), shared constants location, theme mapping done, commands run and their results, and anything left for the human (e.g. data migration, missing upload endpoint). Do not paste large code.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Customization: every color, radius, font, spacing, shadow and z-index in `styles.css` is now a `--bk-*` variable with a default (new: `--bk-font-size`, `--bk-line-height`, `--bk-h2-size`..`--bk-h4-size`, `--bk-block-gap`, `--bk-media-radius`, `--bk-code-inline-bg`, `--bk-hr-color`, `--bk-table-*`, `--bk-backdrop`, `--bk-*-shadow`, `--bk-z-*`, dialog/toolbar sizing, optional `--bk-link`, `--bk-heading-color`, `--bk-quote-border`, `--bk-radius-sm/lg`, `--bk-focus-ring`).
6
+ - Dark theme preset: `[data-bk-theme="dark"]`, `.dark`, and `data-bk-theme="auto"` (follows the OS).
7
+ - `RichTextEditor`: new `classNames` prop (root, toolbar, separator, button, content, tableTools, popover, dialog, input, label) and `toolbar` prop (choose / reorder items, `"|"` separator). Exports `defaultToolbar`, `ToolbarItem`, `EditorClassNames`. Defaults are unchanged.
8
+ - New `styles.layered.css` export: same rules inside `@layer blog-kit`, so plain consumer CSS / Tailwind utilities win. `styles.css` stays unlayered so the default look is unchanged.
9
+ - Docs: README rewritten in Persian; new `AI_INSTALL_PROMPT.md` (shipped in the package) for AI-assisted installation.
10
+
11
+ ## 0.1.0
12
+
13
+ - Initial release: Tiptap editor, Aparat/YouTube embeds, image upload, media library picker, server sanitizer, renderer.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ilamanownuk
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.