@prunellejs/content 0.1.1 → 0.7.2
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 +21 -0
- package/llms.txt +40 -11
- package/package.json +2 -2
- package/src/app.ts +3 -1
- package/src/collection.ts +63 -530
- package/src/components.ts +74 -21
- package/src/entry.ts +171 -0
- package/src/file-collection.ts +308 -0
- package/src/frontmatter.ts +26 -13
- package/src/index.ts +78 -32
- package/src/loader-collection.ts +333 -0
- package/src/markdown.ts +52 -5
- package/src/registry.ts +147 -0
- package/src/rss.ts +44 -24
- package/src/service.ts +88 -0
- package/src/tracking.ts +80 -0
- package/src/types.ts +202 -0
- package/src/sanitize.ts +0 -309
package/src/types.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// Shared public and internal types and symbol keys for @prunellejs/content.
|
|
2
|
+
|
|
3
|
+
import type { ContentImageResolver, ContentImageResult } from 'prunelle/config'
|
|
4
|
+
import type { StandardSchemaV1 } from 'prunelle/server'
|
|
5
|
+
|
|
6
|
+
export const COLLECTION_VALIDATE_KEY = Symbol.for('pru.content.validateAll')
|
|
7
|
+
export const COLLECTION_DIR_FOR_ROOT_KEY = Symbol.for('pru.content.dirForRoot')
|
|
8
|
+
export const COLLECTION_OWNER_ROOT_KEY = Symbol.for('pru.content.ownerRoot')
|
|
9
|
+
export const COLLECTION_META_KEY = Symbol.for('pru.content.meta')
|
|
10
|
+
|
|
11
|
+
export interface InternalCollectionMeta {
|
|
12
|
+
readonly name: string
|
|
13
|
+
readonly dir?: string | undefined
|
|
14
|
+
readonly localized: boolean
|
|
15
|
+
readonly defaultLocale: string
|
|
16
|
+
readonly locales?: readonly string[] | undefined
|
|
17
|
+
readonly schema?: StandardSchemaV1 | undefined
|
|
18
|
+
readonly isAsync: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ContentHeading {
|
|
22
|
+
level: number
|
|
23
|
+
id: string
|
|
24
|
+
text: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RenderedMarkdown {
|
|
28
|
+
readonly html: string
|
|
29
|
+
readonly headings: readonly ContentHeading[]
|
|
30
|
+
readonly wordCount: number
|
|
31
|
+
readonly readingMinutes: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ContentEntry<TData = Record<string, unknown>> {
|
|
35
|
+
readonly slug: string
|
|
36
|
+
readonly locale?: string | undefined
|
|
37
|
+
readonly file: string
|
|
38
|
+
readonly data: TData
|
|
39
|
+
readonly body: string
|
|
40
|
+
readonly html: string
|
|
41
|
+
readonly headings: readonly ContentHeading[]
|
|
42
|
+
readonly wordCount: number
|
|
43
|
+
readonly readingMinutes: number
|
|
44
|
+
/** Lazily resolves async collection renderers (`highlight`, `components`) and renders Markdown once. */
|
|
45
|
+
render(): Promise<RenderedMarkdown>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type MarkdownComponent = (props: never) => unknown
|
|
49
|
+
export type CodeHighlighter = (code: string, language: string | undefined) => string
|
|
50
|
+
export type MarkdownImageResult = ContentImageResult
|
|
51
|
+
export type MarkdownImageResolver = ContentImageResolver
|
|
52
|
+
|
|
53
|
+
export interface CollectionRenderConfig {
|
|
54
|
+
/** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
|
|
55
|
+
highlight?: CodeHighlighter | undefined
|
|
56
|
+
/** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
|
|
57
|
+
components?: Record<string, MarkdownComponent> | undefined
|
|
58
|
+
/** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
|
|
59
|
+
headingLinks?: boolean | undefined
|
|
60
|
+
/** Optional image resolver (set to `false` to disable automatic `@prunellejs/images` optimization). */
|
|
61
|
+
resolveImage?: MarkdownImageResolver | false | undefined
|
|
62
|
+
/** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
|
|
63
|
+
trusted?: boolean | undefined
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RenderMarkdownOptions {
|
|
67
|
+
highlight?: CodeHighlighter | undefined
|
|
68
|
+
components?: Record<string, MarkdownComponent> | undefined
|
|
69
|
+
/** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
|
|
70
|
+
headingLinks?: boolean | undefined
|
|
71
|
+
/** Active locale passed into embedded components as `props.locale`. */
|
|
72
|
+
locale?: string | undefined
|
|
73
|
+
/** Optional image resolver for rewriting `<img src="...">` (defaults to auto-wired `@prunellejs/images` when active; `false` disables). */
|
|
74
|
+
resolveImage?: MarkdownImageResolver | false | undefined
|
|
75
|
+
/** Source file path passed to `resolveImage`. */
|
|
76
|
+
file?: string | undefined
|
|
77
|
+
/** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
|
|
78
|
+
trusted?: boolean | undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface CollectionLoadContext {
|
|
82
|
+
/** Requested locale when `localized: true`; `undefined` otherwise. */
|
|
83
|
+
readonly locale?: string | undefined
|
|
84
|
+
/** Aborted after `timeoutMs` or when the collection's cache is cleared: pass it to `fetch()` or the database client. */
|
|
85
|
+
readonly signal: AbortSignal
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface LoadedEntryInput {
|
|
89
|
+
/** Entry slug used for `.get(slug)` and `.paths(prefix)`. */
|
|
90
|
+
readonly slug: string
|
|
91
|
+
/** Raw entry metadata validated against `schema` when configured. */
|
|
92
|
+
readonly data: unknown
|
|
93
|
+
/** Optional Markdown body rendered through the standard content pipeline. */
|
|
94
|
+
readonly body?: string | undefined
|
|
95
|
+
/** Optional locale tag; when `localized: true`, entries with a non-matching locale are filtered out. */
|
|
96
|
+
readonly locale?: string | undefined
|
|
97
|
+
/** Optional upstream identifier (e.g. CMS record ID) surfaced as `entry.file`. */
|
|
98
|
+
readonly id?: string | undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type CollectionLoader = (
|
|
102
|
+
ctx: CollectionLoadContext,
|
|
103
|
+
) => LoadedEntryInput[] | Promise<LoadedEntryInput[]>
|
|
104
|
+
|
|
105
|
+
export interface BaseCollectionOptions<TData = Record<string, unknown>> {
|
|
106
|
+
/** Collection identifier for diagnostics, CMS, and search (defaults to `dir` basename or `'collection'`). */
|
|
107
|
+
name?: string | undefined
|
|
108
|
+
/** When true, queries are scoped by locale. */
|
|
109
|
+
localized?: boolean | undefined
|
|
110
|
+
/** Default locale when `localized: true` and no locale is passed (default: app defaultLocale or `'en'`). */
|
|
111
|
+
defaultLocale?: string | undefined
|
|
112
|
+
/** Known locales for localized collections (used by `prunelle check`, search, and CMS). */
|
|
113
|
+
locales?: readonly string[] | undefined
|
|
114
|
+
/** Optional Standard Schema (Zod, Valibot, ArkType, custom) to validate entry metadata. */
|
|
115
|
+
schema?: StandardSchemaV1<unknown, TData> | undefined
|
|
116
|
+
/** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
|
|
117
|
+
highlight?: CodeHighlighter | undefined
|
|
118
|
+
/** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
|
|
119
|
+
components?: Record<string, MarkdownComponent> | undefined
|
|
120
|
+
/** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
|
|
121
|
+
headingLinks?: boolean | undefined
|
|
122
|
+
/** Optional image resolver for rewriting Markdown images (defaults to auto-wired `@prunellejs/images`; `false` disables). */
|
|
123
|
+
resolveImage?: MarkdownImageResolver | false | undefined
|
|
124
|
+
/** Opt out of default Markdown HTML sanitization for fully trusted collections (default: false). */
|
|
125
|
+
trusted?: boolean | undefined
|
|
126
|
+
/** Lazy renderer loader (`async () => ({ highlight, components })`) so config/index/RSS never load Shiki or TSX components. */
|
|
127
|
+
render?: (() => CollectionRenderConfig | Promise<CollectionRenderConfig>) | undefined
|
|
128
|
+
/** Include entries with `draft: true` (default: `true` in dev, `false` in production/build). */
|
|
129
|
+
includeDrafts?: boolean | undefined
|
|
130
|
+
/** Custom comparator for `all()` (defaults to newest `date` first, then alphabetical `slug`). */
|
|
131
|
+
sort?: ((a: ContentEntry<TData>, b: ContentEntry<TData>) => number) | undefined
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface CollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
|
|
135
|
+
/** Directory containing `.md` / `.markdown` files (or `<locale>/*.md` when `localized: true`). */
|
|
136
|
+
dir: string
|
|
137
|
+
load?: undefined
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface CollectionOptionsWithSchema<TData> extends Omit<CollectionOptions<TData>, 'schema'> {
|
|
141
|
+
/** Standard Schema (Zod, Valibot, ArkType, custom) validating frontmatter into `TData`. */
|
|
142
|
+
schema: StandardSchemaV1<unknown, TData>
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface CollectionOptionsWithoutSchema extends Omit<CollectionOptions<Record<string, unknown>>, 'schema'> {
|
|
146
|
+
schema?: undefined
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface LoaderCollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
|
|
150
|
+
dir?: undefined
|
|
151
|
+
/** Async or sync loader returning entries from a headless CMS, database, or API. */
|
|
152
|
+
load: CollectionLoader
|
|
153
|
+
/** At runtime, how long every request reuses the entries of a finished load, per locale (default: 0, a load per request; `Infinity` keeps them until the cache is cleared). */
|
|
154
|
+
ttlMs?: number | undefined
|
|
155
|
+
/** How long a load may run before its signal aborts and the load fails (default: 30,000). */
|
|
156
|
+
timeoutMs?: number | undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface LoaderCollectionOptionsWithSchema<TData> extends Omit<LoaderCollectionOptions<TData>, 'schema'> {
|
|
160
|
+
/** Standard Schema (Zod, Valibot, ArkType, custom) validating loaded entry data into `TData`. */
|
|
161
|
+
schema: StandardSchemaV1<unknown, TData>
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface LoaderCollectionOptionsWithoutSchema extends Omit<LoaderCollectionOptions<Record<string, unknown>>, 'schema'> {
|
|
165
|
+
schema?: undefined
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface Collection<TData = Record<string, unknown>> {
|
|
169
|
+
readonly dir: string
|
|
170
|
+
readonly name: string
|
|
171
|
+
all(locale?: string): ContentEntry<TData>[]
|
|
172
|
+
get(slug: string, locale?: string): ContentEntry<TData> | undefined
|
|
173
|
+
byTag(tag: string, locale?: string): ContentEntry<TData>[]
|
|
174
|
+
/** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
|
|
175
|
+
paths(prefix?: string, locale?: string): string[]
|
|
176
|
+
clearCache(): void
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface AsyncCollection<TData = Record<string, unknown>> {
|
|
180
|
+
readonly dir?: undefined
|
|
181
|
+
readonly name: string
|
|
182
|
+
all(locale?: string): Promise<ContentEntry<TData>[]>
|
|
183
|
+
get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined>
|
|
184
|
+
byTag(tag: string, locale?: string): Promise<ContentEntry<TData>[]>
|
|
185
|
+
/** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
|
|
186
|
+
paths(prefix?: string, locale?: string): Promise<string[]>
|
|
187
|
+
clearCache(): void
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export type AnyCollection<TData = Record<string, unknown>> = Collection<TData> | AsyncCollection<TData>
|
|
191
|
+
|
|
192
|
+
export interface InternalCollection {
|
|
193
|
+
readonly dir?: string | undefined
|
|
194
|
+
readonly name?: string | undefined
|
|
195
|
+
all(locale?: string): ContentEntry<unknown>[] | Promise<ContentEntry<unknown>[]>
|
|
196
|
+
get(slug: string, locale?: string): ContentEntry<unknown> | undefined | Promise<ContentEntry<unknown> | undefined>
|
|
197
|
+
clearCache(): void
|
|
198
|
+
[COLLECTION_VALIDATE_KEY]?: (root: string) => string[] | Promise<string[]>
|
|
199
|
+
[COLLECTION_DIR_FOR_ROOT_KEY]?: (root?: string) => string | undefined
|
|
200
|
+
[COLLECTION_OWNER_ROOT_KEY]?: string | undefined
|
|
201
|
+
[COLLECTION_META_KEY]?: (root?: string) => InternalCollectionMeta
|
|
202
|
+
}
|
package/src/sanitize.ts
DELETED
|
@@ -1,309 +0,0 @@
|
|
|
1
|
-
// HTML allow-list sanitizer applied to rendered Markdown: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
|
|
2
|
-
|
|
3
|
-
const DROP_CONTENT_TAGS = new Set([
|
|
4
|
-
'script',
|
|
5
|
-
'style',
|
|
6
|
-
'iframe',
|
|
7
|
-
'object',
|
|
8
|
-
'applet',
|
|
9
|
-
'noscript',
|
|
10
|
-
'template',
|
|
11
|
-
])
|
|
12
|
-
|
|
13
|
-
const ALLOWED_MD_TAGS = new Set([
|
|
14
|
-
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
15
|
-
'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
|
|
16
|
-
'a', 'img', 'picture', 'source',
|
|
17
|
-
'pre', 'code', 'kbd', 'samp', 'var',
|
|
18
|
-
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
|
|
19
|
-
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
|
|
20
|
-
'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
|
|
21
|
-
'details', 'summary', 'figure', 'figcaption',
|
|
22
|
-
'input',
|
|
23
|
-
])
|
|
24
|
-
|
|
25
|
-
// Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
|
|
26
|
-
const GLOBAL_ALLOWED_ATTRS = new Set([
|
|
27
|
-
'class',
|
|
28
|
-
'title',
|
|
29
|
-
'lang',
|
|
30
|
-
'dir',
|
|
31
|
-
'role',
|
|
32
|
-
'aria-label',
|
|
33
|
-
'aria-hidden',
|
|
34
|
-
'aria-current',
|
|
35
|
-
'aria-expanded',
|
|
36
|
-
'aria-level',
|
|
37
|
-
'aria-description',
|
|
38
|
-
'aria-roledescription',
|
|
39
|
-
])
|
|
40
|
-
|
|
41
|
-
const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
|
|
42
|
-
a: new Set(['href', 'rel', 'target', 'hreflang']),
|
|
43
|
-
img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
|
|
44
|
-
source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
|
|
45
|
-
blockquote: new Set(['cite']),
|
|
46
|
-
q: new Set(['cite']),
|
|
47
|
-
del: new Set(['cite', 'datetime']),
|
|
48
|
-
ins: new Set(['cite', 'datetime']),
|
|
49
|
-
time: new Set(['datetime']),
|
|
50
|
-
ol: new Set(['start', 'reversed', 'type']),
|
|
51
|
-
li: new Set(['value']),
|
|
52
|
-
th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
|
|
53
|
-
td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
|
|
54
|
-
col: new Set(['span', 'align']),
|
|
55
|
-
colgroup: new Set(['span', 'align']),
|
|
56
|
-
details: new Set(['open']),
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const URL_ATTRS = new Set(['href', 'src', 'cite'])
|
|
60
|
-
const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
|
|
61
|
-
const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
|
|
62
|
-
const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
|
|
63
|
-
|
|
64
|
-
function decodeHtmlEntities(rawVal: string): string {
|
|
65
|
-
return rawVal
|
|
66
|
-
.replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
|
|
67
|
-
const cp = Number.parseInt(hex, 16)
|
|
68
|
-
return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
|
|
69
|
-
})
|
|
70
|
-
.replace(/&#([0-9]+);?/g, (_, dec: string) => {
|
|
71
|
-
const cp = Number.parseInt(dec, 10)
|
|
72
|
-
return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
|
|
73
|
-
})
|
|
74
|
-
.replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
|
|
75
|
-
const lower = name.toLowerCase()
|
|
76
|
-
if (lower === 'colon') return ':'
|
|
77
|
-
if (lower === 'tab') return '\t'
|
|
78
|
-
if (lower === 'newline') return '\n'
|
|
79
|
-
return '&'
|
|
80
|
-
})
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function isSafeUrl(val: string): boolean {
|
|
84
|
-
const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
|
|
85
|
-
if (cleaned === '')
|
|
86
|
-
return true
|
|
87
|
-
if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
|
|
88
|
-
return true
|
|
89
|
-
if (HAS_SCHEME_RE.test(cleaned))
|
|
90
|
-
return false
|
|
91
|
-
return true
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
|
|
95
|
-
const attrs: Array<{ name: string, value: string | null }> = []
|
|
96
|
-
let i = 0
|
|
97
|
-
const len = attrSrc.length
|
|
98
|
-
while (i < len) {
|
|
99
|
-
while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
|
|
100
|
-
if (i >= len) break
|
|
101
|
-
const nameStart = i
|
|
102
|
-
while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
|
|
103
|
-
const name = attrSrc.slice(nameStart, i).toLowerCase()
|
|
104
|
-
if (!name) {
|
|
105
|
-
i++
|
|
106
|
-
continue
|
|
107
|
-
}
|
|
108
|
-
while (i < len && /\s/.test(attrSrc[i]!)) i++
|
|
109
|
-
if (attrSrc[i] !== '=') {
|
|
110
|
-
attrs.push({ name, value: null })
|
|
111
|
-
continue
|
|
112
|
-
}
|
|
113
|
-
i++ // skip '='
|
|
114
|
-
while (i < len && /\s/.test(attrSrc[i]!)) i++
|
|
115
|
-
if (i >= len) {
|
|
116
|
-
attrs.push({ name, value: '' })
|
|
117
|
-
break
|
|
118
|
-
}
|
|
119
|
-
const quote = attrSrc[i]!
|
|
120
|
-
if (quote === '"' || quote === '\'') {
|
|
121
|
-
i++
|
|
122
|
-
const valStart = i
|
|
123
|
-
while (i < len && attrSrc[i] !== quote) i++
|
|
124
|
-
attrs.push({ name, value: attrSrc.slice(valStart, i) })
|
|
125
|
-
if (i < len) i++
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
const valStart = i
|
|
129
|
-
while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
|
|
130
|
-
attrs.push({ name, value: attrSrc.slice(valStart, i) })
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return attrs
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
|
|
137
|
-
const typeAttr = rawAttrs.find(a => a.name === 'type')
|
|
138
|
-
if (typeAttr?.value?.toLowerCase() !== 'checkbox')
|
|
139
|
-
return ''
|
|
140
|
-
const safeParts = ['type="checkbox"']
|
|
141
|
-
for (const a of rawAttrs) {
|
|
142
|
-
if (a.name === 'class' && a.value !== null)
|
|
143
|
-
safeParts.push(`class="${a.value.replaceAll('"', '"')}"`)
|
|
144
|
-
else if (a.name === 'disabled')
|
|
145
|
-
safeParts.push('disabled')
|
|
146
|
-
else if (a.name === 'checked')
|
|
147
|
-
safeParts.push('checked')
|
|
148
|
-
}
|
|
149
|
-
return `<input ${safeParts.join(' ')}>`
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
|
|
153
|
-
|
|
154
|
-
function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
|
|
155
|
-
if (value === null || allowed === undefined)
|
|
156
|
-
return false
|
|
157
|
-
if (typeof allowed === 'string')
|
|
158
|
-
return value.startsWith(allowed)
|
|
159
|
-
for (const prefix of allowed) {
|
|
160
|
-
if (value.startsWith(prefix))
|
|
161
|
-
return true
|
|
162
|
-
}
|
|
163
|
-
return false
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
|
|
167
|
-
if (tagName === 'div' && name === 'data-pru-md-slot')
|
|
168
|
-
return matchesSlotPrefix(value, slotPrefixes)
|
|
169
|
-
return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function sanitizeAttributes(
|
|
173
|
-
tagName: string,
|
|
174
|
-
rawAttrs: Array<{ name: string, value: string | null }>,
|
|
175
|
-
slotPrefixes: AllowedSlotPrefixes,
|
|
176
|
-
): string[] {
|
|
177
|
-
const safeParts: string[] = []
|
|
178
|
-
for (const a of rawAttrs) {
|
|
179
|
-
if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
|
|
180
|
-
continue
|
|
181
|
-
if (URL_ATTRS.has(a.name)) {
|
|
182
|
-
if (a.value === null || !isSafeUrl(a.value))
|
|
183
|
-
continue
|
|
184
|
-
}
|
|
185
|
-
else if (a.name === 'srcset' && a.value !== null) {
|
|
186
|
-
const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
|
|
187
|
-
if (!candidates.every(isSafeUrl))
|
|
188
|
-
continue
|
|
189
|
-
}
|
|
190
|
-
if (a.value === null)
|
|
191
|
-
safeParts.push(a.name)
|
|
192
|
-
else
|
|
193
|
-
safeParts.push(`${a.name}="${a.value.replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')}"`)
|
|
194
|
-
}
|
|
195
|
-
return safeParts
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function findTagEndOffset(html: string, start: number): number {
|
|
199
|
-
let tagEnd = start
|
|
200
|
-
const len = html.length
|
|
201
|
-
let inQuote: string | null = null
|
|
202
|
-
while (tagEnd < len) {
|
|
203
|
-
const c = html[tagEnd]!
|
|
204
|
-
if (inQuote !== null) {
|
|
205
|
-
if (c === inQuote)
|
|
206
|
-
inQuote = null
|
|
207
|
-
}
|
|
208
|
-
else if (c === '"' || c === '\'') {
|
|
209
|
-
inQuote = c
|
|
210
|
-
}
|
|
211
|
-
else if (c === '>') {
|
|
212
|
-
return tagEnd
|
|
213
|
-
}
|
|
214
|
-
tagEnd++
|
|
215
|
-
}
|
|
216
|
-
return -1
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
|
|
220
|
-
let out = ''
|
|
221
|
-
let i = 0
|
|
222
|
-
const len = html.length
|
|
223
|
-
|
|
224
|
-
while (i < len) {
|
|
225
|
-
const lt = html.indexOf('<', i)
|
|
226
|
-
if (lt === -1) {
|
|
227
|
-
out += html.slice(i)
|
|
228
|
-
break
|
|
229
|
-
}
|
|
230
|
-
out += html.slice(i, lt)
|
|
231
|
-
|
|
232
|
-
// Strip HTML comments (including HTML5 `--!>` closer)
|
|
233
|
-
if (html.startsWith('<!--', lt)) {
|
|
234
|
-
const endStd = html.indexOf('-->', lt + 4)
|
|
235
|
-
const endBang = html.indexOf('--!>', lt + 4)
|
|
236
|
-
if (endStd === -1 && endBang === -1)
|
|
237
|
-
i = len
|
|
238
|
-
else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
|
|
239
|
-
i = endBang + 4
|
|
240
|
-
else
|
|
241
|
-
i = endStd + 3
|
|
242
|
-
continue
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
let pos = lt + 1
|
|
246
|
-
const isClosing = html[pos] === '/'
|
|
247
|
-
if (isClosing)
|
|
248
|
-
pos++
|
|
249
|
-
|
|
250
|
-
const nameStart = pos
|
|
251
|
-
while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
|
|
252
|
-
const tagName = html.slice(nameStart, pos).toLowerCase()
|
|
253
|
-
if (!tagName) {
|
|
254
|
-
out += '<'
|
|
255
|
-
i = lt + 1
|
|
256
|
-
continue
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const tagEnd = findTagEndOffset(html, pos)
|
|
260
|
-
if (tagEnd === -1)
|
|
261
|
-
break
|
|
262
|
-
|
|
263
|
-
const attrSrc = html.slice(pos, tagEnd)
|
|
264
|
-
const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
|
|
265
|
-
i = tagEnd + 1
|
|
266
|
-
|
|
267
|
-
if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
|
|
268
|
-
if (!selfClosing) {
|
|
269
|
-
const closeRe = new RegExp(`</${tagName}\\b[^>]*>`, 'gi')
|
|
270
|
-
closeRe.lastIndex = i
|
|
271
|
-
const m = closeRe.exec(html)
|
|
272
|
-
i = m ? m.index + m[0].length : len
|
|
273
|
-
}
|
|
274
|
-
continue
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
if (!ALLOWED_MD_TAGS.has(tagName))
|
|
278
|
-
continue
|
|
279
|
-
|
|
280
|
-
if (isClosing) {
|
|
281
|
-
if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
|
|
282
|
-
out += `</${tagName}>`
|
|
283
|
-
continue
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
const rawAttrs = parseTagAttributes(attrSrc)
|
|
287
|
-
if (tagName === 'input') {
|
|
288
|
-
out += sanitizeInputTag(rawAttrs)
|
|
289
|
-
continue
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
|
|
293
|
-
const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
|
|
294
|
-
out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
return out
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
|
|
301
|
-
let current = html
|
|
302
|
-
for (let pass = 0; pass < 3; pass++) {
|
|
303
|
-
const next = sanitizePass(current, slotPrefixes)
|
|
304
|
-
if (next === current)
|
|
305
|
-
return next
|
|
306
|
-
current = next
|
|
307
|
-
}
|
|
308
|
-
return current
|
|
309
|
-
}
|