import { editor, internationalization } from '@intlayer/config/built'; import { conditionPlugin, type DeepTransformContent as DeepTransformContentCore, enumerationPlugin, fallbackPlugin, filePlugin, genderPlugin, getHTML, type IInterpreterPluginState as IInterpreterPluginStateCore, isInterpolableWrapperNode, nestedPlugin, type Plugins, pluralPlugin, resolveInsertedSelector, resolveInterpreterLocale, selectPlugin, splitInsertionTemplate, transformInterpolableNode, translationPlugin, } from '@intlayer/core/interpreter'; import { type CompileOptions, compileWithOptions, getMarkdownMetadata, } from '@intlayer/core/markdown'; import type { HTMLContent, InsertionContent, MarkdownContent, } from '@intlayer/core/transpiler'; import { getIntlayerNodePrototype } from '@intlayer/core/utils'; import type { KeyPath } from '@intlayer/types/keyPath'; import type { DeclaredLocales, LocalesValues, } from '@intlayer/types/module_augmentation'; import type { NodeType } from '@intlayer/types/nodeType'; import * as NodeTypes from '@intlayer/types/nodeType'; import type { TemplateResult } from 'lit'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { html, unsafeStatic } from 'lit/static-html.js'; import { getIntlayerClient } from './client/installIntlayer'; import type { HTMLComponents, LitHTMLComponent } from './html/types'; import { litRuntime } from './markdown/runtime'; import { type IntlayerNode as IntlayerNodeCore, renderIntlayerNode, } from './renderIntlayerNode'; /** * Compile markdown to an HTML string using the Lit runtime. * Inline here to avoid a cross-entry circular import with markdown/compiler. */ const compileMarkdown = (markdown = '', options: CompileOptions = {}): string => compileWithOptions(markdown, litRuntime, options) as string; /** * Creates a Lit-renderable node for raw HTML/compiled markdown. * * The returned object is a copy of an `unsafeHTML` DirectiveResult or TemplateResult * so that Lit's template engine renders it as HTML, while string * coercion (`.toString()`, `String(node)`) still returns the raw source string * for editor tooling and serialization. */ const createLitHTMLNode = ( content: string | TemplateResult | any[], rawStr: string, additionalProps: Record = {} ): any => { const result = typeof content === 'string' ? unsafeHTML(content) : Array.isArray(content) ? content : content; const isArrayResult = Array.isArray(result); const node = Object.assign( isArrayResult ? [...result] : { ...result }, additionalProps, { value: rawStr, raw: rawStr, [Symbol.iterator]: undefined, __update: () => {}, isJSX: true, } ); // Serves `${node}` and the string members from the raw source, after the // assignments above so they never walk a Proxy in the prototype chain return Object.setPrototypeOf( node, getIntlayerNodePrototype( rawStr, isArrayResult ? Array.prototype : Object.prototype ) ); }; /** --------------------------------------------- * INTLAYER NODE PLUGIN * --------------------------------------------- */ export type IntlayerNodeCond = T extends number | string ? IntlayerNode : never; export type IntlayerNode = IntlayerNodeCore & P; const escapeHtmlAttr = (str: string): string => str.replace(/&/g, '&').replace(/"/g, '"'); const escapeHtmlText = (str: string): string => str.replace(/&/g, '&').replace(//g, '>'); /** * Wraps string/number leaf values in an IntlayerNode so they carry * `.value`, `.raw`, `toString()`, and `__update()`. * When the editor is enabled, wraps the content with * `` so the visual editor can highlight it. */ export const intlayerNodePlugins: Plugins = { id: 'intlayer-node-plugin', canHandle: (node) => typeof node === 'bigint' || typeof node === 'string' || typeof node === 'number', transform: (_node, { children, keyPath, dictionaryKey }) => { if (process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled) { const rawStr = String(children ?? ''); const htmlStr = `${escapeHtmlText(rawStr)}`; return createLitHTMLNode(htmlStr, rawStr); } return renderIntlayerNode({ value: children as string, children, }); }, }; /** --------------------------------------------- * INSERTION PLUGIN * --------------------------------------------- */ export type InsertionCond = T extends { nodeType: NodeType | string; [NodeTypes.INSERTION]: infer I; fields: readonly (infer F)[]; } ? ]: string | number }>( values: V ) => I extends string ? IntlayerNode : DeepTransformContent : never; export const insertionPlugin: Plugins = process.env.INTLAYER_NODE_TYPE_INSERTION === 'false' ? fallbackPlugin : { id: 'insertion-plugin', canHandle: (node) => typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION, transform: (node: InsertionContent, props, deepTransformNode) => { const newKeyPath: KeyPath[] = [ ...props.keyPath, { type: NodeTypes.INSERTION }, ]; const children = node[NodeTypes.INSERTION]; const insertionStringPlugin: Plugins = { id: 'insertion-string-plugin', canHandle: (node) => typeof node === 'string' || isInterpolableWrapperNode(node), transform: (node, subProps, deepTransformNode) => { // `html()`/`markdown()` nodes carry their `{{ … }}` placeholders // inside a raw string. Interpolate into that string, then re-run // the transform so the html/markdown renderer applies afterwards. if (isInterpolableWrapperNode(node)) { return (values: { [K in InsertionContent['fields'][number]]: string | number; }) => transformInterpolableNode( node, values, subProps, props.plugins, deepTransformNode ); } const transformedResult = deepTransformNode(node, { ...subProps, children: node, plugins: (props.plugins ?? ([] as Plugins[])).filter( (plugin) => plugin.id !== 'intlayer-node-plugin' ), }); return (values: { [K in InsertionContent['fields'][number]]: string | number; }) => { const result = splitInsertionTemplate( transformedResult, values ); const resultStr = result.isSimple ? (result.parts as string) : (result.parts as string[]).join(''); return deepTransformNode(resultStr, { ...subProps, plugins: props.plugins, children: resultStr, }); }; }, }; const transformed = deepTransformNode(children, { ...props, children, keyPath: newKeyPath, plugins: [insertionStringPlugin, ...(props.plugins ?? [])], }); return resolveInsertedSelector(children, transformed); }, }; /** --------------------------------------------- * MARKDOWN PLUGIN * --------------------------------------------- */ export type MarkdownStringCond = T extends string ? IntlayerNode< string, { metadata: DeepTransformContent; /** Returns the raw markdown string; render with compileMarkdown() or . */ use: (components?: HTMLComponents<'permissive', {}>) => string; } > : never; /** Markdown string plugin. Replaces string node with a component that render the markdown. */ export const markdownStringPlugin: Plugins = process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false' ? fallbackPlugin : { id: 'markdown-string-plugin', canHandle: (node) => typeof node === 'string', transform: (node: string, props, deepTransformNode) => { const { plugins: _plugins, ...rest } = props; const { keyPath, dictionaryKey } = rest; const metadata = getMarkdownMetadata(node) ?? {}; const metadataPlugins: Plugins = { id: 'markdown-metadata-plugin', canHandle: (metadataNode) => typeof metadataNode === 'string' || typeof metadataNode === 'number' || typeof metadataNode === 'boolean' || !metadataNode, transform: (metadataNode, subProps) => renderIntlayerNode({ ...subProps, value: metadataNode, children: node, }), }; const metadataNodes = deepTransformNode(metadata, { plugins: [metadataPlugins], dictionaryKey: rest.dictionaryKey, keyPath: [], }); const compiled = compileMarkdown(node); const use = (components?: any) => { const rendered = compileMarkdown(node, { components }); if ( process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ) { const wrappedHTML = `${rendered}`; return createLitHTMLNode(wrappedHTML, node); } return createLitHTMLNode(rendered, node); }; if ( process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ) { const wrappedHTML = `${compiled}`; return createLitHTMLNode(wrappedHTML, node, { metadata: metadataNodes, use, }); } return createLitHTMLNode(compiled, node, { metadata: metadataNodes, use, }); }, }; export type MarkdownCond = T extends { nodeType: NodeType | string; [NodeTypes.MARKDOWN]: infer M; metadata?: infer U; tags?: infer U; } ? { use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode; metadata: DeepTransformContent; } : never; export const markdownPlugin: Plugins = process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false' ? fallbackPlugin : { id: 'markdown-plugin', canHandle: (node) => typeof node === 'object' && node?.nodeType === NodeTypes.MARKDOWN, transform: (node: MarkdownContent, props, deepTransformNode) => { const newKeyPath: KeyPath[] = [ ...props.keyPath, { type: NodeTypes.MARKDOWN }, ]; const children = node[NodeTypes.MARKDOWN]; return deepTransformNode(children, { ...props, children, keyPath: newKeyPath, plugins: [markdownStringPlugin, ...(props.plugins ?? [])], }); }, }; /** --------------------------------------------- * HTML PLUGIN * --------------------------------------------- */ export type HTMLPluginCond = T extends { nodeType: NodeType | string; [NodeTypes.HTML]: infer I; tags?: infer U; } ? { /** Returns the raw HTML string; render with unsafeHTML() or . */ use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode; } : never; export const htmlPlugin: Plugins = process.env.INTLAYER_NODE_TYPE_HTML === 'false' ? fallbackPlugin : { id: 'html-plugin', canHandle: (node) => typeof node === 'object' && node?.nodeType === NodeTypes.HTML, transform: (node: HTMLContent, props) => { const htmlStr = node[NodeTypes.HTML] as string; const { keyPath, dictionaryKey } = props; const use = (components: HTMLComponents<'permissive', {}> = {}) => { // Wrap explicit user components to ensure they return what getHTML expects const userComponents = Object.fromEntries( Object.entries(components) .filter(([, Component]) => Component) .map(([key, Component]) => [ key, (props: any) => (Component as LitHTMLComponent)(props), ]) ); // Proxy handles standard HTML tags lazily const wrappedComponents = new Proxy(userComponents, { get(target, prop) { if (typeof prop === 'string' && prop in target) { return target[prop]; } // Fallback: wrapper for standard lowercase HTML tags if (typeof prop === 'string' && /^[a-z][a-z0-9]*$/.test(prop)) { return (props: any) => html`<${unsafeStatic(prop)} ...${props} >${props.children}`; } return undefined; }, }); const rendered = getHTML(htmlStr, wrappedComponents as any); if ( process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ) { const wrappedHTML = `${rendered}`; return createLitHTMLNode(wrappedHTML, htmlStr); } return createLitHTMLNode(rendered, htmlStr); }; if ( process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ) { const wrappedHTML = `${htmlStr}`; return createLitHTMLNode(wrappedHTML, htmlStr, { use }); } return createLitHTMLNode(htmlStr, htmlStr, { use }); }, }; /** --------------------------------------------- * PLUGINS RESULT * --------------------------------------------- */ export interface IInterpreterPluginLit { litIntlayerNode: IntlayerNodeCond; litInsertion: InsertionCond; litMarkdown: MarkdownCond; litHtml: HTMLPluginCond; } export type IInterpreterPluginState = Omit< IInterpreterPluginStateCore, 'insertion' > & { litIntlayerNode: true; litInsertion: true; litMarkdown: true; litHtml: true; }; export type DeepTransformContent< T, L extends LocalesValues = DeclaredLocales, > = DeepTransformContentCore; const pluginsCache = new Map(); export const getPlugins = ( locale?: LocalesValues, fallback = true ): Plugins[] => { const currentLocale = locale ?? ((typeof window !== 'undefined' && getIntlayerClient()?.locale) as | LocalesValues | undefined) ?? resolveInterpreterLocale(); const cacheKey = `${currentLocale}_${fallback}`; if (pluginsCache.has(cacheKey)) { return pluginsCache.get(cacheKey)!; } const plugins = [ // First: most nodes are plain strings, which every other plugin rejects intlayerNodePlugins, translationPlugin( currentLocale, fallback ? internationalization.defaultLocale : undefined ), enumerationPlugin, pluralPlugin(currentLocale), conditionPlugin, nestedPlugin(currentLocale), filePlugin, genderPlugin, selectPlugin, insertionPlugin, markdownPlugin, htmlPlugin, ] as Plugins[]; // Plugins disabled at build time never match: skip them on every node const enabledPlugins = plugins.filter((plugin) => plugin !== fallbackPlugin); pluginsCache.set(cacheKey, enabledPlugins); return enabledPlugins; };