Files
vue-journal-layer/app/utils/embedRegistry.ts

245 lines
9.2 KiB
TypeScript

// Extensible embed provider registry for vue-journal-layer.
//
// Pure TypeScript with zero Nuxt imports so unit tests run directly under
// `node --test`. Consuming Nuxt apps register custom providers via
// `app.config.ts` (`journal.embeds`, synced by `app/plugins/journal-embeds.ts`)
// and/or a Nuxt plugin calling `registerJournalEmbedProvider` /
// `defineJournalEmbedProviders`.
//
// Both `htmlGate.ts` (pair-aware sanitization) and `embeds.ts` /
// `useJournalEmbedHydration.ts` (SSR expansion + client lazy hydration) read
// from the same registry. Lookups use `Map` exclusively so prototype keys
// (`__proto__`, `constructor`, `toString`) are never matched.
/** Allowed embed provider key format (mirrors sm-journal-plugin). */
export const EMBED_PROVIDER_KEY = /^[a-z][a-z0-9_-]{0,31}$/
/** Allowed `data-aspect` token (e.g. `16/9`, `4 / 3`, `1.5`), zero CSS injection vectors. */
export const EMBED_ASPECT = /^[1-9][0-9]{0,3}(?:\s*\/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$/
/** Allowed `data-height` token (e.g. `420`, `420px`), zero CSS injection vectors. */
export const EMBED_HEIGHT = /^[1-9][0-9]{0,3}(?:px)?$/
/** Context passed to a provider's optional SSR renderer. */
export interface JournalEmbedSsrContext {
provider: string
innerHtml: string
aspect?: string
height?: string
}
/** Context passed to a provider's client-side `mount` callback. */
export interface JournalEmbedMountContext {
id: string
provider: string
figure: HTMLElement
aspect?: string
height?: string
fallbackHtml: string
reducedMotion: Readonly<{ value: boolean }>
isReducedMotion: boolean
}
/** Provider registration shape accepted by `app.config.ts` and plugin helpers. */
export interface JournalEmbedProvider {
/** Pattern a `data-id` value must match (anchored automatically). */
idPattern: RegExp | string
/**
* Optional SSR expansion hook. Returning a string replaces the `<figure>`
* element during `expandEmbeds`; returning `undefined` or `null` leaves it
* for client hydration or untouched.
*/
renderSsr?: (id: string, ctx: JournalEmbedSsrContext) => string | undefined | null
/** Optional Vue async component loader for client-side lazy hydration. */
component?: () => Promise<unknown>
/** Optional plain DOM mount callback for client-side lazy hydration. */
mount?: (el: HTMLElement, ctx: JournalEmbedMountContext) => void | (() => void) | Promise<void | (() => void)>
/** Default CLS aspect-ratio token (validated against `EMBED_ASPECT`). */
aspectRatio?: string
/** Default CLS min-height token (validated against `EMBED_HEIGHT`). */
minHeight?: string
/** `IntersectionObserver` rootMargin override (default `'200px'`). */
rootMargin?: string
}
/** Normalized provider stored inside `JournalEmbedRegistry`. */
export interface NormalizedJournalEmbedProvider {
readonly key: string
readonly idPattern: RegExp
readonly renderSsr?: JournalEmbedProvider['renderSsr']
readonly component?: JournalEmbedProvider['component']
readonly mount?: JournalEmbedProvider['mount']
readonly aspectRatio?: string
readonly minHeight?: string
readonly rootMargin?: string
/** Internal flag distinguishing the built-in default YouTube provider. */
readonly _builtinYoutube?: boolean
}
function normalizeCssHeight(value: string): string {
return value.endsWith('px') ? value : `${value}px`
}
function buildClsStyle(aspect?: string, height?: string): string {
const parts: string[] = []
if (aspect && EMBED_ASPECT.test(aspect)) parts.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`)
if (height && EMBED_HEIGHT.test(height)) parts.push(`min-height:${normalizeCssHeight(height)}`)
return parts.join(';')
}
/** Built-in privacy-enhanced YouTube provider (100% SSR byte-compatible default). */
export const YOUTUBE_EMBED_PROVIDER: JournalEmbedProvider = Object.freeze({
idPattern: /^[A-Za-z0-9_-]{11}$/,
renderSsr(id: string, ctx: JournalEmbedSsrContext): string | undefined {
if (ctx.innerHtml !== '') return undefined
const style = buildClsStyle(ctx.aspect, ctx.height)
const styleAttr = style ? ` style="${style}"` : ''
return (
`<figure class="journal-embed journal-embed--youtube"${styleAttr}>` +
`<iframe src="https://www.youtube-nocookie.com/embed/${id}" title="YouTube video" loading="lazy" ` +
'referrerpolicy="strict-origin-when-cross-origin" ' +
'allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe>' +
'</figure>'
)
},
})
function normalizeIdPattern(name: string, pattern: RegExp | string): RegExp {
let raw: RegExp
if (pattern instanceof RegExp) {
raw = pattern
} else if (typeof pattern === 'string' && pattern.length > 0) {
try {
raw = new RegExp(pattern)
} catch (err) {
throw new Error(`Invalid idPattern for journal embed provider "${name}": ${String(err)}`)
}
} else {
throw new Error(`Journal embed provider "${name}" must provide a RegExp or non-empty string idPattern`)
}
const flags = raw.flags.replace(/[gy]/g, '')
return new RegExp(`^(?:${raw.source})$`, flags)
}
function normalizeProvider(name: string, provider: JournalEmbedProvider): NormalizedJournalEmbedProvider {
if (!EMBED_PROVIDER_KEY.test(name)) {
throw new Error(`Invalid journal embed provider key "${name}": must match ${EMBED_PROVIDER_KEY.source}`)
}
if (!provider || typeof provider !== 'object') {
throw new Error(`Journal embed provider "${name}" must be an object`)
}
const idPattern = normalizeIdPattern(name, provider.idPattern)
let aspectRatio: string | undefined
if (provider.aspectRatio !== undefined) {
const trimmed = provider.aspectRatio.trim()
if (!EMBED_ASPECT.test(trimmed)) {
throw new Error(`Invalid aspectRatio "${provider.aspectRatio}" for journal embed provider "${name}"`)
}
aspectRatio = trimmed
}
let minHeight: string | undefined
if (provider.minHeight !== undefined) {
const trimmed = provider.minHeight.trim()
if (!EMBED_HEIGHT.test(trimmed)) {
throw new Error(`Invalid minHeight "${provider.minHeight}" for journal embed provider "${name}"`)
}
minHeight = trimmed
}
return Object.freeze({
key: name,
idPattern,
renderSsr: provider.renderSsr,
component: provider.component,
mount: provider.mount,
aspectRatio,
minHeight,
rootMargin: typeof provider.rootMargin === 'string' && provider.rootMargin.trim() ? provider.rootMargin.trim() : undefined,
_builtinYoutube: provider === YOUTUBE_EMBED_PROVIDER,
})
}
/** Prototype-safe registry of allowed Journal embed providers. */
export class JournalEmbedRegistry {
private readonly providers = new Map<string, NormalizedJournalEmbedProvider>()
register(name: string, provider: JournalEmbedProvider): this {
this.providers.set(name, normalizeProvider(name, provider))
return this
}
define(map: Record<string, JournalEmbedProvider> | null | undefined): this {
if (!map || typeof map !== 'object') return this
for (const key of Object.keys(map)) {
const provider = map[key]
if (provider !== undefined) this.register(key, provider)
}
return this
}
get(name: string): NormalizedJournalEmbedProvider | undefined {
if (!EMBED_PROVIDER_KEY.test(name)) return undefined
return this.providers.get(name)
}
has(name: string): boolean {
if (!EMBED_PROVIDER_KEY.test(name)) return false
return this.providers.has(name)
}
match(name: string, id: string): boolean {
const provider = this.get(name)
if (!provider || typeof id !== 'string') return false
return provider.idPattern.test(id)
}
keys(): string[] {
return [...this.providers.keys()]
}
entries(): Array<[string, NormalizedJournalEmbedProvider]> {
return [...this.providers.entries()]
}
clone(): JournalEmbedRegistry {
const copy = new JournalEmbedRegistry()
for (const [k, v] of this.providers.entries()) copy.providers.set(k, v)
return copy
}
}
/** Creates a new embed registry, pre-populated with built-in `youtube` by default. */
export function createJournalEmbedRegistry(
initial?: Record<string, JournalEmbedProvider> | null,
includeDefaults = true,
): JournalEmbedRegistry {
const registry = new JournalEmbedRegistry()
if (includeDefaults) registry.register('youtube', YOUTUBE_EMBED_PROVIDER)
if (initial) registry.define(initial)
return registry
}
let activeRegistry = createJournalEmbedRegistry()
/** Returns the active module-level Journal embed registry. */
export function getJournalEmbedRegistry(): JournalEmbedRegistry {
return activeRegistry
}
/** Registers or overrides a single embed provider on the active registry. */
export function registerJournalEmbedProvider(name: string, provider: JournalEmbedProvider): JournalEmbedRegistry {
return activeRegistry.register(name, provider)
}
/** Registers or overrides a map of embed providers on the active registry. */
export function defineJournalEmbedProviders(
map: Record<string, JournalEmbedProvider> | null | undefined,
): JournalEmbedRegistry {
return activeRegistry.define(map)
}
/** Resets the active registry back to the default built-in `youtube` provider (for tests). */
export function resetJournalEmbedRegistry(): JournalEmbedRegistry {
activeRegistry = createJournalEmbedRegistry()
return activeRegistry
}