import { editor, internationalization } from '@intlayer/config/built'; import { bindInsertedValues, conditionPlugin, type DeepTransformContent as DeepTransformContentCore, enumerationPlugin, fallbackPlugin, filePlugin, genderPlugin, type IInterpreterPluginState as IInterpreterPluginStateCore, isInterpolableWrapperNode, nestedPlugin, type Plugins, pluralPlugin, resolveInterpreterLocale, selectPlugin, splitInsertionTemplate, transformInterpolableNode, translationPlugin, } from '@intlayer/core/interpreter'; import { getMarkdownMetadata } from '@intlayer/core/markdown'; import type { HTMLContent, InsertionContent, MarkdownContent, } from '@intlayer/core/transpiler'; 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 { Component, JSX } from 'solid-js'; import { reportExposure } from './analytics/exposureSink'; import type { HTMLComponents } from './html/types'; import { type IntlayerNode, renderIntlayerNode } from './IntlayerNode'; import { LoadingBoundary } from './LoadingBoundary'; import { lazyComponent } from './solidCompat'; import { renderSolidElement } from './solidElement/renderSolidElement'; const LazyContentSelector = ( process.env.INTLAYER_EDITOR_ENABLED === 'false' ? null : lazyComponent(() => import('./editor/ContentSelector').then((m) => ({ default: m.ContentSelector, })) ) )!; const markdownRendererModulePromise = process.env.INTLAYER_NODE_TYPE_MARKDOWN !== 'false' ? import('./markdown/MarkdownRenderer').then((m) => ({ MarkdownRenderer: m.MarkdownRenderer, MarkdownMetadataRenderer: m.MarkdownMetadataRenderer, })) : null; const htmlRendererModulePromise = process.env.INTLAYER_NODE_TYPE_HTML !== 'false' ? import('./html/HTMLRenderer').then((m) => m.HTMLRenderer) : null; // These preloads are read later by `useLoadDynamic`, so the rejection must stay // on the promise: a `.catch()` chained into it would resolve with `undefined` // and be mistaken for a loaded module. Handle it on the side instead, so an // aborted chunk load never escapes as an unhandled rejection. markdownRendererModulePromise?.catch(() => {}); htmlRendererModulePromise?.catch(() => {}); /** --------------------------------------------- * INTLAYER NODE PLUGIN * --------------------------------------------- */ export type IntlayerNodeCond = T extends number | string ? IntlayerNode : never; /** Translation plugin. Replaces node with a locale string if nodeType = Translation. */ export const intlayerNodePlugins: Plugins = { id: 'intlayer-node-plugin', canHandle: (node) => typeof node === 'bigint' || typeof node === 'string' || typeof node === 'number', transform: (_node, props) => { // Node-level analytics: record which content is resolved for display. // No-op (and dead-code-eliminated) when analytics is disabled. if (process.env.INTLAYER_ANALYTICS_ENABLED !== 'false') { reportExposure({ dictionaryKey: props.dictionaryKey, keyPath: props.keyPath, locale: props.locale, nodeType: 'text', }); } // Props are only forwarded to the editor selector: copying them for every // leaf would cost an allocation per rendered string if (process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled) { const { plugins, // Removed to avoid next error - Functions cannot be passed directly to Client Components ...rest } = props; return renderIntlayerNode({ value: rest.children, children: ( {rest.children} ), }); } return renderIntlayerNode({ value: props.children, children: props.children, }); }, }; /** --------------------------------------------- * SOLID NODE PLUGIN * --------------------------------------------- */ export type SolidNodeCond = T extends { props: any; key?: any; } ? JSX.Element : never; /** Translation plugin. Replaces node with a locale string if nodeType = Translation. */ export const solidNodePlugins: Plugins = process.env.INTLAYER_NODE_TYPE_SOLID_NODE === 'false' ? fallbackPlugin : { id: 'solid-node-plugin', canHandle: (node) => (typeof node === 'object' && node?.props !== undefined) || (typeof Node !== 'undefined' && node instanceof Node), transform: ( node, { plugins, // Removed to avoid next error - Functions cannot be passed directly to Client Components ...rest } ) => { if (process.env.INTLAYER_ANALYTICS_ENABLED !== 'false') { reportExposure({ dictionaryKey: rest.dictionaryKey, keyPath: rest.keyPath, locale: rest.locale, nodeType: 'solid-node', }); } return renderIntlayerNode({ ...rest, value: '[[solid-element]]', children: process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ? ( {typeof Node !== 'undefined' && node instanceof Node ? node : renderSolidElement(node)} ) : typeof Node !== 'undefined' && node instanceof Node ? ( node ) : ( renderSolidElement(node) ), }); }, }; /** --------------------------------------------- * INSERTION PLUGIN * --------------------------------------------- */ export type InsertionCond = T extends { nodeType: NodeType | string; [NodeTypes.INSERTION]: infer I; fields: readonly (infer F)[]; } ? ]: string | number | JSX.Element }>( values: V ) => I extends string ? V[keyof V] extends string | number ? IntlayerNode : IntlayerNode : DeepTransformContent : never; /** * Split insertion string and join with JSX elements */ const splitAndJoinInsertion = ( template: string, values: Record ): JSX.Element => { const result = splitInsertionTemplate(template, values); // No JSX elements - use original logic if (result.isSimple) { // Simple string replacement return result.parts as string; } // Return as JSX array return result.parts as any[] as JSX.Element; }; /** Insertion plugin for Solid. Handles component/element insertion. */ 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]; // Return the (values) => wrapper at the Insertion level return (values: Record) => { /** Insertion string plugin. Replaces strings by injecting the values. */ const insertionStringPlugin: Plugins = { id: 'insertion-string-plugin', canHandle: (n) => typeof n === 'string' || isInterpolableWrapperNode(n), transform: (n, 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 after. if (isInterpolableWrapperNode(n)) { return transformInterpolableNode( n, values as Record, subProps, props.plugins, deepTransformNode ); } const transformedResult = deepTransformNode(n, { ...subProps, children: n, plugins: (props.plugins ?? ([] as Plugins[])).filter( (plugin) => plugin.id !== 'intlayer-node-plugin' ), }); // Inject the values captured from the parent scope const result = splitAndJoinInsertion(transformedResult, values); return deepTransformNode(result, { ...subProps, plugins: props.plugins, children: result, }); }, }; // Process the child nodes (strings or enumerations) with the string plugin active const result = deepTransformNode(children, { ...props, children, keyPath: newKeyPath, plugins: [insertionStringPlugin, ...(props.plugins ?? [])], }); // Branch strings are interpolated above; a plural still needs the // values merged with its count. return bindInsertedValues(children, result, values, true); }; }, }; /** * MARKDOWN PLUGIN */ export type MarkdownStringCond = T extends string ? IntlayerNode< string, { metadata: DeepTransformContent; use: (components?: HTMLComponents<'permissive', {}>) => JSX.Element; } > : never; /** * Code-split renderers are loaded with `lazy` rather than read through * `useLoadDynamic`'s value proxy. A component reached through that proxy gets * re-invoked on every read, inside the caller's tracking scope — which leaks the * component's own reactive reads upward and re-renders forever, rebuilding a * fresh instance each pass. `lazy` keeps a single memoised instance and hands * pending state to Suspense. */ const MarkdownSuspenseRenderer = lazyComponent(() => markdownRendererModulePromise!.then((modules) => ({ default: modules.MarkdownRenderer as Component>, })) ); const MarkdownMetadataSuspenseRenderer = lazyComponent(() => markdownRendererModulePromise!.then((modules) => ({ default: modules.MarkdownMetadataRenderer as Component>, })) ); /** 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, // Removed to avoid next error - Functions cannot be passed directly to Client Components ...rest } = props; 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, props) => renderIntlayerNode({ ...props, value: metadataNode, children: process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ? ( {node} ) : ( {node} ), }), }; // Transform metadata while keeping the same structure const metadataNodes = deepTransformNode(metadata, { plugins: [metadataPlugins], dictionaryKey: rest.dictionaryKey, keyPath: [], }); const render = (components?: HTMLComponents) => renderIntlayerNode({ ...props, value: node, children: process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ? ( {node} ) : ( {node} ), additionalProps: { metadata: metadataNodes, use: render, }, }); return render() as any; }, }; export type MarkdownCond = T extends { nodeType: NodeType | string; [NodeTypes.MARKDOWN]: infer M; metadata?: infer U; tags?: infer U; } ? IntlayerNode< M, { use: (components?: HTMLComponents<'permissive', U>) => JSX.Element; 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; } ? IntlayerNode< I, { use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode; } > : never; const HTMLSuspenseRenderer = lazyComponent(() => htmlRendererModulePromise!.then((HTMLRenderer) => ({ default: HTMLRenderer as Component>, })) ); /** HTML plugin. Replaces node with a function that takes components => JSX.Element. */ 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 html = node[NodeTypes.HTML]; // `children` is dropped deliberately: `HTMLRenderer` resolves its // content as `children || html`, so forwarding the raw node here would // shadow the HTML string and render nothing. const { plugins, children: _nodeChildren, ...rest } = props; // Type-safe render function that accepts properly typed components const render = (userComponents?: HTMLComponents): any => renderIntlayerNode({ ...rest, value: html, children: process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled ? ( ) : ( ), additionalProps: { use: render }, }); return render(); }, }; /** --------------------------------------------- * PLUGINS RESULT * --------------------------------------------- */ export interface IInterpreterPluginSolid { solidNode: SolidNodeCond; solidIntlayerNode: IntlayerNodeCond; solidInsertion: InsertionCond; solidMarkdown: MarkdownCond; solidHtml: HTMLPluginCond; } /** * Insert this type as param of `DeepTransformContent` to avoid `intlayer` package pollution. * * Otherwise the the `solid-intlayer` plugins will override the types of `intlayer` functions. */ export type IInterpreterPluginState = Omit< IInterpreterPluginStateCore, 'insertion' // Remove insertion type from core package > & { solidNode: true; solidIntlayerNode: true; solidInsertion: true; solidMarkdown: true; solidHtml: true; }; export type DeepTransformContent< T, L extends LocalesValues = DeclaredLocales, > = DeepTransformContentCore; const pluginsCache = new Map(); /** * Get the plugins array for Solid content transformation. * This function is used by both getIntlayer and getDictionary to ensure consistent plugin configuration. */ export const getPlugins = ( locale?: LocalesValues, fallback: boolean = true ): Plugins[] => { const currentLocale = resolveInterpreterLocale(locale); 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, solidNodePlugins, 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; };