vanilla-intlayer 9.0.0-canary.8 → 9.0.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.
- package/dist/cjs/client/installIntlayer.cjs +0 -1
- package/dist/cjs/client/installIntlayer.cjs.map +1 -1
- package/dist/cjs/client/useDictionary.cjs.map +1 -1
- package/dist/cjs/client/useDictionaryDynamic.cjs +0 -1
- package/dist/cjs/client/useDictionaryDynamic.cjs.map +1 -1
- package/dist/cjs/client/useIntlayer.cjs.map +1 -1
- package/dist/cjs/client/useLocale.cjs +0 -1
- package/dist/cjs/client/useLocale.cjs.map +1 -1
- package/dist/cjs/client/useLocaleStorage.cjs +0 -1
- package/dist/cjs/client/useLocaleStorage.cjs.map +1 -1
- package/dist/cjs/client/usePathname.cjs +0 -1
- package/dist/cjs/client/usePathname.cjs.map +1 -1
- package/dist/cjs/client/useRewriteURL.cjs +0 -1
- package/dist/cjs/client/useRewriteURL.cjs.map +1 -1
- package/dist/cjs/editor/useEditor.cjs +0 -1
- package/dist/cjs/editor/useEditor.cjs.map +1 -1
- package/dist/cjs/format/useCompact.cjs +0 -1
- package/dist/cjs/format/useCompact.cjs.map +1 -1
- package/dist/cjs/format/useCurrency.cjs +0 -1
- package/dist/cjs/format/useCurrency.cjs.map +1 -1
- package/dist/cjs/format/useDate.cjs +0 -1
- package/dist/cjs/format/useDate.cjs.map +1 -1
- package/dist/cjs/format/useIntl.cjs +0 -1
- package/dist/cjs/format/useIntl.cjs.map +1 -1
- package/dist/cjs/format/useList.cjs +0 -1
- package/dist/cjs/format/useList.cjs.map +1 -1
- package/dist/cjs/format/useNumber.cjs +0 -1
- package/dist/cjs/format/useNumber.cjs.map +1 -1
- package/dist/cjs/format/usePercentage.cjs +0 -1
- package/dist/cjs/format/usePercentage.cjs.map +1 -1
- package/dist/cjs/format/useRelativeTime.cjs +0 -1
- package/dist/cjs/format/useRelativeTime.cjs.map +1 -1
- package/dist/cjs/format/useUnit.cjs +0 -1
- package/dist/cjs/format/useUnit.cjs.map +1 -1
- package/dist/cjs/getDictionary.cjs +0 -1
- package/dist/cjs/getDictionary.cjs.map +1 -1
- package/dist/cjs/getIntlayer.cjs +0 -1
- package/dist/cjs/getIntlayer.cjs.map +1 -1
- package/dist/cjs/html/HTMLRenderer.cjs.map +1 -1
- package/dist/cjs/html/installIntlayerHTML.cjs +2 -1
- package/dist/cjs/html/installIntlayerHTML.cjs.map +1 -1
- package/dist/cjs/markdown/MarkdownRenderer.cjs.map +1 -1
- package/dist/cjs/markdown/compiler.cjs +0 -1
- package/dist/cjs/markdown/compiler.cjs.map +1 -1
- package/dist/cjs/markdown/installIntlayerMarkdown.cjs +2 -1
- package/dist/cjs/markdown/installIntlayerMarkdown.cjs.map +1 -1
- package/dist/cjs/markdown/runtime.cjs +1 -1
- package/dist/cjs/markdown/runtime.cjs.map +1 -1
- package/dist/cjs/plugins.cjs +5 -3
- package/dist/cjs/plugins.cjs.map +1 -1
- package/dist/cjs/renderIntlayerNode.cjs.map +1 -1
- package/dist/esm/client/installIntlayer.mjs.map +1 -1
- package/dist/esm/client/useDictionary.mjs.map +1 -1
- package/dist/esm/client/useDictionaryDynamic.mjs.map +1 -1
- package/dist/esm/client/useIntlayer.mjs.map +1 -1
- package/dist/esm/client/useLocale.mjs.map +1 -1
- package/dist/esm/client/useLocaleStorage.mjs.map +1 -1
- package/dist/esm/client/usePathname.mjs.map +1 -1
- package/dist/esm/client/useRewriteURL.mjs.map +1 -1
- package/dist/esm/editor/useEditor.mjs.map +1 -1
- package/dist/esm/format/useCompact.mjs.map +1 -1
- package/dist/esm/format/useCurrency.mjs.map +1 -1
- package/dist/esm/format/useDate.mjs.map +1 -1
- package/dist/esm/format/useIntl.mjs.map +1 -1
- package/dist/esm/format/useList.mjs.map +1 -1
- package/dist/esm/format/useNumber.mjs.map +1 -1
- package/dist/esm/format/usePercentage.mjs.map +1 -1
- package/dist/esm/format/useRelativeTime.mjs.map +1 -1
- package/dist/esm/format/useUnit.mjs.map +1 -1
- package/dist/esm/getDictionary.mjs.map +1 -1
- package/dist/esm/getIntlayer.mjs.map +1 -1
- package/dist/esm/html/HTMLRenderer.mjs.map +1 -1
- package/dist/esm/html/installIntlayerHTML.mjs +2 -1
- package/dist/esm/html/installIntlayerHTML.mjs.map +1 -1
- package/dist/esm/markdown/MarkdownRenderer.mjs.map +1 -1
- package/dist/esm/markdown/compiler.mjs.map +1 -1
- package/dist/esm/markdown/installIntlayerMarkdown.mjs +2 -1
- package/dist/esm/markdown/installIntlayerMarkdown.mjs.map +1 -1
- package/dist/esm/markdown/runtime.mjs +1 -1
- package/dist/esm/markdown/runtime.mjs.map +1 -1
- package/dist/esm/plugins.mjs +6 -4
- package/dist/esm/plugins.mjs.map +1 -1
- package/dist/esm/renderIntlayerNode.mjs.map +1 -1
- package/dist/types/client/installIntlayer.d.ts +1 -5
- package/dist/types/client/installIntlayer.d.ts.map +1 -1
- package/dist/types/client/useDictionary.d.ts +0 -1
- package/dist/types/client/useDictionary.d.ts.map +1 -1
- package/dist/types/client/useDictionaryDynamic.d.ts +1 -2
- package/dist/types/client/useDictionaryDynamic.d.ts.map +1 -1
- package/dist/types/client/useIntlayer.d.ts +0 -1
- package/dist/types/client/useIntlayer.d.ts.map +1 -1
- package/dist/types/client/useLocale.d.ts +0 -1
- package/dist/types/client/useLocale.d.ts.map +1 -1
- package/dist/types/client/useLocaleStorage.d.ts +5 -10
- package/dist/types/client/useLocaleStorage.d.ts.map +1 -1
- package/dist/types/client/usePathname.d.ts +2 -1
- package/dist/types/client/usePathname.d.ts.map +1 -1
- package/dist/types/client/useRewriteURL.d.ts.map +1 -1
- package/dist/types/editor/useEditor.d.ts.map +1 -1
- package/dist/types/format/useCompact.d.ts +0 -1
- package/dist/types/format/useCompact.d.ts.map +1 -1
- package/dist/types/format/useCurrency.d.ts +0 -1
- package/dist/types/format/useCurrency.d.ts.map +1 -1
- package/dist/types/format/useDate.d.ts +0 -1
- package/dist/types/format/useDate.d.ts.map +1 -1
- package/dist/types/format/useIntl.d.ts +0 -1
- package/dist/types/format/useIntl.d.ts.map +1 -1
- package/dist/types/format/useList.d.ts +0 -1
- package/dist/types/format/useList.d.ts.map +1 -1
- package/dist/types/format/useNumber.d.ts +0 -1
- package/dist/types/format/useNumber.d.ts.map +1 -1
- package/dist/types/format/usePercentage.d.ts +0 -1
- package/dist/types/format/usePercentage.d.ts.map +1 -1
- package/dist/types/format/useRelativeTime.d.ts +0 -1
- package/dist/types/format/useRelativeTime.d.ts.map +1 -1
- package/dist/types/format/useUnit.d.ts +0 -1
- package/dist/types/format/useUnit.d.ts.map +1 -1
- package/dist/types/getDictionary.d.ts +0 -1
- package/dist/types/getDictionary.d.ts.map +1 -1
- package/dist/types/getIntlayer.d.ts +0 -1
- package/dist/types/getIntlayer.d.ts.map +1 -1
- package/dist/types/html/HTMLRenderer.d.ts +1 -4
- package/dist/types/html/HTMLRenderer.d.ts.map +1 -1
- package/dist/types/html/installIntlayerHTML.d.ts +0 -1
- package/dist/types/html/installIntlayerHTML.d.ts.map +1 -1
- package/dist/types/html/types.d.ts +2 -3
- package/dist/types/html/types.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/markdown/MarkdownRenderer.d.ts +1 -7
- package/dist/types/markdown/MarkdownRenderer.d.ts.map +1 -1
- package/dist/types/markdown/compiler.d.ts +0 -1
- package/dist/types/markdown/compiler.d.ts.map +1 -1
- package/dist/types/markdown/installIntlayerMarkdown.d.ts +8 -5
- package/dist/types/markdown/installIntlayerMarkdown.d.ts.map +1 -1
- package/dist/types/markdown/runtime.d.ts +0 -1
- package/dist/types/markdown/runtime.d.ts.map +1 -1
- package/dist/types/plugins.d.ts +3 -3
- package/dist/types/plugins.d.ts.map +1 -1
- package/dist/types/renderIntlayerNode.d.ts +1 -6
- package/dist/types/renderIntlayerNode.d.ts.map +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"installIntlayerMarkdown.cjs","names":["compileMarkdown"],"sources":["../../../src/markdown/installIntlayerMarkdown.ts"],"sourcesContent":["import type { HTMLComponents } from '../html/types';\nimport {\n compileMarkdown,\n type MarkdownCompilerOptions,\n type ParsedMarkdown,\n} from './compiler';\n\nexport type MarkdownProviderOptions = {\n /** Forces the compiler to always output content with a block-level wrapper. */\n forceBlock?: boolean;\n /** Forces the compiler to always output content with an inline wrapper. */\n forceInline?: boolean;\n /** Whether to preserve frontmatter in the markdown content. */\n preserveFrontmatter?: boolean;\n /** Whether to use the GitHub Tag Filter. */\n tagfilter?: boolean;\n};\n\nexport type RenderMarkdownOptions = MarkdownProviderOptions & {\n components?: HTMLComponents<'permissive', {}>;\n wrapper?: string;\n};\n\nexport type RenderMarkdownFunction = (\n markdown: string | ParsedMarkdown,\n options?: MarkdownProviderOptions,\n components?: HTMLComponents<'permissive', {}>,\n wrapper?: string\n) => string | Promise<string>;\n\n/**\n * Singleton instance\n */\nlet instance: IntlayerMarkdownProvider | null = null;\n\nexport type IntlayerMarkdownProvider = {\n components?: HTMLComponents<'permissive', {}>;\n renderMarkdown: RenderMarkdownFunction;\n};\n\nexport type IntlayerMarkdownPluginOptions = MarkdownProviderOptions & {\n components?: HTMLComponents<'permissive', {}>;\n wrapper?: string;\n renderMarkdown?: RenderMarkdownFunction;\n};\n\n/**\n * Create and return a single IntlayerMarkdownProvider instance.\n */\nexport const createIntlayerMarkdownClient = (\n renderMarkdown: RenderMarkdownFunction,\n components?: HTMLComponents<'permissive', {}>\n): IntlayerMarkdownProvider => {\n if (instance) return instance;\n\n instance = { components, renderMarkdown };\n return instance;\n};\n\n/**\n * Install the Intlayer Markdown provider for your vanilla JS application.\n *\n * @example\n * ```ts\n * import { installIntlayerMarkdown } from 'vanilla-intlayer/markdown';\n *\n * installIntlayerMarkdown({ forceBlock: true });\n * ```\n */\nexport const installIntlayerMarkdown = (\n pluginOptions?: IntlayerMarkdownPluginOptions | RenderMarkdownFunction\n): IntlayerMarkdownProvider => {\n let renderMarkdown: RenderMarkdownFunction;\n let providerComponents: HTMLComponents<'permissive', {}> | undefined;\n\n if (typeof pluginOptions === 'function') {\n renderMarkdown = pluginOptions;\n } else {\n const {\n components,\n wrapper,\n forceBlock,\n forceInline,\n preserveFrontmatter,\n tagfilter,\n renderMarkdown: customRender,\n } = pluginOptions ?? {};\n\n providerComponents = components;\n\n if (customRender) {\n renderMarkdown = customRender;\n } else {\n const internalOptions: MarkdownCompilerOptions = {\n forceBlock,\n forceInline,\n preserveFrontmatter,\n tagfilter,\n };\n\n renderMarkdown = (\n markdown,\n options,\n _componentsOverride,\n _wrapperOverride\n ) =>\n compileMarkdown(markdown, {\n ...internalOptions,\n forceBlock: options?.forceBlock ?? internalOptions.forceBlock,\n forceInline: options?.forceInline ?? internalOptions.forceInline,\n preserveFrontmatter:\n options?.preserveFrontmatter ?? internalOptions.preserveFrontmatter,\n tagfilter: options?.tagfilter ?? internalOptions.tagfilter,\n });\n }\n }\n\n return createIntlayerMarkdownClient(renderMarkdown, providerComponents);\n};\n\n/**\n * Access the installed IntlayerMarkdownProvider.\n * Returns a fallback renderer that compiles with default options if no\n * provider has been installed.\n */\nexport const useMarkdown = (): IntlayerMarkdownProvider => {\n if (instance) return instance;\n\n return {\n renderMarkdown: (markdown) =>\n compileMarkdown(markdown as string | ParsedMarkdown),\n };\n};\n\n/**\n * Asynchronously install a markdown renderer whose implementation is loaded\n * via a dynamic `import()`.\n *\n * Use this to keep the markdown compiler out of the initial bundle — the\n * loader is only called the first time this function is executed.\n *\n * The returned promise resolves once the provider is ready. Any calls to\n * `useMarkdown()` before the promise resolves will use the fallback\n * (raw-string) renderer.\n *\n * @param loader - A zero-argument async function that resolves to either a\n * `RenderMarkdownFunction` or an `IntlayerMarkdownPluginOptions` object.\n *\n * @example\n * ```ts\n * // Load a custom markdown renderer (e.g. marked) only when needed\n * await installIntlayerMarkdownDynamic(async () => {\n * const { marked } = await import('marked');\n * return (markdown) => marked(markdown) as string;\n * });\n * ```\n */\nexport const installIntlayerMarkdownDynamic = async (\n loader: () => Promise<IntlayerMarkdownPluginOptions | RenderMarkdownFunction>\n): Promise<IntlayerMarkdownProvider> => {\n if (instance) return instance;\n const pluginOptions = await loader();\n return installIntlayerMarkdown(pluginOptions);\n};\n"],"mappings":";;;;;;;AAiCA,IAAI,WAA4C;;;;AAgBhD,MAAa,gCACX,gBACA,eAC6B;
|
|
1
|
+
{"version":3,"file":"installIntlayerMarkdown.cjs","names":["compileMarkdown"],"sources":["../../../src/markdown/installIntlayerMarkdown.ts"],"sourcesContent":["import type { HTMLComponents } from '../html/types';\nimport {\n compileMarkdown,\n type MarkdownCompilerOptions,\n type ParsedMarkdown,\n} from './compiler';\n\nexport type MarkdownProviderOptions = {\n /** Forces the compiler to always output content with a block-level wrapper. */\n forceBlock?: boolean;\n /** Forces the compiler to always output content with an inline wrapper. */\n forceInline?: boolean;\n /** Whether to preserve frontmatter in the markdown content. */\n preserveFrontmatter?: boolean;\n /** Whether to use the GitHub Tag Filter. */\n tagfilter?: boolean;\n};\n\nexport type RenderMarkdownOptions = MarkdownProviderOptions & {\n components?: HTMLComponents<'permissive', {}>;\n wrapper?: string;\n};\n\nexport type RenderMarkdownFunction = (\n markdown: string | ParsedMarkdown,\n options?: MarkdownProviderOptions,\n components?: HTMLComponents<'permissive', {}>,\n wrapper?: string\n) => string | Promise<string>;\n\n/**\n * Singleton instance\n */\nlet instance: IntlayerMarkdownProvider | null = null;\n\nexport type IntlayerMarkdownProvider = {\n components?: HTMLComponents<'permissive', {}>;\n renderMarkdown: RenderMarkdownFunction;\n};\n\nexport type IntlayerMarkdownPluginOptions = MarkdownProviderOptions & {\n components?: HTMLComponents<'permissive', {}>;\n wrapper?: string;\n renderMarkdown?: RenderMarkdownFunction;\n};\n\n/**\n * Create and return a single IntlayerMarkdownProvider instance.\n */\nexport const createIntlayerMarkdownClient = (\n renderMarkdown: RenderMarkdownFunction,\n components?: HTMLComponents<'permissive', {}>\n): IntlayerMarkdownProvider => {\n if (instance) return instance;\n\n instance = { components, renderMarkdown };\n return instance;\n};\n\n/**\n * Install the Intlayer Markdown provider for your vanilla JS application.\n *\n * @example\n * ```ts\n * import { installIntlayerMarkdown } from 'vanilla-intlayer/markdown';\n *\n * installIntlayerMarkdown({ forceBlock: true });\n * ```\n */\nexport const installIntlayerMarkdown = (\n pluginOptions?: IntlayerMarkdownPluginOptions | RenderMarkdownFunction\n): IntlayerMarkdownProvider => {\n let renderMarkdown: RenderMarkdownFunction;\n let providerComponents: HTMLComponents<'permissive', {}> | undefined;\n\n if (typeof pluginOptions === 'function') {\n renderMarkdown = pluginOptions;\n } else {\n const {\n components,\n wrapper,\n forceBlock,\n forceInline,\n preserveFrontmatter,\n tagfilter,\n renderMarkdown: customRender,\n } = pluginOptions ?? {};\n\n providerComponents = components;\n\n if (customRender) {\n renderMarkdown = customRender;\n } else {\n const internalOptions: MarkdownCompilerOptions = {\n forceBlock,\n forceInline,\n preserveFrontmatter,\n tagfilter,\n };\n\n renderMarkdown = (\n markdown,\n options,\n _componentsOverride,\n _wrapperOverride\n ) =>\n compileMarkdown(markdown, {\n ...internalOptions,\n forceBlock: options?.forceBlock ?? internalOptions.forceBlock,\n forceInline: options?.forceInline ?? internalOptions.forceInline,\n preserveFrontmatter:\n options?.preserveFrontmatter ?? internalOptions.preserveFrontmatter,\n tagfilter: options?.tagfilter ?? internalOptions.tagfilter,\n });\n }\n }\n\n return createIntlayerMarkdownClient(renderMarkdown, providerComponents);\n};\n\n/**\n * Access the installed IntlayerMarkdownProvider.\n * Returns a fallback renderer that compiles with default options if no\n * provider has been installed.\n */\nexport const useMarkdown = (): IntlayerMarkdownProvider => {\n if (instance) return instance;\n\n return {\n renderMarkdown: (markdown) =>\n compileMarkdown(markdown as string | ParsedMarkdown),\n };\n};\n\n/**\n * Asynchronously install a markdown renderer whose implementation is loaded\n * via a dynamic `import()`.\n *\n * Use this to keep the markdown compiler out of the initial bundle — the\n * loader is only called the first time this function is executed.\n *\n * The returned promise resolves once the provider is ready. Any calls to\n * `useMarkdown()` before the promise resolves will use the fallback\n * (raw-string) renderer.\n *\n * @param loader - A zero-argument async function that resolves to either a\n * `RenderMarkdownFunction` or an `IntlayerMarkdownPluginOptions` object.\n *\n * @example\n * ```ts\n * // Load a custom markdown renderer (e.g. marked) only when needed\n * await installIntlayerMarkdownDynamic(async () => {\n * const { marked } = await import('marked');\n * return (markdown) => marked(markdown) as string;\n * });\n * ```\n */\nexport const installIntlayerMarkdownDynamic = async (\n loader: () => Promise<IntlayerMarkdownPluginOptions | RenderMarkdownFunction>\n): Promise<IntlayerMarkdownProvider> => {\n if (instance) return instance;\n const pluginOptions = await loader();\n return installIntlayerMarkdown(pluginOptions);\n};\n"],"mappings":";;;;;;;AAiCA,IAAI,WAA4C;;;;AAgBhD,MAAa,gCACX,gBACA,eAC6B;CAC7B,IAAI,UAAU,OAAO;CAErB,WAAW;EAAE;EAAY;CAAe;CACxC,OAAO;AACT;;;;;;;;;;;AAYA,MAAa,2BACX,kBAC6B;CAC7B,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO,kBAAkB,YAC3B,iBAAiB;MACZ;EACL,MAAM,EACJ,YACA,SACA,YACA,aACA,qBACA,WACA,gBAAgB,iBACd,iBAAiB,CAAC;EAEtB,qBAAqB;EAErB,IAAI,cACF,iBAAiB;OACZ;GACL,MAAM,kBAA2C;IAC/C;IACA;IACA;IACA;GACF;GAEA,kBACE,UACA,SACA,qBACA,qBAEAA,0CAAgB,UAAU;IACxB,GAAG;IACH,YAAY,SAAS,cAAc,gBAAgB;IACnD,aAAa,SAAS,eAAe,gBAAgB;IACrD,qBACE,SAAS,uBAAuB,gBAAgB;IAClD,WAAW,SAAS,aAAa,gBAAgB;GACnD,CAAC;EACL;CACF;CAEA,OAAO,6BAA6B,gBAAgB,kBAAkB;AACxE;;;;;;AAOA,MAAa,oBAA8C;CACzD,IAAI,UAAU,OAAO;CAErB,OAAO,EACL,iBAAiB,aACfA,0CAAgB,QAAmC,EACvD;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,iCAAiC,OAC5C,WACsC;CACtC,IAAI,UAAU,OAAO;CACrB,MAAM,gBAAgB,MAAM,OAAO;CACnC,OAAO,wBAAwB,aAAa;AAC9C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
|
|
2
2
|
|
|
3
3
|
//#region src/markdown/runtime.ts
|
|
4
|
-
const SELF_CLOSING_TAGS = new Set([
|
|
4
|
+
const SELF_CLOSING_TAGS = /* @__PURE__ */ new Set([
|
|
5
5
|
"area",
|
|
6
6
|
"base",
|
|
7
7
|
"br",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.cjs","names":[],"sources":["../../../src/markdown/runtime.ts"],"sourcesContent":["/**\n * Vanilla JS adapter for the framework-agnostic markdown processor.\n *\n * Builds HTML strings which can be inserted into the DOM via `innerHTML`\n * or the `renderMarkdown` utility.\n */\n\nimport type { HTMLTag, MarkdownRuntime } from '@intlayer/core/markdown';\n\nconst SELF_CLOSING_TAGS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nconst buildPropsString = (props: Record<string, any> | null): string => {\n if (!props) return '';\n\n return Object.entries(props)\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => {\n if (typeof v === 'boolean') return v ? k : '';\n if (k === '_innerHTML') return ''; // handled separately\n return `${k}=\"${String(v).replace(/&/g, '&').replace(/\"/g, '"')}\"`;\n })\n .filter(Boolean)\n .join(' ');\n};\n\nconst VANILLA_FRAGMENT = '__vanilla_fragment__';\n\n/**\n * Vanilla-specific MarkdownRuntime that produces HTML strings.\n */\nexport const vanillaRuntime: MarkdownRuntime = {\n createElement: (\n type: any,\n props: Record<string, any> | null,\n ...children: any[]\n ): string => {\n const childStr = children.flat(Infinity).join('');\n\n if (type === VANILLA_FRAGMENT) return childStr;\n\n if (typeof type === 'string') {\n const propsStr = buildPropsString(props);\n const propsWithSpace = propsStr ? ` ${propsStr}` : '';\n const innerHTML = props?._innerHTML;\n\n if (SELF_CLOSING_TAGS.has(type)) {\n return `<${type}${propsWithSpace}>`;\n }\n\n if (innerHTML !== undefined) {\n return `<${type}${propsWithSpace}>${innerHTML}</${type}>`;\n }\n\n return `<${type}${propsWithSpace}>${childStr}</${type}>`;\n }\n\n // Function component override — returns a string\n if (typeof type === 'function') {\n try {\n const result = type({ ...props, children: childStr });\n return typeof result === 'string' ? result : childStr;\n } catch {\n return childStr;\n }\n }\n\n return childStr;\n },\n\n cloneElement: (\n element: unknown,\n _props: Record<string, any>,\n ..._children: any[]\n ): string => {\n return typeof element === 'string' ? element : String(element ?? '');\n },\n\n Fragment: VANILLA_FRAGMENT as any,\n\n /**\n * Normalize props to standard HTML attribute names.\n */\n normalizeProps: (\n _tag: HTMLTag,\n props: Record<string, any>\n ): Record<string, any> => {\n const normalized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(props)) {\n if (key === 'className') {\n normalized.class = value;\n } else if (key === 'htmlFor') {\n normalized.for = value;\n } else if (key === 'dangerouslySetInnerHTML' && value?.__html) {\n normalized._innerHTML = value.__html;\n } else {\n normalized[key] = value;\n }\n }\n\n return normalized;\n },\n};\n\n/**\n * Creates a vanilla runtime with a custom createElement for advanced use cases.\n */\nexport const createVanillaRuntime = (\n options: {\n onCreateElement?: (\n type: any,\n props: Record<string, any> | null,\n children: any[]\n ) => string;\n } = {}\n): MarkdownRuntime => {\n const { onCreateElement } = options;\n\n if (onCreateElement) {\n return {\n ...vanillaRuntime,\n createElement: (\n type: any,\n props: Record<string, any> | null,\n ...children: any[]\n ): string => onCreateElement(type, props, children),\n };\n }\n\n return vanillaRuntime;\n};\n\nexport default vanillaRuntime;\n"],"mappings":";;;AASA,MAAM,
|
|
1
|
+
{"version":3,"file":"runtime.cjs","names":[],"sources":["../../../src/markdown/runtime.ts"],"sourcesContent":["/**\n * Vanilla JS adapter for the framework-agnostic markdown processor.\n *\n * Builds HTML strings which can be inserted into the DOM via `innerHTML`\n * or the `renderMarkdown` utility.\n */\n\nimport type { HTMLTag, MarkdownRuntime } from '@intlayer/core/markdown';\n\nconst SELF_CLOSING_TAGS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nconst buildPropsString = (props: Record<string, any> | null): string => {\n if (!props) return '';\n\n return Object.entries(props)\n .filter(([, v]) => v !== undefined && v !== null)\n .map(([k, v]) => {\n if (typeof v === 'boolean') return v ? k : '';\n if (k === '_innerHTML') return ''; // handled separately\n return `${k}=\"${String(v).replace(/&/g, '&').replace(/\"/g, '"')}\"`;\n })\n .filter(Boolean)\n .join(' ');\n};\n\nconst VANILLA_FRAGMENT = '__vanilla_fragment__';\n\n/**\n * Vanilla-specific MarkdownRuntime that produces HTML strings.\n */\nexport const vanillaRuntime: MarkdownRuntime = {\n createElement: (\n type: any,\n props: Record<string, any> | null,\n ...children: any[]\n ): string => {\n const childStr = children.flat(Infinity).join('');\n\n if (type === VANILLA_FRAGMENT) return childStr;\n\n if (typeof type === 'string') {\n const propsStr = buildPropsString(props);\n const propsWithSpace = propsStr ? ` ${propsStr}` : '';\n const innerHTML = props?._innerHTML;\n\n if (SELF_CLOSING_TAGS.has(type)) {\n return `<${type}${propsWithSpace}>`;\n }\n\n if (innerHTML !== undefined) {\n return `<${type}${propsWithSpace}>${innerHTML}</${type}>`;\n }\n\n return `<${type}${propsWithSpace}>${childStr}</${type}>`;\n }\n\n // Function component override — returns a string\n if (typeof type === 'function') {\n try {\n const result = type({ ...props, children: childStr });\n return typeof result === 'string' ? result : childStr;\n } catch {\n return childStr;\n }\n }\n\n return childStr;\n },\n\n cloneElement: (\n element: unknown,\n _props: Record<string, any>,\n ..._children: any[]\n ): string => {\n return typeof element === 'string' ? element : String(element ?? '');\n },\n\n Fragment: VANILLA_FRAGMENT as any,\n\n /**\n * Normalize props to standard HTML attribute names.\n */\n normalizeProps: (\n _tag: HTMLTag,\n props: Record<string, any>\n ): Record<string, any> => {\n const normalized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(props)) {\n if (key === 'className') {\n normalized.class = value;\n } else if (key === 'htmlFor') {\n normalized.for = value;\n } else if (key === 'dangerouslySetInnerHTML' && value?.__html) {\n normalized._innerHTML = value.__html;\n } else {\n normalized[key] = value;\n }\n }\n\n return normalized;\n },\n};\n\n/**\n * Creates a vanilla runtime with a custom createElement for advanced use cases.\n */\nexport const createVanillaRuntime = (\n options: {\n onCreateElement?: (\n type: any,\n props: Record<string, any> | null,\n children: any[]\n ) => string;\n } = {}\n): MarkdownRuntime => {\n const { onCreateElement } = options;\n\n if (onCreateElement) {\n return {\n ...vanillaRuntime,\n createElement: (\n type: any,\n props: Record<string, any> | null,\n ...children: any[]\n ): string => onCreateElement(type, props, children),\n };\n }\n\n return vanillaRuntime;\n};\n\nexport default vanillaRuntime;\n"],"mappings":";;;AASA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,oBAAoB,UAA8C;CACtE,IAAI,CAAC,OAAO,OAAO;CAEnB,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,QAAQ,GAAG,OAAO,MAAM,UAAa,MAAM,IAAI,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO;EACf,IAAI,OAAO,MAAM,WAAW,OAAO,IAAI,IAAI;EAC3C,IAAI,MAAM,cAAc,OAAO;EAC/B,OAAO,GAAG,EAAE,IAAI,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,EAAE;CAC3E,CAAC,CAAC,CACD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,aACQ,gBAAgB,MAAM,OAAO,QAAQ;CACpD;CAGF,OAAO;AACT"}
|
package/dist/cjs/plugins.cjs
CHANGED
|
@@ -54,8 +54,9 @@ const insertionPlugin = process.env.INTLAYER_NODE_TYPE_INSERTION === "false" ? _
|
|
|
54
54
|
const children = node[_intlayer_types_nodeType.INSERTION];
|
|
55
55
|
const insertionStringPlugin = {
|
|
56
56
|
id: "insertion-string-plugin",
|
|
57
|
-
canHandle: (node) => typeof node === "string",
|
|
57
|
+
canHandle: (node) => typeof node === "string" || (0, _intlayer_core_interpreter.isInterpolableWrapperNode)(node),
|
|
58
58
|
transform: (node, subProps, deepTransformNode) => {
|
|
59
|
+
if ((0, _intlayer_core_interpreter.isInterpolableWrapperNode)(node)) return (values) => (0, _intlayer_core_interpreter.transformInterpolableNode)(node, values, subProps, props.plugins, deepTransformNode);
|
|
59
60
|
const transformedResult = deepTransformNode(node, {
|
|
60
61
|
...subProps,
|
|
61
62
|
children: node,
|
|
@@ -171,7 +172,7 @@ const htmlPlugin = process.env.INTLAYER_NODE_TYPE_HTML === "false" ? _intlayer_c
|
|
|
171
172
|
transform: (node, props) => {
|
|
172
173
|
const htmlStr = node[_intlayer_types_nodeType.HTML];
|
|
173
174
|
const use = (components = {}) => {
|
|
174
|
-
const
|
|
175
|
+
const wrappedComponents = new Proxy(components, { get(target, prop) {
|
|
175
176
|
if (typeof prop === "string" && prop in target) {
|
|
176
177
|
const Component = target[prop];
|
|
177
178
|
return (props) => {
|
|
@@ -187,7 +188,8 @@ const htmlPlugin = process.env.INTLAYER_NODE_TYPE_HTML === "false" ? _intlayer_c
|
|
|
187
188
|
const children = Array.isArray(props.children) ? props.children.join("") : props.children;
|
|
188
189
|
return `<${prop}${attrs ? ` ${attrs}` : ""}>${children}</${prop}>`;
|
|
189
190
|
};
|
|
190
|
-
} })
|
|
191
|
+
} });
|
|
192
|
+
const result = (0, _intlayer_core_interpreter.getHTML)(htmlStr, wrappedComponents);
|
|
191
193
|
return Array.isArray(result) ? result.join("") : result;
|
|
192
194
|
};
|
|
193
195
|
const value = use();
|
package/dist/cjs/plugins.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.cjs","names":["editor","renderIntlayerNode","fallbackPlugin","NodeTypes","internationalization","enumerationPlugin","conditionPlugin","filePlugin","genderPlugin"],"sources":["../../src/plugins.ts"],"sourcesContent":["import { editor, internationalization } from '@intlayer/config/built';\nimport {\n conditionPlugin,\n type DeepTransformContent as DeepTransformContentCore,\n enumerationPlugin,\n fallbackPlugin,\n filePlugin,\n genderPlugin,\n getHTML,\n type IInterpreterPluginState as IInterpreterPluginStateCore,\n nestedPlugin,\n type Plugins,\n pluralPlugin,\n splitInsertionTemplate,\n translationPlugin,\n} from '@intlayer/core/interpreter';\nimport {\n compileWithOptions,\n getMarkdownMetadata,\n} from '@intlayer/core/markdown';\nimport type {\n HTMLContent,\n InsertionContent,\n MarkdownContent,\n} from '@intlayer/core/transpiler';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type { HTMLComponents } from './html/types';\nimport {\n type IntlayerNode as IntlayerNodeCore,\n renderIntlayerNode,\n} from './renderIntlayerNode';\n\n/** ---------------------------------------------\n * INTLAYER NODE PLUGIN\n * --------------------------------------------- */\n\nexport type IntlayerNodeCond<T> = T extends number | string\n ? IntlayerNode<T>\n : never;\n\nexport type IntlayerNode<T, P = {}> = IntlayerNodeCore<T> & P;\n\nconst escapeHtmlAttr = (str: string): string =>\n str.replace(/&/g, '&').replace(/\"/g, '"');\n\nconst escapeHtmlText = (str: string): string =>\n str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nexport const intlayerNodePlugins: Plugins = {\n id: 'intlayer-node-plugin',\n canHandle: (node) =>\n typeof node === 'bigint' ||\n typeof node === 'string' ||\n typeof node === 'number',\n transform: (_node, { children, keyPath, dictionaryKey, ...rest }) => {\n if (process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled) {\n const rawStr = String(children ?? '');\n const keyPathJson = JSON.stringify(keyPath ?? []);\n const dictKey = String(dictionaryKey ?? '');\n\n /**\n * In editor mode, string coercion returns the wrapper HTML so that\n * `element.innerHTML = content.title` automatically inserts the\n * `<intlayer-content-selector-wrapper>` into the DOM.\n */\n const htmlStr = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(rawStr)}</intlayer-content-selector-wrapper>`;\n\n return renderIntlayerNode({\n ...rest,\n value: children as string,\n children: htmlStr,\n keyPath,\n dictionaryKey,\n additionalProps: {\n toElement: (): HTMLElement => {\n const wrapper = document.createElement(\n 'intlayer-content-selector-wrapper'\n );\n wrapper.setAttribute('key-path', keyPathJson);\n wrapper.setAttribute('dictionary-key', dictKey);\n wrapper.textContent = rawStr;\n return wrapper;\n },\n },\n });\n }\n\n return renderIntlayerNode({\n ...rest,\n value: children as string,\n children,\n });\n },\n};\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, _S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer I;\n fields: readonly (infer F)[];\n}\n ? <V extends { [K in Extract<F, string>]: string | number }>(\n values: V\n ) => I extends string ? IntlayerNode<string> : DeepTransformContent<I, L>\n : never;\n\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n { type: NodeTypes.INSERTION },\n ];\n\n const children = node[NodeTypes.INSERTION];\n\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, subProps, deepTransformNode) => {\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: (props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const result = splitInsertionTemplate(\n transformedResult,\n values\n );\n const resultStr = result.isSimple\n ? (result.parts as string)\n : (result.parts as string[]).join('');\n\n return deepTransformNode(resultStr, {\n ...subProps,\n plugins: props.plugins,\n children: resultStr,\n });\n };\n },\n };\n\n const transformed = deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n\n if (\n typeof children === 'object' &&\n children !== null &&\n 'nodeType' in children &&\n (\n [NodeTypes.ENUMERATION, NodeTypes.CONDITION] as NodeType[]\n ).includes(children.nodeType as NodeType)\n ) {\n return (values: any) => (arg: any) => {\n const inner = (transformed as (a: any) => any)(arg);\n return typeof inner === 'function' ? inner(values) : inner;\n };\n }\n\n return transformed;\n },\n };\n\n/** ---------------------------------------------\n * MARKDOWN PLUGIN\n * --------------------------------------------- */\n\nconst vanillaRuntime = {\n createElement: (tag: string, props: any, ...children: any[]) => {\n const attrs = Object.entries(props || {})\n .filter(\n ([key]) => key !== 'children' && key !== 'key' && key !== '_innerHTML'\n )\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(' ');\n const innerHTML = props?._innerHTML;\n const childrenStr =\n innerHTML !== undefined ? innerHTML : children.flat(Infinity).join('');\n return `<${tag}${attrs ? ` ${attrs}` : ''}>${childrenStr}</${tag}>`;\n },\n normalizeProps: (_tag: string, props: Record<string, any>) => {\n const normalized: Record<string, any> = {};\n for (const [key, value] of Object.entries(props)) {\n if (key === 'className') {\n normalized.class = value;\n } else if (key === 'htmlFor') {\n normalized.for = value;\n } else if (key === 'dangerouslySetInnerHTML' && (value as any)?.__html) {\n normalized._innerHTML = (value as any).__html;\n } else {\n normalized[key] = value;\n }\n }\n return normalized;\n },\n};\n\nexport type MarkdownStringCond<T> = T extends string\n ? IntlayerNode<\n string,\n {\n metadata: DeepTransformContent<string>;\n /** Returns the rendered markdown; render with .use(). */\n use: (components?: HTMLComponents<'permissive', {}>) => string;\n }\n >\n : never;\n\nexport const markdownStringPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, props, deepTransformNode) => {\n const { plugins: _plugins, ...rest } = props;\n const metadata = getMarkdownMetadata(node) ?? {};\n\n const metadataPlugins: Plugins = {\n id: 'markdown-metadata-plugin',\n canHandle: (metadataNode) =>\n typeof metadataNode === 'string' ||\n typeof metadataNode === 'number' ||\n typeof metadataNode === 'boolean' ||\n !metadataNode,\n transform: (metadataNode, subProps) =>\n renderIntlayerNode({\n ...subProps,\n value: metadataNode,\n children: node,\n }),\n };\n\n const metadataNodes = deepTransformNode(metadata, {\n plugins: [metadataPlugins],\n dictionaryKey: rest.dictionaryKey,\n keyPath: [],\n });\n\n const compile = (components: any = {}) =>\n compileWithOptions(\n node,\n {\n ...vanillaRuntime,\n createElement: (tag: any, props: any, ...children: any[]) => {\n const override = components[tag];\n if (typeof override === 'function') {\n return override({ ...props, children: children.join('') });\n }\n return vanillaRuntime.createElement(tag, props, ...children);\n },\n },\n {}\n ) as any;\n\n const value = compile();\n let children = node;\n\n if (\n process.env.INTLAYER_EDITOR_ENABLED !== 'false' &&\n editor.enabled\n ) {\n const keyPathJson = JSON.stringify(props.keyPath ?? []);\n const dictKey = String(props.dictionaryKey ?? '');\n children = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(value)}</intlayer-content-selector-wrapper>`;\n }\n\n return renderIntlayerNode({\n ...props,\n value,\n children,\n additionalProps: {\n metadata: metadataNodes,\n use: (components?: any) => compile(components),\n },\n }) as any;\n },\n };\n\nexport type MarkdownCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.MARKDOWN]: infer M;\n metadata?: infer U;\n tags?: infer U;\n}\n ? {\n use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode<M>;\n metadata: DeepTransformContent<U>;\n }\n : never;\n\nexport const markdownPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.MARKDOWN,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n { type: NodeTypes.MARKDOWN },\n ];\n const children = node[NodeTypes.MARKDOWN];\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [markdownStringPlugin, ...(props.plugins ?? [])],\n });\n },\n };\n\n/** ---------------------------------------------\n * HTML PLUGIN\n * --------------------------------------------- */\n\nexport type HTMLPluginCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.HTML]: infer I;\n tags?: infer U;\n}\n ? {\n use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode<I>;\n }\n : never;\n\nexport const htmlPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_HTML === 'false'\n ? fallbackPlugin\n : {\n id: 'html-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.HTML,\n transform: (node: HTMLContent<string>, props) => {\n const htmlStr = node[NodeTypes.HTML];\n\n const use = (components: Record<string, any> = {}) => {\n const wrappedComponents = new Proxy(components, {\n get(target, prop) {\n if (typeof prop === 'string' && prop in target) {\n const Component = target[prop];\n return (props: any) => {\n const children = Array.isArray(props.children)\n ? props.children.join('')\n : props.children;\n return Component({ ...props, children });\n };\n }\n if (typeof prop === 'string' && /^[a-z][a-z0-9]*$/.test(prop)) {\n return (props: any) => {\n const attrs = Object.entries(props)\n .filter(([key]) => key !== 'children' && key !== 'key')\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(' ');\n const children = Array.isArray(props.children)\n ? props.children.join('')\n : props.children;\n return `<${prop}${attrs ? ` ${attrs}` : ''}>${children}</${prop}>`;\n };\n }\n return undefined;\n },\n });\n\n const result = getHTML(htmlStr, wrappedComponents as any);\n return Array.isArray(result) ? result.join('') : result;\n };\n\n const value = use();\n let children = htmlStr;\n\n if (\n process.env.INTLAYER_EDITOR_ENABLED !== 'false' &&\n editor.enabled\n ) {\n const keyPathJson = JSON.stringify(props.keyPath ?? []);\n const dictKey = String(props.dictionaryKey ?? '');\n children = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(value)}</intlayer-content-selector-wrapper>`;\n }\n\n return renderIntlayerNode({\n ...props,\n value,\n children,\n additionalProps: {\n use: (components?: any) => use(components),\n },\n });\n },\n };\n\n/** ---------------------------------------------\n * PLUGINS RESULT\n * --------------------------------------------- */\n\nexport interface IInterpreterPluginVanilla<T, S, L extends LocalesValues> {\n vanillaIntlayerNode: IntlayerNodeCond<T>;\n vanillaInsertion: InsertionCond<T, S, L>;\n vanillaMarkdown: MarkdownCond<T>;\n vanillaHtml: HTMLPluginCond<T>;\n}\n\n/**\n * Insert this type as param of `DeepTransformContent` to avoid `intlayer` package pollution.\n *\n * Otherwise the `vanilla-intlayer` plugins will override the types of `intlayer` functions.\n * Use `getIntlayer` from `vanilla-intlayer` (not from `intlayer`) to get properly typed\n * `IntlayerNode` wrappers with `.value` access on string/number content.\n */\nexport type IInterpreterPluginState = Omit<\n IInterpreterPluginStateCore,\n 'insertion'\n> & {\n vanillaIntlayerNode: true;\n vanillaInsertion: true;\n vanillaMarkdown: true;\n vanillaHtml: true;\n};\n\nexport type DeepTransformContent<\n T,\n L extends LocalesValues = DeclaredLocales,\n> = DeepTransformContentCore<T, IInterpreterPluginState, L>;\n\nconst pluginsCache = new Map<string, Plugins[]>();\n\n/**\n * Get the plugins array for Vanilla content transformation.\n * This function is used by both getIntlayer and getDictionary to ensure consistent plugin configuration.\n */\nexport const getPlugins = (\n locale?: LocalesValues,\n fallback = true\n): Plugins[] => {\n const currentLocale = locale ?? internationalization.defaultLocale;\n const cacheKey = `${currentLocale}_${fallback}`;\n\n if (pluginsCache.has(cacheKey)) {\n return pluginsCache.get(cacheKey)!;\n }\n\n const plugins = [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n pluralPlugin(locale ?? internationalization.defaultLocale),\n conditionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n intlayerNodePlugins,\n insertionPlugin,\n markdownPlugin,\n htmlPlugin,\n ] as Plugins[];\n\n pluginsCache.set(cacheKey, plugins);\n\n return plugins;\n};\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,kBAAkB,QACtB,IAAI,QAAQ,MAAM,QAAQ,CAAC,QAAQ,MAAM,SAAS;AAEpD,MAAM,kBAAkB,QACtB,IAAI,QAAQ,MAAM,QAAQ,CAAC,QAAQ,MAAM,OAAO,CAAC,QAAQ,MAAM,OAAO;AAExE,MAAa,sBAA+B;CAC1C,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAChB,OAAO,SAAS,YAChB,OAAO,SAAS;CAClB,YAAY,OAAO,EAAE,UAAU,SAAS,eAAe,GAAG,WAAW;AACnE,MAAI,QAAQ,IAAI,4BAA4B,WAAWA,8BAAO,SAAS;GACrE,MAAM,SAAS,OAAO,YAAY,GAAG;GACrC,MAAM,cAAc,KAAK,UAAU,WAAW,EAAE,CAAC;GACjD,MAAM,UAAU,OAAO,iBAAiB,GAAG;;;;;;GAO3C,MAAM,UAAU,gDAAgD,eAA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AW,gDAAgD,eAAe,YAAY,CAAC,oBAAoB,eAAe,QAAQ,CAAC,IAAI,eAAe,MAAM,CAAC;;AAG/J,SAAOC,8CAAmB;GACxB,GAAG;GACH;GACA;GACA,iBAAiB,EACf,MAAM,eAAqB,IAAI,WAAW,EAC3C;GACF,CAAC;;CAEL;AAmCP,MAAM,+BAAe,IAAI,KAAwB;;;;;AAMjD,MAAa,cACX,QACA,WAAW,SACG;CAEd,MAAM,WAAW,GADK,UAAUG,4CAAqB,cACnB,GAAG;AAErC,KAAI,aAAa,IAAI,SAAS,CAC5B,QAAO,aAAa,IAAI,SAAS;CAGnC,MAAM,UAAU;oDAEZ,UAAUA,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,OACjD;EACDC;+CACa,UAAUD,4CAAqB,cAAc;EAC1DE;+CACa,UAAUF,4CAAqB,cAAc;EAC1DG;EACAC;EACA;EACA;EACA;EACA;EACD;AAED,cAAa,IAAI,UAAU,QAAQ;AAEnC,QAAO"}
|
|
1
|
+
{"version":3,"file":"plugins.cjs","names":["editor","renderIntlayerNode","fallbackPlugin","NodeTypes","internationalization","enumerationPlugin","conditionPlugin","filePlugin","genderPlugin"],"sources":["../../src/plugins.ts"],"sourcesContent":["import { editor, internationalization } from '@intlayer/config/built';\nimport {\n conditionPlugin,\n type DeepTransformContent as DeepTransformContentCore,\n enumerationPlugin,\n fallbackPlugin,\n filePlugin,\n genderPlugin,\n getHTML,\n type IInterpreterPluginState as IInterpreterPluginStateCore,\n isInterpolableWrapperNode,\n nestedPlugin,\n type Plugins,\n pluralPlugin,\n splitInsertionTemplate,\n transformInterpolableNode,\n translationPlugin,\n} from '@intlayer/core/interpreter';\nimport {\n compileWithOptions,\n getMarkdownMetadata,\n} from '@intlayer/core/markdown';\nimport type {\n HTMLContent,\n InsertionContent,\n MarkdownContent,\n} from '@intlayer/core/transpiler';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type { HTMLComponents } from './html/types';\nimport {\n type IntlayerNode as IntlayerNodeCore,\n renderIntlayerNode,\n} from './renderIntlayerNode';\n\n/** ---------------------------------------------\n * INTLAYER NODE PLUGIN\n * --------------------------------------------- */\n\nexport type IntlayerNodeCond<T> = T extends number | string\n ? IntlayerNode<T>\n : never;\n\nexport type IntlayerNode<T, P = {}> = IntlayerNodeCore<T> & P;\n\nconst escapeHtmlAttr = (str: string): string =>\n str.replace(/&/g, '&').replace(/\"/g, '"');\n\nconst escapeHtmlText = (str: string): string =>\n str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nexport const intlayerNodePlugins: Plugins = {\n id: 'intlayer-node-plugin',\n canHandle: (node) =>\n typeof node === 'bigint' ||\n typeof node === 'string' ||\n typeof node === 'number',\n transform: (_node, { children, keyPath, dictionaryKey, ...rest }) => {\n if (process.env.INTLAYER_EDITOR_ENABLED !== 'false' && editor.enabled) {\n const rawStr = String(children ?? '');\n const keyPathJson = JSON.stringify(keyPath ?? []);\n const dictKey = String(dictionaryKey ?? '');\n\n /**\n * In editor mode, string coercion returns the wrapper HTML so that\n * `element.innerHTML = content.title` automatically inserts the\n * `<intlayer-content-selector-wrapper>` into the DOM.\n */\n const htmlStr = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(rawStr)}</intlayer-content-selector-wrapper>`;\n\n return renderIntlayerNode({\n ...rest,\n value: children as string,\n children: htmlStr,\n keyPath,\n dictionaryKey,\n additionalProps: {\n toElement: (): HTMLElement => {\n const wrapper = document.createElement(\n 'intlayer-content-selector-wrapper'\n );\n wrapper.setAttribute('key-path', keyPathJson);\n wrapper.setAttribute('dictionary-key', dictKey);\n wrapper.textContent = rawStr;\n return wrapper;\n },\n },\n });\n }\n\n return renderIntlayerNode({\n ...rest,\n value: children as string,\n children,\n });\n },\n};\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, _S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer I;\n fields: readonly (infer F)[];\n}\n ? <V extends { [K in Extract<F, string>]: string | number }>(\n values: V\n ) => I extends string ? IntlayerNode<string> : DeepTransformContent<I, L>\n : never;\n\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n { type: NodeTypes.INSERTION },\n ];\n\n const children = node[NodeTypes.INSERTION];\n\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) =>\n typeof node === 'string' || isInterpolableWrapperNode(node),\n transform: (node, subProps, deepTransformNode) => {\n // `html()`/`markdown()` nodes carry their `{{ … }}` placeholders\n // inside a raw string. Interpolate into that string, then re-run\n // the transform so the html/markdown renderer applies afterwards.\n if (isInterpolableWrapperNode(node)) {\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) =>\n transformInterpolableNode(\n node,\n values,\n subProps,\n props.plugins,\n deepTransformNode\n );\n }\n\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: (props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const result = splitInsertionTemplate(\n transformedResult,\n values\n );\n const resultStr = result.isSimple\n ? (result.parts as string)\n : (result.parts as string[]).join('');\n\n return deepTransformNode(resultStr, {\n ...subProps,\n plugins: props.plugins,\n children: resultStr,\n });\n };\n },\n };\n\n const transformed = deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n\n if (\n typeof children === 'object' &&\n children !== null &&\n 'nodeType' in children &&\n (\n [NodeTypes.ENUMERATION, NodeTypes.CONDITION] as NodeType[]\n ).includes(children.nodeType as NodeType)\n ) {\n return (values: any) => (arg: any) => {\n const inner = (transformed as (a: any) => any)(arg);\n return typeof inner === 'function' ? inner(values) : inner;\n };\n }\n\n return transformed;\n },\n };\n\n/** ---------------------------------------------\n * MARKDOWN PLUGIN\n * --------------------------------------------- */\n\nconst vanillaRuntime = {\n createElement: (tag: string, props: any, ...children: any[]) => {\n const attrs = Object.entries(props || {})\n .filter(\n ([key]) => key !== 'children' && key !== 'key' && key !== '_innerHTML'\n )\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(' ');\n const innerHTML = props?._innerHTML;\n const childrenStr =\n innerHTML !== undefined ? innerHTML : children.flat(Infinity).join('');\n return `<${tag}${attrs ? ` ${attrs}` : ''}>${childrenStr}</${tag}>`;\n },\n normalizeProps: (_tag: string, props: Record<string, any>) => {\n const normalized: Record<string, any> = {};\n for (const [key, value] of Object.entries(props)) {\n if (key === 'className') {\n normalized.class = value;\n } else if (key === 'htmlFor') {\n normalized.for = value;\n } else if (key === 'dangerouslySetInnerHTML' && (value as any)?.__html) {\n normalized._innerHTML = (value as any).__html;\n } else {\n normalized[key] = value;\n }\n }\n return normalized;\n },\n};\n\nexport type MarkdownStringCond<T> = T extends string\n ? IntlayerNode<\n string,\n {\n metadata: DeepTransformContent<string>;\n /** Returns the rendered markdown; render with .use(). */\n use: (components?: HTMLComponents<'permissive', {}>) => string;\n }\n >\n : never;\n\nexport const markdownStringPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, props, deepTransformNode) => {\n const { plugins: _plugins, ...rest } = props;\n const metadata = getMarkdownMetadata(node) ?? {};\n\n const metadataPlugins: Plugins = {\n id: 'markdown-metadata-plugin',\n canHandle: (metadataNode) =>\n typeof metadataNode === 'string' ||\n typeof metadataNode === 'number' ||\n typeof metadataNode === 'boolean' ||\n !metadataNode,\n transform: (metadataNode, subProps) =>\n renderIntlayerNode({\n ...subProps,\n value: metadataNode,\n children: node,\n }),\n };\n\n const metadataNodes = deepTransformNode(metadata, {\n plugins: [metadataPlugins],\n dictionaryKey: rest.dictionaryKey,\n keyPath: [],\n });\n\n const compile = (components: any = {}) =>\n compileWithOptions(\n node,\n {\n ...vanillaRuntime,\n createElement: (tag: any, props: any, ...children: any[]) => {\n const override = components[tag];\n if (typeof override === 'function') {\n return override({ ...props, children: children.join('') });\n }\n return vanillaRuntime.createElement(tag, props, ...children);\n },\n },\n {}\n ) as any;\n\n const value = compile();\n let children = node;\n\n if (\n process.env.INTLAYER_EDITOR_ENABLED !== 'false' &&\n editor.enabled\n ) {\n const keyPathJson = JSON.stringify(props.keyPath ?? []);\n const dictKey = String(props.dictionaryKey ?? '');\n children = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(value)}</intlayer-content-selector-wrapper>`;\n }\n\n return renderIntlayerNode({\n ...props,\n value,\n children,\n additionalProps: {\n metadata: metadataNodes,\n use: (components?: any) => compile(components),\n },\n }) as any;\n },\n };\n\nexport type MarkdownCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.MARKDOWN]: infer M;\n metadata?: infer U;\n tags?: infer U;\n}\n ? {\n use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode<M>;\n metadata: DeepTransformContent<U>;\n }\n : never;\n\nexport const markdownPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.MARKDOWN,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n { type: NodeTypes.MARKDOWN },\n ];\n const children = node[NodeTypes.MARKDOWN];\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [markdownStringPlugin, ...(props.plugins ?? [])],\n });\n },\n };\n\n/** ---------------------------------------------\n * HTML PLUGIN\n * --------------------------------------------- */\n\nexport type HTMLPluginCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.HTML]: infer I;\n tags?: infer U;\n}\n ? {\n use: (components?: HTMLComponents<'permissive', U>) => IntlayerNode<I>;\n }\n : never;\n\nexport const htmlPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_HTML === 'false'\n ? fallbackPlugin\n : {\n id: 'html-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.HTML,\n transform: (node: HTMLContent<string>, props) => {\n const htmlStr = node[NodeTypes.HTML];\n\n const use = (components: Record<string, any> = {}) => {\n const wrappedComponents = new Proxy(components, {\n get(target, prop) {\n if (typeof prop === 'string' && prop in target) {\n const Component = target[prop];\n return (props: any) => {\n const children = Array.isArray(props.children)\n ? props.children.join('')\n : props.children;\n return Component({ ...props, children });\n };\n }\n if (typeof prop === 'string' && /^[a-z][a-z0-9]*$/.test(prop)) {\n return (props: any) => {\n const attrs = Object.entries(props)\n .filter(([key]) => key !== 'children' && key !== 'key')\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(' ');\n const children = Array.isArray(props.children)\n ? props.children.join('')\n : props.children;\n return `<${prop}${attrs ? ` ${attrs}` : ''}>${children}</${prop}>`;\n };\n }\n return undefined;\n },\n });\n\n const result = getHTML(htmlStr, wrappedComponents as any);\n return Array.isArray(result) ? result.join('') : result;\n };\n\n const value = use();\n let children = htmlStr;\n\n if (\n process.env.INTLAYER_EDITOR_ENABLED !== 'false' &&\n editor.enabled\n ) {\n const keyPathJson = JSON.stringify(props.keyPath ?? []);\n const dictKey = String(props.dictionaryKey ?? '');\n children = `<intlayer-content-selector-wrapper key-path=\"${escapeHtmlAttr(keyPathJson)}\" dictionary-key=\"${escapeHtmlAttr(dictKey)}\">${escapeHtmlText(value)}</intlayer-content-selector-wrapper>`;\n }\n\n return renderIntlayerNode({\n ...props,\n value,\n children,\n additionalProps: {\n use: (components?: any) => use(components),\n },\n });\n },\n };\n\n/** ---------------------------------------------\n * PLUGINS RESULT\n * --------------------------------------------- */\n\nexport interface IInterpreterPluginVanilla<T, S, L extends LocalesValues> {\n vanillaIntlayerNode: IntlayerNodeCond<T>;\n vanillaInsertion: InsertionCond<T, S, L>;\n vanillaMarkdown: MarkdownCond<T>;\n vanillaHtml: HTMLPluginCond<T>;\n}\n\n/**\n * Insert this type as param of `DeepTransformContent` to avoid `intlayer` package pollution.\n *\n * Otherwise the `vanilla-intlayer` plugins will override the types of `intlayer` functions.\n * Use `getIntlayer` from `vanilla-intlayer` (not from `intlayer`) to get properly typed\n * `IntlayerNode` wrappers with `.value` access on string/number content.\n */\nexport type IInterpreterPluginState = Omit<\n IInterpreterPluginStateCore,\n 'insertion'\n> & {\n vanillaIntlayerNode: true;\n vanillaInsertion: true;\n vanillaMarkdown: true;\n vanillaHtml: true;\n};\n\nexport type DeepTransformContent<\n T,\n L extends LocalesValues = DeclaredLocales,\n> = DeepTransformContentCore<T, IInterpreterPluginState, L>;\n\nconst pluginsCache = new Map<string, Plugins[]>();\n\n/**\n * Get the plugins array for Vanilla content transformation.\n * This function is used by both getIntlayer and getDictionary to ensure consistent plugin configuration.\n */\nexport const getPlugins = (\n locale?: LocalesValues,\n fallback = true\n): Plugins[] => {\n const currentLocale = locale ?? internationalization.defaultLocale;\n const cacheKey = `${currentLocale}_${fallback}`;\n\n if (pluginsCache.has(cacheKey)) {\n return pluginsCache.get(cacheKey)!;\n }\n\n const plugins = [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n pluralPlugin(locale ?? internationalization.defaultLocale),\n conditionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n intlayerNodePlugins,\n insertionPlugin,\n markdownPlugin,\n htmlPlugin,\n ] as Plugins[];\n\n pluginsCache.set(cacheKey, plugins);\n\n return plugins;\n};\n"],"mappings":";;;;;;;;;;AAkDA,MAAM,kBAAkB,QACtB,IAAI,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAEnD,MAAM,kBAAkB,QACtB,IAAI,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAEvE,MAAa,sBAA+B;CAC1C,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAChB,OAAO,SAAS,YAChB,OAAO,SAAS;CAClB,YAAY,OAAO,EAAE,UAAU,SAAS,eAAe,GAAG,WAAW;EACnE,IAAI,QAAQ,IAAI,4BAA4B,WAAWA,8BAAO,SAAS;GACrE,MAAM,SAAS,OAAO,YAAY,EAAE;GACpC,MAAM,cAAc,KAAK,UAAU,WAAW,CAAC,CAAC;GAChD,MAAM,UAAU,OAAO,iBAAiB,EAAE;;;;;;GAO1C,MAAM,UAAU,gDAAgD,eAAe,WAAW,EAAE,oBAAoB,eAAe,OAAO,EAAE,IAAI,eAAe,MAAM,EAAE;GAEnK,OAAOC,8CAAmB;IACxB,GAAG;IACH,OAAO;IACP,UAAU;IACV;IACA;IACA,iBAAiB,EACf,iBAA8B;KAC5B,MAAM,UAAU,SAAS,cACvB,mCACF;KACA,QAAQ,aAAa,YAAY,WAAW;KAC5C,QAAQ,aAAa,kBAAkB,OAAO;KAC9C,QAAQ,cAAc;KACtB,OAAO;IACT,EACF;GACF,CAAC;EACH;EAEA,OAAOA,8CAAmB;GACxB,GAAG;GACH,OAAO;GACP;EACF,CAAC;CACH;AACF;AAgBA,MAAa,kBACX,QAAQ,IA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H;AACF;AAmCN,MAAM,+BAAe,IAAI,IAAuB;;;;;AAMhD,MAAa,cACX,QACA,WAAW,SACG;CAEd,MAAM,WAAW,GADK,UAAUG,4CAAqB,cACnB,GAAG;CAErC,IAAI,aAAa,IAAI,QAAQ,GAC3B,OAAO,aAAa,IAAI,QAAQ;CAGlC,MAAM,UAAU;oDAEZ,UAAUA,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,MAClD;EACAC;+CACa,UAAUD,4CAAqB,aAAa;EACzDE;+CACa,UAAUF,4CAAqB,aAAa;EACzDG;EACAC;EACA;EACA;EACA;EACA;CACF;CAEA,aAAa,IAAI,UAAU,OAAO;CAElC,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderIntlayerNode.cjs","names":[],"sources":["../../src/renderIntlayerNode.ts"],"sourcesContent":["import type { ResolvedEditor } from '@intlayer/types/module_augmentation';\n\nexport type IntlayerNode<T = string> = ResolvedEditor<\n T & {\n raw: T;\n value: T;\n toString: () => string;\n valueOf: () => T;\n toJSON: () => T;\n __update: (next: IntlayerNode<T>) => void;\n },\n {\n raw: T;\n value: T;\n toString: () => string;\n valueOf: () => T;\n toJSON: () => T;\n __update: (next: IntlayerNode<T>) => void;\n }\n> &\n T;\n\nexport const renderIntlayerNode = <\n T, // Broadened to support arrays, numbers, objects, etc.\n>({\n value,\n children,\n additionalProps = {},\n}: {\n value: T;\n children?: any;\n additionalProps?: Record<string, unknown>;\n [key: string]: unknown;\n}): IntlayerNode<T> => {\n let _value = value;\n\n // When children is a string that differs from value, it acts as a display\n // override (e.g. editor HTML wrapper). Otherwise toString/toPrimitive reflect\n // the live _value so that __update propagates.\n const displayOverride =\n typeof children === 'string' && children !== String(value ?? '')\n ? children\n : null;\n\n const node = {\n toString: () => displayOverride ?? String(_value ?? ''),\n valueOf: () => _value,\n [Symbol.toPrimitive]: () => displayOverride ?? _value,\n toJSON: () => _value,\n\n get raw() {\n return _value;\n },\n set raw(value: T) {\n _value = value;\n },\n\n get value() {\n return _value;\n },\n\n __update(next: any) {\n _value = next?.raw ?? next?.value ?? next;\n },\n\n ...additionalProps,\n };\n\n // Delegate native methods from the underlying value (any type) to node.\n if (_value !== null && _value !== undefined) {\n const valObj = Object(_value); // Safely boxes primitives (e.g., 50 -> Number object)\n const proto = Object.getPrototypeOf(valObj);\n for (const prop of Object.getOwnPropertyNames(proto)) {\n if (prop === 'constructor' || prop in node) continue;\n const valProp = valObj[prop]; // read from instance so length/index values are correct\n if (typeof valProp === 'function') {\n Object.defineProperty(node, prop, {\n value: valProp.bind(_value),\n writable: true,\n configurable: true,\n });\n }\n }\n }\n\n return node as unknown as IntlayerNode<T>;\n};\n"],"mappings":";;;AAsBA,MAAa,sBAEX,EACA,OACA,UACA,kBAAkB,
|
|
1
|
+
{"version":3,"file":"renderIntlayerNode.cjs","names":[],"sources":["../../src/renderIntlayerNode.ts"],"sourcesContent":["import type { ResolvedEditor } from '@intlayer/types/module_augmentation';\n\nexport type IntlayerNode<T = string> = ResolvedEditor<\n T & {\n raw: T;\n value: T;\n toString: () => string;\n valueOf: () => T;\n toJSON: () => T;\n __update: (next: IntlayerNode<T>) => void;\n },\n {\n raw: T;\n value: T;\n toString: () => string;\n valueOf: () => T;\n toJSON: () => T;\n __update: (next: IntlayerNode<T>) => void;\n }\n> &\n T;\n\nexport const renderIntlayerNode = <\n T, // Broadened to support arrays, numbers, objects, etc.\n>({\n value,\n children,\n additionalProps = {},\n}: {\n value: T;\n children?: any;\n additionalProps?: Record<string, unknown>;\n [key: string]: unknown;\n}): IntlayerNode<T> => {\n let _value = value;\n\n // When children is a string that differs from value, it acts as a display\n // override (e.g. editor HTML wrapper). Otherwise toString/toPrimitive reflect\n // the live _value so that __update propagates.\n const displayOverride =\n typeof children === 'string' && children !== String(value ?? '')\n ? children\n : null;\n\n const node = {\n toString: () => displayOverride ?? String(_value ?? ''),\n valueOf: () => _value,\n [Symbol.toPrimitive]: () => displayOverride ?? _value,\n toJSON: () => _value,\n\n get raw() {\n return _value;\n },\n set raw(value: T) {\n _value = value;\n },\n\n get value() {\n return _value;\n },\n\n __update(next: any) {\n _value = next?.raw ?? next?.value ?? next;\n },\n\n ...additionalProps,\n };\n\n // Delegate native methods from the underlying value (any type) to node.\n if (_value !== null && _value !== undefined) {\n const valObj = Object(_value); // Safely boxes primitives (e.g., 50 -> Number object)\n const proto = Object.getPrototypeOf(valObj);\n for (const prop of Object.getOwnPropertyNames(proto)) {\n if (prop === 'constructor' || prop in node) continue;\n const valProp = valObj[prop]; // read from instance so length/index values are correct\n if (typeof valProp === 'function') {\n Object.defineProperty(node, prop, {\n value: valProp.bind(_value),\n writable: true,\n configurable: true,\n });\n }\n }\n }\n\n return node as unknown as IntlayerNode<T>;\n};\n"],"mappings":";;;AAsBA,MAAa,sBAEX,EACA,OACA,UACA,kBAAkB,CAAC,QAME;CACrB,IAAI,SAAS;CAKb,MAAM,kBACJ,OAAO,aAAa,YAAY,aAAa,OAAO,SAAS,EAAE,IAC3D,WACA;CAEN,MAAM,OAAO;EACX,gBAAgB,mBAAmB,OAAO,UAAU,EAAE;EACtD,eAAe;GACd,OAAO,oBAAoB,mBAAmB;EAC/C,cAAc;EAEd,IAAI,MAAM;GACR,OAAO;EACT;EACA,IAAI,IAAI,OAAU;GAChB,SAAS;EACX;EAEA,IAAI,QAAQ;GACV,OAAO;EACT;EAEA,SAAS,MAAW;GAClB,SAAS,MAAM,OAAO,MAAM,SAAS;EACvC;EAEA,GAAG;CACL;CAGA,IAAI,WAAW,QAAQ,WAAW,QAAW;EAC3C,MAAM,SAAS,OAAO,MAAM;EAC5B,MAAM,QAAQ,OAAO,eAAe,MAAM;EAC1C,KAAK,MAAM,QAAQ,OAAO,oBAAoB,KAAK,GAAG;GACpD,IAAI,SAAS,iBAAiB,QAAQ,MAAM;GAC5C,MAAM,UAAU,OAAO;GACvB,IAAI,OAAO,YAAY,YACrB,OAAO,eAAe,MAAM,MAAM;IAChC,OAAO,QAAQ,KAAK,MAAM;IAC1B,UAAU;IACV,cAAc;GAChB,CAAC;EAEL;CACF;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"installIntlayer.mjs","names":[],"sources":["../../../src/client/installIntlayer.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { setIntlayerIdentifier } from '@intlayer/config/client';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useEditor } from '../editor/useEditor';\n\ntype LocaleListener = (locale: LocalesValues) => void;\n\nexport class IntlayerClient {\n private _locale: LocalesValues;\n private _listeners: Set<LocaleListener> = new Set();\n isCookieEnabled: boolean;\n\n constructor(locale?: LocalesValues, isCookieEnabled = true) {\n const { defaultLocale } = internationalization ?? {};\n\n setIntlayerIdentifier();\n\n this._locale =\n (locale as LocalesValues) ?? (defaultLocale as LocalesValues);\n this.isCookieEnabled = isCookieEnabled;\n }\n\n get locale(): LocalesValues {\n return this._locale;\n }\n\n setLocale(newLocale: LocalesValues): void {\n this._locale = newLocale;\n for (const listener of this._listeners) {\n listener(newLocale);\n }\n }\n\n subscribe(listener: LocaleListener): () => void {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Fire all listeners with the current locale without changing it.\n * Used to trigger re-renders after async data loads.\n */\n notify(): void {\n for (const listener of this._listeners) {\n listener(this._locale);\n }\n }\n}\n\n/**\n * Singleton instance\n */\nlet instance: IntlayerClient | null = null;\n\n/**\n * Create and return a single IntlayerClient instance.\n */\nexport const createIntlayerClient = (\n locale?: LocalesValues,\n isCookieEnabled = true\n): IntlayerClient => {\n if (instance) return instance;\n\n instance = new IntlayerClient(locale, isCookieEnabled);\n return instance;\n};\n\n/**\n * Get the current IntlayerClient instance, creating one with defaults if needed.\n */\nexport const getIntlayerClient = (): IntlayerClient => {\n if (!instance) {\n instance = new IntlayerClient();\n }\n return instance;\n};\n\n/**\n * Install Intlayer into your vanilla JS application.\n *\n * Call this once at application startup, before any Intlayer APIs are used.\n *\n * When called with a `config` argument, `window.INTLAYER_CONFIG` is set so\n * that `@intlayer/config/built` resolves the correct values in the browser\n * without requiring module aliasing in the bundler configuration.\n *\n * @param locale - Initial locale (defaults to config defaultLocale).\n * @param isCookieEnabled - Whether to persist locale in cookies/localStorage.\n * @param config - Optional Intlayer configuration. When provided, sets\n * `window.INTLAYER_CONFIG` with the browser-safe subset of the config so\n * the application works without a Vite/webpack plugin alias.\n * @returns The IntlayerClient singleton.\n *\n * @example\n * ```ts\n * import { installIntlayer } from 'vanilla-intlayer';\n *\n * // With explicit config (no build plugin alias needed):\n * installIntlayer('en', true, {\n * internationalization: { locales: ['en', 'fr'], defaultLocale: 'en' },\n * });\n *\n * // With build plugin (alias handles config automatically):\n * installIntlayer('en');\n * ```\n */\nexport const installIntlayer = ({\n locale,\n isCookieEnabled,\n}: {\n locale?: LocalesValues;\n isCookieEnabled?: boolean;\n} = {}): IntlayerClient => {\n const client = createIntlayerClient(locale, isCookieEnabled);\n\n useEditor();\n\n return client;\n};\n"],"mappings":";;;;;AAOA,IAAa,iBAAb,MAA4B;CAC1B,AAAQ;CACR,AAAQ,6BAAkC,IAAI,
|
|
1
|
+
{"version":3,"file":"installIntlayer.mjs","names":[],"sources":["../../../src/client/installIntlayer.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { setIntlayerIdentifier } from '@intlayer/config/client';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { useEditor } from '../editor/useEditor';\n\ntype LocaleListener = (locale: LocalesValues) => void;\n\nexport class IntlayerClient {\n private _locale: LocalesValues;\n private _listeners: Set<LocaleListener> = new Set();\n isCookieEnabled: boolean;\n\n constructor(locale?: LocalesValues, isCookieEnabled = true) {\n const { defaultLocale } = internationalization ?? {};\n\n setIntlayerIdentifier();\n\n this._locale =\n (locale as LocalesValues) ?? (defaultLocale as LocalesValues);\n this.isCookieEnabled = isCookieEnabled;\n }\n\n get locale(): LocalesValues {\n return this._locale;\n }\n\n setLocale(newLocale: LocalesValues): void {\n this._locale = newLocale;\n for (const listener of this._listeners) {\n listener(newLocale);\n }\n }\n\n subscribe(listener: LocaleListener): () => void {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Fire all listeners with the current locale without changing it.\n * Used to trigger re-renders after async data loads.\n */\n notify(): void {\n for (const listener of this._listeners) {\n listener(this._locale);\n }\n }\n}\n\n/**\n * Singleton instance\n */\nlet instance: IntlayerClient | null = null;\n\n/**\n * Create and return a single IntlayerClient instance.\n */\nexport const createIntlayerClient = (\n locale?: LocalesValues,\n isCookieEnabled = true\n): IntlayerClient => {\n if (instance) return instance;\n\n instance = new IntlayerClient(locale, isCookieEnabled);\n return instance;\n};\n\n/**\n * Get the current IntlayerClient instance, creating one with defaults if needed.\n */\nexport const getIntlayerClient = (): IntlayerClient => {\n if (!instance) {\n instance = new IntlayerClient();\n }\n return instance;\n};\n\n/**\n * Install Intlayer into your vanilla JS application.\n *\n * Call this once at application startup, before any Intlayer APIs are used.\n *\n * When called with a `config` argument, `window.INTLAYER_CONFIG` is set so\n * that `@intlayer/config/built` resolves the correct values in the browser\n * without requiring module aliasing in the bundler configuration.\n *\n * @param locale - Initial locale (defaults to config defaultLocale).\n * @param isCookieEnabled - Whether to persist locale in cookies/localStorage.\n * @param config - Optional Intlayer configuration. When provided, sets\n * `window.INTLAYER_CONFIG` with the browser-safe subset of the config so\n * the application works without a Vite/webpack plugin alias.\n * @returns The IntlayerClient singleton.\n *\n * @example\n * ```ts\n * import { installIntlayer } from 'vanilla-intlayer';\n *\n * // With explicit config (no build plugin alias needed):\n * installIntlayer('en', true, {\n * internationalization: { locales: ['en', 'fr'], defaultLocale: 'en' },\n * });\n *\n * // With build plugin (alias handles config automatically):\n * installIntlayer('en');\n * ```\n */\nexport const installIntlayer = ({\n locale,\n isCookieEnabled,\n}: {\n locale?: LocalesValues;\n isCookieEnabled?: boolean;\n} = {}): IntlayerClient => {\n const client = createIntlayerClient(locale, isCookieEnabled);\n\n useEditor();\n\n return client;\n};\n"],"mappings":";;;;;AAOA,IAAa,iBAAb,MAA4B;CAC1B,AAAQ;CACR,AAAQ,6BAAkC,IAAI,IAAI;CAClD;CAEA,YAAY,QAAwB,kBAAkB,MAAM;EAC1D,MAAM,EAAE,kBAAkB,wBAAwB,CAAC;EAEnD,sBAAsB;EAEtB,KAAK,UACF,UAA6B;EAChC,KAAK,kBAAkB;CACzB;CAEA,IAAI,SAAwB;EAC1B,OAAO,KAAK;CACd;CAEA,UAAU,WAAgC;EACxC,KAAK,UAAU;EACf,KAAK,MAAM,YAAY,KAAK,YAC1B,SAAS,SAAS;CAEtB;CAEA,UAAU,UAAsC;EAC9C,KAAK,WAAW,IAAI,QAAQ;EAC5B,aAAa;GACX,KAAK,WAAW,OAAO,QAAQ;EACjC;CACF;;;;;CAMA,SAAe;EACb,KAAK,MAAM,YAAY,KAAK,YAC1B,SAAS,KAAK,OAAO;CAEzB;AACF;;;;AAKA,IAAI,WAAkC;;;;AAKtC,MAAa,wBACX,QACA,kBAAkB,SACC;CACnB,IAAI,UAAU,OAAO;CAErB,WAAW,IAAI,eAAe,QAAQ,eAAe;CACrD,OAAO;AACT;;;;AAKA,MAAa,0BAA0C;CACrD,IAAI,CAAC,UACH,WAAW,IAAI,eAAe;CAEhC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,mBAAmB,EAC9B,QACA,oBAIE,CAAC,MAAsB;CACzB,MAAM,SAAS,qBAAqB,QAAQ,eAAe;CAE3D,UAAU;CAEV,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionary.mjs","names":[],"sources":["../../../src/client/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getDictionary } from '../getDictionary';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\n\nexport type WithOnChange<T> = T & {\n /**\n * Subscribe to locale changes. The callback receives the fresh content\n * whenever the active locale changes. Returns the content object itself\n * for convenient one-liner patterns:\n *\n * ```ts\n * const content = useDictionary(myDict).onChange((c) => {\n * document.querySelector('p')!.textContent = String(c.greeting);\n * });\n * ```\n */\n onChange: (callback: (content: any) => void) => WithOnChange<T>;\n};\n\n/**\n * Get the content for a raw dictionary (or qualified dictionary group) and\n * optionally subscribe to locale changes via the chainable `.onChange()`\n * method — mirroring the API of `react-intlayer`.\n *\n * The second argument is either a locale or a selector object (`{ item }`,\n * `{ variant }`, optionally combined with `locale`).\n *\n * @param dictionary - The raw dictionary (or qualified group) object.\n * @param localeOrSelector - Optional locale or selector.\n * @returns The current content with an `.onChange()` method.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): WithOnChange<\n DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n ExtractSelectorLocale<A>\n >\n> => {\n const client = getIntlayerClient();\n\n const isSelector =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n typeof localeOrSelector === 'object' &&\n localeOrSelector !== null;\n const explicitLocale = isSelector\n ? (localeOrSelector as DictionarySelector).locale\n : (localeOrSelector as LocalesValues | undefined);\n\n const read = (locale: LocalesValues | undefined) =>\n isSelector\n ? getDictionary(dictionary, {\n ...(localeOrSelector as DictionarySelector),\n locale,\n } as A)\n : getDictionary(dictionary, locale as A);\n\n const content = read(explicitLocale ?? client.locale) as WithOnChange<any>;\n\n // A selector can resolve to null/array; only objects carry `.onChange`.\n if (content != null && typeof content === 'object') {\n content.onChange = (callback) => {\n client.subscribe((newLocale) => {\n callback(read(explicitLocale ?? newLocale));\n });\n return content;\n };\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,MAAa,iBAMX,YACA,qBAMG;CACH,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useDictionary.mjs","names":[],"sources":["../../../src/client/useDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionarySelector,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getDictionary } from '../getDictionary';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\n\nexport type WithOnChange<T> = T & {\n /**\n * Subscribe to locale changes. The callback receives the fresh content\n * whenever the active locale changes. Returns the content object itself\n * for convenient one-liner patterns:\n *\n * ```ts\n * const content = useDictionary(myDict).onChange((c) => {\n * document.querySelector('p')!.textContent = String(c.greeting);\n * });\n * ```\n */\n onChange: (callback: (content: any) => void) => WithOnChange<T>;\n};\n\n/**\n * Get the content for a raw dictionary (or qualified dictionary group) and\n * optionally subscribe to locale changes via the chainable `.onChange()`\n * method — mirroring the API of `react-intlayer`.\n *\n * The second argument is either a locale or a selector object (`{ item }`,\n * `{ variant }`, optionally combined with `locale`).\n *\n * @param dictionary - The raw dictionary (or qualified group) object.\n * @param localeOrSelector - Optional locale or selector.\n * @returns The current content with an `.onChange()` method.\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): WithOnChange<\n DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n ExtractSelectorLocale<A>\n >\n> => {\n const client = getIntlayerClient();\n\n const isSelector =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n typeof localeOrSelector === 'object' &&\n localeOrSelector !== null;\n const explicitLocale = isSelector\n ? (localeOrSelector as DictionarySelector).locale\n : (localeOrSelector as LocalesValues | undefined);\n\n const read = (locale: LocalesValues | undefined) =>\n isSelector\n ? getDictionary(dictionary, {\n ...(localeOrSelector as DictionarySelector),\n locale,\n } as A)\n : getDictionary(dictionary, locale as A);\n\n const content = read(explicitLocale ?? client.locale) as WithOnChange<any>;\n\n // A selector can resolve to null/array; only objects carry `.onChange`.\n if (content != null && typeof content === 'object') {\n content.onChange = (callback) => {\n client.subscribe((newLocale) => {\n callback(read(explicitLocale ?? newLocale));\n });\n return content;\n };\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,MAAa,iBAMX,YACA,qBAMG;CACH,MAAM,SAAS,kBAAkB;CAEjC,MAAM,aACJ,QAAQ,IAAI,iCAAiC,WAC7C,OAAO,qBAAqB,YAC5B,qBAAqB;CACvB,MAAM,iBAAiB,aAClB,iBAAwC,SACxC;CAEL,MAAM,QAAQ,WACZ,aACI,cAAc,YAAY;EACxB,GAAI;EACJ;CACF,CAAM,IACN,cAAc,YAAY,MAAW;CAE3C,MAAM,UAAU,KAAK,kBAAkB,OAAO,MAAM;CAGpD,IAAI,WAAW,QAAQ,OAAO,YAAY,UACxC,QAAQ,YAAY,aAAa;EAC/B,OAAO,WAAW,cAAc;GAC9B,SAAS,KAAK,kBAAkB,SAAS,CAAC;EAC5C,CAAC;EACD,OAAO;CACT;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionaryDynamic.mjs","names":[],"sources":["../../../src/client/useDictionaryDynamic.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport {\n getDictionarySelectorCacheKey,\n isQualifiedDynamicLoaderMap,\n parseDictionarySelector,\n type QualifiedDynamicLoaderMap,\n resolveQualifiedDynamicContentAsync,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { getDictionary } from '../getDictionary';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\nimport type { WithOnChange } from './useDictionary';\n\n/** Simple in-memory cache shared across all calls in the same page. */\nconst cache = new Map<string, Dictionary>();\n\n/** Tracks in-flight loads to avoid duplicate fetches. */\nconst inflight = new Map<string, Promise<void>>();\n\n/** Resolved-content cache for qualified (collection/variant/meta) keys. */\nconst qualifiedCache = new Map<string, unknown>();\nconst qualifiedInflight = new Map<string, Promise<void>>();\n\nconst loadDictionary = <T extends Dictionary>(\n cacheKey: string,\n loader: () => Promise<T>\n): Promise<void> => {\n if (cache.has(cacheKey)) return Promise.resolve();\n if (inflight.has(cacheKey)) return inflight.get(cacheKey)!;\n\n const promise = loader().then((dictionary) => {\n cache.set(cacheKey, dictionary);\n inflight.delete(cacheKey);\n });\n\n inflight.set(cacheKey, promise);\n return promise;\n};\n\n/** Placeholder proxy — safe for any property access while loading. */\nconst recursiveProxy: any = new Proxy(() => {}, {\n get: (_t, prop) => {\n if (prop === Symbol.toPrimitive) return () => '';\n if (prop === 'toString') return () => '';\n if (prop === 'valueOf') return () => '';\n if (prop === 'then') return undefined; // not a Promise\n if (prop === 'onChange') return (_cb: any) => recursiveProxy;\n return recursiveProxy;\n },\n apply: () => recursiveProxy,\n});\n\n/**\n * Dynamically load and transform a dictionary (plain or qualified).\n *\n * For a qualified loader map (collection / variant, possibly\n * combined), only the chunk(s) the selector targets are loaded. For a plain\n * loader map, the locale chunk is loaded. The first call returns a placeholder\n * and triggers a background load; the client then notifies subscribers so the\n * render runs again with real content.\n *\n * @param dictionaryLoaders - Locale-keyed loader map, or a qualified loader map.\n * @param key - Dictionary key (used for cache namespacing).\n * @param localeOrSelector - Optional locale or selector.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const K extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<K> = LocalesValues,\n>(\n dictionaryLoaders:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: K,\n localeOrSelector?: A\n): WithOnChange<DeepTransformContent<T['content']>> => {\n const client = getIntlayerClient();\n const defaultLocale = internationalization.defaultLocale;\n\n // --- Qualified loader map (collection / variant) ---\n if (\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n isQualifiedDynamicLoaderMap(dictionaryLoaders)\n ) {\n const loaderMap = dictionaryLoaders;\n const { locale: selectorLocale, selector } =\n parseDictionarySelector<LocalesValues>(localeOrSelector);\n const selectorId = getDictionarySelectorCacheKey(selector);\n\n const buildKey = (locale: string) =>\n `${String(key)}.${locale}.${selectorId}`;\n const resolveContent = (locale: LocalesValues) =>\n resolveQualifiedDynamicContentAsync({\n loaderMap,\n key: String(key),\n locale,\n selector,\n transform: (dictionary) => getDictionary(dictionary, locale),\n });\n\n const currentLocale = (selectorLocale ??\n client.locale ??\n defaultLocale) as LocalesValues;\n const cacheKey = buildKey(currentLocale);\n\n const attachOnChange = (content: any) => {\n if (content != null && typeof content === 'object') {\n content.onChange = (callback: (c: any) => void) => {\n client.subscribe((newLocale) => {\n const locale = (selectorLocale ?? newLocale) as LocalesValues;\n const newKey = buildKey(locale);\n\n if (qualifiedCache.has(newKey)) {\n callback(qualifiedCache.get(newKey));\n return;\n }\n\n resolveContent(locale).then((resolved) => {\n qualifiedCache.set(newKey, resolved);\n callback(resolved);\n });\n });\n return content;\n };\n }\n return content;\n };\n\n if (qualifiedCache.has(cacheKey)) {\n return attachOnChange(qualifiedCache.get(cacheKey)) as any;\n }\n\n if (!qualifiedInflight.has(cacheKey)) {\n const promise = resolveContent(currentLocale).then((resolved) => {\n qualifiedCache.set(cacheKey, resolved);\n qualifiedInflight.delete(cacheKey);\n client.notify();\n });\n qualifiedInflight.set(cacheKey, promise);\n }\n\n return recursiveProxy;\n }\n\n // --- Plain locale-keyed loader map ---\n const locale =\n typeof localeOrSelector === 'string'\n ? (localeOrSelector as LocalesValues)\n : undefined;\n const currentLocale = (locale ?? client.locale ?? defaultLocale) as A;\n\n const cacheKey = `${String(key)}.${currentLocale}`;\n const loader = (dictionaryLoaders as Record<string, () => Promise<T>>)[\n currentLocale as string\n ];\n\n // --- Cache hit: return real content synchronously ---\n const cached = cache.get(cacheKey);\n if (cached) {\n const content = getDictionary(cached, currentLocale) as WithOnChange<\n DeepTransformContent<T['content']>\n >;\n\n content.onChange = (callback) => {\n // Re-fire whenever content reloads (locale change → new cache entry).\n client.subscribe((newLocale) => {\n const newKey = `${String(key)}.${newLocale}`;\n const newLoader = (\n dictionaryLoaders as Record<string, () => Promise<T>>\n )[newLocale];\n\n if (!newLoader) return;\n\n loadDictionary(newKey, newLoader).then(() => {\n const dict = cache.get(newKey);\n if (dict) {\n callback(getDictionary(dict, newLocale as A) as any);\n }\n });\n });\n\n return content;\n };\n\n return content;\n }\n\n // --- Cache miss: kick off background load, then notify to re-render ---\n if (loader) {\n loadDictionary(cacheKey, loader).then(() => {\n client.notify();\n });\n }\n\n return recursiveProxy;\n};\n"],"mappings":";;;;;;;AAqBA,MAAM,wBAAQ,IAAI,
|
|
1
|
+
{"version":3,"file":"useDictionaryDynamic.mjs","names":[],"sources":["../../../src/client/useDictionaryDynamic.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport {\n getDictionarySelectorCacheKey,\n isQualifiedDynamicLoaderMap,\n parseDictionarySelector,\n type QualifiedDynamicLoaderMap,\n resolveQualifiedDynamicContentAsync,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { getDictionary } from '../getDictionary';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\nimport type { WithOnChange } from './useDictionary';\n\n/** Simple in-memory cache shared across all calls in the same page. */\nconst cache = new Map<string, Dictionary>();\n\n/** Tracks in-flight loads to avoid duplicate fetches. */\nconst inflight = new Map<string, Promise<void>>();\n\n/** Resolved-content cache for qualified (collection/variant/meta) keys. */\nconst qualifiedCache = new Map<string, unknown>();\nconst qualifiedInflight = new Map<string, Promise<void>>();\n\nconst loadDictionary = <T extends Dictionary>(\n cacheKey: string,\n loader: () => Promise<T>\n): Promise<void> => {\n if (cache.has(cacheKey)) return Promise.resolve();\n if (inflight.has(cacheKey)) return inflight.get(cacheKey)!;\n\n const promise = loader().then((dictionary) => {\n cache.set(cacheKey, dictionary);\n inflight.delete(cacheKey);\n });\n\n inflight.set(cacheKey, promise);\n return promise;\n};\n\n/** Placeholder proxy — safe for any property access while loading. */\nconst recursiveProxy: any = new Proxy(() => {}, {\n get: (_t, prop) => {\n if (prop === Symbol.toPrimitive) return () => '';\n if (prop === 'toString') return () => '';\n if (prop === 'valueOf') return () => '';\n if (prop === 'then') return undefined; // not a Promise\n if (prop === 'onChange') return (_cb: any) => recursiveProxy;\n return recursiveProxy;\n },\n apply: () => recursiveProxy,\n});\n\n/**\n * Dynamically load and transform a dictionary (plain or qualified).\n *\n * For a qualified loader map (collection / variant, possibly\n * combined), only the chunk(s) the selector targets are loaded. For a plain\n * loader map, the locale chunk is loaded. The first call returns a placeholder\n * and triggers a background load; the client then notifies subscribers so the\n * render runs again with real content.\n *\n * @param dictionaryLoaders - Locale-keyed loader map, or a qualified loader map.\n * @param key - Dictionary key (used for cache namespacing).\n * @param localeOrSelector - Optional locale or selector.\n */\nexport const useDictionaryDynamic = <\n const T extends Dictionary,\n const K extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<K> = LocalesValues,\n>(\n dictionaryLoaders:\n | StrictModeLocaleMap<() => Promise<T>>\n | QualifiedDynamicLoaderMap,\n key: K,\n localeOrSelector?: A\n): WithOnChange<DeepTransformContent<T['content']>> => {\n const client = getIntlayerClient();\n const defaultLocale = internationalization.defaultLocale;\n\n // --- Qualified loader map (collection / variant) ---\n if (\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n isQualifiedDynamicLoaderMap(dictionaryLoaders)\n ) {\n const loaderMap = dictionaryLoaders;\n const { locale: selectorLocale, selector } =\n parseDictionarySelector<LocalesValues>(localeOrSelector);\n const selectorId = getDictionarySelectorCacheKey(selector);\n\n const buildKey = (locale: string) =>\n `${String(key)}.${locale}.${selectorId}`;\n const resolveContent = (locale: LocalesValues) =>\n resolveQualifiedDynamicContentAsync({\n loaderMap,\n key: String(key),\n locale,\n selector,\n transform: (dictionary) => getDictionary(dictionary, locale),\n });\n\n const currentLocale = (selectorLocale ??\n client.locale ??\n defaultLocale) as LocalesValues;\n const cacheKey = buildKey(currentLocale);\n\n const attachOnChange = (content: any) => {\n if (content != null && typeof content === 'object') {\n content.onChange = (callback: (c: any) => void) => {\n client.subscribe((newLocale) => {\n const locale = (selectorLocale ?? newLocale) as LocalesValues;\n const newKey = buildKey(locale);\n\n if (qualifiedCache.has(newKey)) {\n callback(qualifiedCache.get(newKey));\n return;\n }\n\n resolveContent(locale).then((resolved) => {\n qualifiedCache.set(newKey, resolved);\n callback(resolved);\n });\n });\n return content;\n };\n }\n return content;\n };\n\n if (qualifiedCache.has(cacheKey)) {\n return attachOnChange(qualifiedCache.get(cacheKey)) as any;\n }\n\n if (!qualifiedInflight.has(cacheKey)) {\n const promise = resolveContent(currentLocale).then((resolved) => {\n qualifiedCache.set(cacheKey, resolved);\n qualifiedInflight.delete(cacheKey);\n client.notify();\n });\n qualifiedInflight.set(cacheKey, promise);\n }\n\n return recursiveProxy;\n }\n\n // --- Plain locale-keyed loader map ---\n const locale =\n typeof localeOrSelector === 'string'\n ? (localeOrSelector as LocalesValues)\n : undefined;\n const currentLocale = (locale ?? client.locale ?? defaultLocale) as A;\n\n const cacheKey = `${String(key)}.${currentLocale}`;\n const loader = (dictionaryLoaders as Record<string, () => Promise<T>>)[\n currentLocale as string\n ];\n\n // --- Cache hit: return real content synchronously ---\n const cached = cache.get(cacheKey);\n if (cached) {\n const content = getDictionary(cached, currentLocale) as WithOnChange<\n DeepTransformContent<T['content']>\n >;\n\n content.onChange = (callback) => {\n // Re-fire whenever content reloads (locale change → new cache entry).\n client.subscribe((newLocale) => {\n const newKey = `${String(key)}.${newLocale}`;\n const newLoader = (\n dictionaryLoaders as Record<string, () => Promise<T>>\n )[newLocale];\n\n if (!newLoader) return;\n\n loadDictionary(newKey, newLoader).then(() => {\n const dict = cache.get(newKey);\n if (dict) {\n callback(getDictionary(dict, newLocale as A) as any);\n }\n });\n });\n\n return content;\n };\n\n return content;\n }\n\n // --- Cache miss: kick off background load, then notify to re-render ---\n if (loader) {\n loadDictionary(cacheKey, loader).then(() => {\n client.notify();\n });\n }\n\n return recursiveProxy;\n};\n"],"mappings":";;;;;;;AAqBA,MAAM,wBAAQ,IAAI,IAAwB;;AAG1C,MAAM,2BAAW,IAAI,IAA2B;;AAGhD,MAAM,iCAAiB,IAAI,IAAqB;AAChD,MAAM,oCAAoB,IAAI,IAA2B;AAEzD,MAAM,kBACJ,UACA,WACkB;CAClB,IAAI,MAAM,IAAI,QAAQ,GAAG,OAAO,QAAQ,QAAQ;CAChD,IAAI,SAAS,IAAI,QAAQ,GAAG,OAAO,SAAS,IAAI,QAAQ;CAExD,MAAM,UAAU,OAAO,CAAC,CAAC,MAAM,eAAe;EAC5C,MAAM,IAAI,UAAU,UAAU;EAC9B,SAAS,OAAO,QAAQ;CAC1B,CAAC;CAED,SAAS,IAAI,UAAU,OAAO;CAC9B,OAAO;AACT;;AAGA,MAAM,iBAAsB,IAAI,YAAY,CAAC,GAAG;CAC9C,MAAM,IAAI,SAAS;EACjB,IAAI,SAAS,OAAO,aAAa,aAAa;EAC9C,IAAI,SAAS,YAAY,aAAa;EACtC,IAAI,SAAS,WAAW,aAAa;EACrC,IAAI,SAAS,QAAQ,OAAO;EAC5B,IAAI,SAAS,YAAY,QAAQ,QAAa;EAC9C,OAAO;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AChB,CAAC;GACD,kBAAkB,IAAI,UAAU,OAAO;EACzC;EAEA,OAAO;CACT;CAOA,MAAM,iBAHJ,OAAO,qBAAqB,WACvB,mBACD,WAC2B,OAAO,UAAU;CAElD,MAAM,WAAW,GAAG,OAAO,GAAG,EAAE,GAAG;CACnC,MAAM,SAAU,kBACd;CAIF,MAAM,SAAS,MAAM,IAAI,QAAQ;CACjC,IAAI,QAAQ;EACV,MAAM,UAAU,cAAc,QAAQ,aAAa;EAInD,QAAQ,YAAY,aAAa;GAE/B,OAAO,WAAW,cAAc;IAC9B,MAAM,SAAS,GAAG,OAAO,GAAG,EAAE,GAAG;IACjC,MAAM,YACJ,kBACA;IAEF,IAAI,CAAC,WAAW;IAEhB,eAAe,QAAQ,SAAS,CAAC,CAAC,WAAW;KAC3C,MAAM,OAAO,MAAM,IAAI,MAAM;KAC7B,IAAI,MACF,SAAS,cAAc,MAAM,SAAc,CAAQ;IAEvD,CAAC;GACH,CAAC;GAED,OAAO;EACT;EAEA,OAAO;CACT;CAGA,IAAI,QACF,eAAe,UAAU,MAAM,CAAC,CAAC,WAAW;EAC1C,OAAO,OAAO;CAChB,CAAC;CAGH,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIntlayer.mjs","names":[],"sources":["../../../src/client/useIntlayer.ts"],"sourcesContent":["import type { DictionarySelector } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n DictionarySelectorForKey,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getIntlayer } from '../getIntlayer';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\nimport type { WithOnChange } from './useDictionary';\n\n/**\n * Get the translated content for the given key and optionally subscribe to\n * locale changes via the chainable `.onChange()` method — mirroring the API\n * of `react-intlayer`'s `useIntlayer`.\n *\n * The second argument is either a locale or a selector object:\n * - `{ item: 2 }` — collection item (omit `item` to get every item as array)\n * - `{ variant: 'black-friday' }` — named variant (omit for the `default` one)\n * - `locale` composes with any selector and overrides the current locale\n *\n * The function returns the current content **directly** (same shape as\n * `getIntlayer(key)`), plus the `.onChange()` helper.\n *\n * @param key - Dictionary key registered in your intlayer content files.\n * @param localeOrSelector - Optional locale or selector.\n * @returns The current translated content with an `.onChange()` method.\n *\n * @example\n * ```ts\n * import { installIntlayer, useIntlayer } from 'vanilla-intlayer';\n *\n * installIntlayer();\n *\n * const content = useIntlayer('homepage');\n * const faq2 = useIntlayer('faq', { item: 2 });\n * ```\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): WithOnChange<\n DeepTransformContent<DictionaryRegistryResult<T, A>, ExtractSelectorLocale<A>>\n> => {\n const client = getIntlayerClient();\n\n const isSelector =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n typeof localeOrSelector === 'object' &&\n localeOrSelector !== null;\n const explicitLocale = isSelector\n ? (localeOrSelector as DictionarySelector).locale\n : (localeOrSelector as LocalesValues | undefined);\n\n const read = (locale: LocalesValues | undefined) =>\n isSelector\n ? getIntlayer(key, {\n ...(localeOrSelector as DictionarySelector),\n locale,\n } as A)\n : getIntlayer(key, locale as A);\n\n const content = read(explicitLocale ?? client.locale) as WithOnChange<any>;\n\n // A selector can resolve to null/array; only objects carry `.onChange`.\n if (content != null && typeof content === 'object') {\n content.onChange = (callback) => {\n client.subscribe((newLocale) => {\n callback(read(explicitLocale ?? newLocale));\n });\n return content;\n };\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,eAIX,KACA,qBAGG;CACH,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useIntlayer.mjs","names":[],"sources":["../../../src/client/useIntlayer.ts"],"sourcesContent":["import type { DictionarySelector } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n DictionarySelectorForKey,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getIntlayer } from '../getIntlayer';\nimport type { DeepTransformContent } from '../plugins';\nimport { getIntlayerClient } from './installIntlayer';\nimport type { WithOnChange } from './useDictionary';\n\n/**\n * Get the translated content for the given key and optionally subscribe to\n * locale changes via the chainable `.onChange()` method — mirroring the API\n * of `react-intlayer`'s `useIntlayer`.\n *\n * The second argument is either a locale or a selector object:\n * - `{ item: 2 }` — collection item (omit `item` to get every item as array)\n * - `{ variant: 'black-friday' }` — named variant (omit for the `default` one)\n * - `locale` composes with any selector and overrides the current locale\n *\n * The function returns the current content **directly** (same shape as\n * `getIntlayer(key)`), plus the `.onChange()` helper.\n *\n * @param key - Dictionary key registered in your intlayer content files.\n * @param localeOrSelector - Optional locale or selector.\n * @returns The current translated content with an `.onChange()` method.\n *\n * @example\n * ```ts\n * import { installIntlayer, useIntlayer } from 'vanilla-intlayer';\n *\n * installIntlayer();\n *\n * const content = useIntlayer('homepage');\n * const faq2 = useIntlayer('faq', { item: 2 });\n * ```\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): WithOnChange<\n DeepTransformContent<DictionaryRegistryResult<T, A>, ExtractSelectorLocale<A>>\n> => {\n const client = getIntlayerClient();\n\n const isSelector =\n process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false' &&\n typeof localeOrSelector === 'object' &&\n localeOrSelector !== null;\n const explicitLocale = isSelector\n ? (localeOrSelector as DictionarySelector).locale\n : (localeOrSelector as LocalesValues | undefined);\n\n const read = (locale: LocalesValues | undefined) =>\n isSelector\n ? getIntlayer(key, {\n ...(localeOrSelector as DictionarySelector),\n locale,\n } as A)\n : getIntlayer(key, locale as A);\n\n const content = read(explicitLocale ?? client.locale) as WithOnChange<any>;\n\n // A selector can resolve to null/array; only objects carry `.onChange`.\n if (content != null && typeof content === 'object') {\n content.onChange = (callback) => {\n client.subscribe((newLocale) => {\n callback(read(explicitLocale ?? newLocale));\n });\n return content;\n };\n }\n\n return content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,eAIX,KACA,qBAGG;CACH,MAAM,SAAS,kBAAkB;CAEjC,MAAM,aACJ,QAAQ,IAAI,iCAAiC,WAC7C,OAAO,qBAAqB,YAC5B,qBAAqB;CACvB,MAAM,iBAAiB,aAClB,iBAAwC,SACxC;CAEL,MAAM,QAAQ,WACZ,aACI,YAAY,KAAK;EACf,GAAI;EACJ;CACF,CAAM,IACN,YAAY,KAAK,MAAW;CAElC,MAAM,UAAU,KAAK,kBAAkB,OAAO,MAAM;CAGpD,IAAI,WAAW,QAAQ,OAAO,YAAY,UACxC,QAAQ,YAAY,aAAa;EAC/B,OAAO,WAAW,cAAc;GAC9B,SAAS,KAAK,kBAAkB,SAAS,CAAC;EAC5C,CAAC;EACD,OAAO;CACT;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocale.mjs","names":[],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getIntlayerClient } from './installIntlayer';\nimport { setLocaleInStorage } from './useLocaleStorage';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n};\n\nexport type UseLocaleResult = {\n locale: DeclaredLocales;\n defaultLocale: DeclaredLocales;\n availableLocales: DeclaredLocales[];\n setLocale: (locale: LocalesValues) => void;\n subscribe: (callback: (locale: LocalesValues) => void) => () => void;\n};\n\n/**\n * Get the current locale state and locale management utilities.\n *\n * Returns a plain object with the current `locale`, `defaultLocale`,\n * `availableLocales`, a `setLocale` function, and a `subscribe` function\n * to react to locale changes.\n *\n * @param props - Optional configuration.\n * @returns Locale state and management utilities.\n *\n * @example\n * ```ts\n * import { installIntlayer, useLocale } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const { locale, availableLocales, setLocale, subscribe } = useLocale();\n *\n * const unsubscribe = subscribe((newLocale) => {\n * console.log('Locale changed to', newLocale);\n * });\n *\n * document.querySelector('#lang-switcher').addEventListener('change', (e) => {\n * setLocale(e.target.value);\n * });\n * ```\n */\nexport const useLocale = (props: UseLocaleProps = {}): UseLocaleResult => {\n const client = getIntlayerClient();\n const { defaultLocale, locales: availableLocales } =\n internationalization ?? {};\n\n const setLocale = (newLocale: LocalesValues): void => {\n if (!(availableLocales ?? []).map(String).includes(newLocale)) {\n console.error(`Locale \"${newLocale}\" is not available.`);\n return;\n }\n\n client.setLocale(newLocale);\n\n setLocaleInStorage(\n newLocale,\n props.isCookieEnabled ?? client.isCookieEnabled ?? true\n );\n\n props.onLocaleChange?.(newLocale as DeclaredLocales);\n };\n\n return {\n locale: client.locale as DeclaredLocales,\n defaultLocale: defaultLocale as DeclaredLocales,\n availableLocales: (availableLocales ?? []) as DeclaredLocales[],\n setLocale,\n subscribe: (callback) => client.subscribe(callback),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,aAAa,QAAwB,
|
|
1
|
+
{"version":3,"file":"useLocale.mjs","names":[],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getIntlayerClient } from './installIntlayer';\nimport { setLocaleInStorage } from './useLocaleStorage';\n\nexport type UseLocaleProps = {\n isCookieEnabled?: boolean;\n onLocaleChange?: (locale: DeclaredLocales) => void;\n};\n\nexport type UseLocaleResult = {\n locale: DeclaredLocales;\n defaultLocale: DeclaredLocales;\n availableLocales: DeclaredLocales[];\n setLocale: (locale: LocalesValues) => void;\n subscribe: (callback: (locale: LocalesValues) => void) => () => void;\n};\n\n/**\n * Get the current locale state and locale management utilities.\n *\n * Returns a plain object with the current `locale`, `defaultLocale`,\n * `availableLocales`, a `setLocale` function, and a `subscribe` function\n * to react to locale changes.\n *\n * @param props - Optional configuration.\n * @returns Locale state and management utilities.\n *\n * @example\n * ```ts\n * import { installIntlayer, useLocale } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const { locale, availableLocales, setLocale, subscribe } = useLocale();\n *\n * const unsubscribe = subscribe((newLocale) => {\n * console.log('Locale changed to', newLocale);\n * });\n *\n * document.querySelector('#lang-switcher').addEventListener('change', (e) => {\n * setLocale(e.target.value);\n * });\n * ```\n */\nexport const useLocale = (props: UseLocaleProps = {}): UseLocaleResult => {\n const client = getIntlayerClient();\n const { defaultLocale, locales: availableLocales } =\n internationalization ?? {};\n\n const setLocale = (newLocale: LocalesValues): void => {\n if (!(availableLocales ?? []).map(String).includes(newLocale)) {\n console.error(`Locale \"${newLocale}\" is not available.`);\n return;\n }\n\n client.setLocale(newLocale);\n\n setLocaleInStorage(\n newLocale,\n props.isCookieEnabled ?? client.isCookieEnabled ?? true\n );\n\n props.onLocaleChange?.(newLocale as DeclaredLocales);\n };\n\n return {\n locale: client.locale as DeclaredLocales,\n defaultLocale: defaultLocale as DeclaredLocales,\n availableLocales: (availableLocales ?? []) as DeclaredLocales[],\n setLocale,\n subscribe: (callback) => client.subscribe(callback),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,aAAa,QAAwB,CAAC,MAAuB;CACxE,MAAM,SAAS,kBAAkB;CACjC,MAAM,EAAE,eAAe,SAAS,qBAC9B,wBAAwB,CAAC;CAE3B,MAAM,aAAa,cAAmC;EACpD,IAAI,EAAE,oBAAoB,CAAC,EAAC,CAAE,IAAI,MAAM,CAAC,CAAC,SAAS,SAAS,GAAG;GAC7D,QAAQ,MAAM,WAAW,UAAU,oBAAoB;GACvD;EACF;EAEA,OAAO,UAAU,SAAS;EAE1B,mBACE,WACA,MAAM,mBAAmB,OAAO,mBAAmB,IACrD;EAEA,MAAM,iBAAiB,SAA4B;CACrD;CAEA,OAAO;EACL,QAAQ,OAAO;EACA;EACf,kBAAmB,oBAAoB,CAAC;EACxC;EACA,YAAY,aAAa,OAAO,UAAU,QAAQ;CACpD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocaleStorage.mjs","names":["setLocaleInStorageCore"],"sources":["../../../src/client/useLocaleStorage.ts"],"sourcesContent":["import {\n getLocaleFromStorageClient,\n LocaleStorageClient,\n localeStorageOptions,\n setLocaleInStorageClient as setLocaleInStorageCore,\n} from '@intlayer/core/utils';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the current locale from storage (cookie or localStorage).\n */\nexport const localeInStorage = getLocaleFromStorageClient(localeStorageOptions);\n\n/**\n * @deprecated Use localeInStorage instead.\n */\nexport const localeCookie = localeInStorage;\n\n/**\n * Persist the locale to storage (cookie and/or localStorage).\n */\nexport const setLocaleInStorage = (\n locale: LocalesValues,\n isCookieEnabled: boolean\n) =>\n setLocaleInStorageCore(locale, {\n ...localeStorageOptions,\n isCookieEnabled,\n });\n\n/**\n * @deprecated Use setLocaleInStorage instead.\n */\nexport const setLocaleCookie = setLocaleInStorage;\n\n/**\n * Returns the current locale from storage and a setter.\n */\nexport const useLocaleStorage = (isCookieEnabled?: boolean) => {\n const storage = LocaleStorageClient({\n ...localeStorageOptions,\n isCookieEnabled,\n });\n\n return {\n localeStorage: storage.getLocale(),\n setLocaleStorage: storage.setLocale,\n };\n};\n\n/**\n * @deprecated Use useLocaleStorage instead.\n */\nexport const useLocaleCookie = useLocaleStorage;\n"],"mappings":";;;;;;AAWA,MAAa,kBAAkB,2BAA2B,
|
|
1
|
+
{"version":3,"file":"useLocaleStorage.mjs","names":["setLocaleInStorageCore"],"sources":["../../../src/client/useLocaleStorage.ts"],"sourcesContent":["import {\n getLocaleFromStorageClient,\n LocaleStorageClient,\n localeStorageOptions,\n setLocaleInStorageClient as setLocaleInStorageCore,\n} from '@intlayer/core/utils';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the current locale from storage (cookie or localStorage).\n */\nexport const localeInStorage = getLocaleFromStorageClient(localeStorageOptions);\n\n/**\n * @deprecated Use localeInStorage instead.\n */\nexport const localeCookie = localeInStorage;\n\n/**\n * Persist the locale to storage (cookie and/or localStorage).\n */\nexport const setLocaleInStorage = (\n locale: LocalesValues,\n isCookieEnabled: boolean\n) =>\n setLocaleInStorageCore(locale, {\n ...localeStorageOptions,\n isCookieEnabled,\n });\n\n/**\n * @deprecated Use setLocaleInStorage instead.\n */\nexport const setLocaleCookie = setLocaleInStorage;\n\n/**\n * Returns the current locale from storage and a setter.\n */\nexport const useLocaleStorage = (isCookieEnabled?: boolean) => {\n const storage = LocaleStorageClient({\n ...localeStorageOptions,\n isCookieEnabled,\n });\n\n return {\n localeStorage: storage.getLocale(),\n setLocaleStorage: storage.setLocale,\n };\n};\n\n/**\n * @deprecated Use useLocaleStorage instead.\n */\nexport const useLocaleCookie = useLocaleStorage;\n"],"mappings":";;;;;;AAWA,MAAa,kBAAkB,2BAA2B,oBAAoB;;;;AAK9E,MAAa,eAAe;;;;AAK5B,MAAa,sBACX,QACA,oBAEAA,yBAAuB,QAAQ;CAC7B,GAAG;CACH;AACF,CAAC;;;;AAKH,MAAa,kBAAkB;;;;AAK/B,MAAa,oBAAoB,oBAA8B;CAC7D,MAAM,UAAU,oBAAoB;EAClC,GAAG;EACH;CACF,CAAC;CAED,OAAO;EACL,eAAe,QAAQ,UAAU;EACjC,kBAAkB,QAAQ;CAC5B;AACF;;;;AAKA,MAAa,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePathname.mjs","names":[],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["import { getPathWithoutLocale } from '@intlayer/core/localization';\n\nexport type UsePathnameResult = {\n /** Current pathname without the locale prefix. */\n pathname: string;\n /**\n * Subscribe to pathname changes triggered by browser navigation.\n *\n * @param callback - Called with the new pathname on every `popstate` event.\n * @returns A cleanup function that removes the event listener.\n */\n subscribe: (callback: (pathname: string) => void) => () => void;\n};\n\n/**\n * Returns the current pathname with the locale segment removed, plus a\n * `subscribe` function to react to browser navigation changes.\n *\n * Falls back to an empty string during server-side rendering.\n *\n * @returns An object with the current pathname and a subscribe function.\n *\n * @example\n * ```ts\n * import { usePathname } from 'vanilla-intlayer';\n *\n * const { pathname, subscribe } = usePathname();\n *\n * const unsubscribe = subscribe((newPathname) => {\n * document.querySelector('.active')?.classList.remove('active');\n * document.querySelector(`[href=\"${newPathname}\"]`)?.classList.add('active');\n * });\n * ```\n */\nexport const usePathname = (): UsePathnameResult => {\n const getPathname = (): string =>\n typeof window !== 'undefined'\n ? getPathWithoutLocale(window.location.pathname)\n : '';\n\n const subscribe = (callback: (pathname: string) => void): (() => void) => {\n const handleLocationChange = (): void => callback(getPathname());\n window.addEventListener('popstate', handleLocationChange);\n return () => window.removeEventListener('popstate', handleLocationChange);\n };\n\n return {\n pathname: getPathname(),\n subscribe,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,oBAAuC;CAClD,MAAM,oBACJ,OAAO,WAAW,cACd,qBAAqB,OAAO,SAAS,
|
|
1
|
+
{"version":3,"file":"usePathname.mjs","names":[],"sources":["../../../src/client/usePathname.ts"],"sourcesContent":["import { getPathWithoutLocale } from '@intlayer/core/localization';\n\nexport type UsePathnameResult = {\n /** Current pathname without the locale prefix. */\n pathname: string;\n /**\n * Subscribe to pathname changes triggered by browser navigation.\n *\n * @param callback - Called with the new pathname on every `popstate` event.\n * @returns A cleanup function that removes the event listener.\n */\n subscribe: (callback: (pathname: string) => void) => () => void;\n};\n\n/**\n * Returns the current pathname with the locale segment removed, plus a\n * `subscribe` function to react to browser navigation changes.\n *\n * Falls back to an empty string during server-side rendering.\n *\n * @returns An object with the current pathname and a subscribe function.\n *\n * @example\n * ```ts\n * import { usePathname } from 'vanilla-intlayer';\n *\n * const { pathname, subscribe } = usePathname();\n *\n * const unsubscribe = subscribe((newPathname) => {\n * document.querySelector('.active')?.classList.remove('active');\n * document.querySelector(`[href=\"${newPathname}\"]`)?.classList.add('active');\n * });\n * ```\n */\nexport const usePathname = (): UsePathnameResult => {\n const getPathname = (): string =>\n typeof window !== 'undefined'\n ? getPathWithoutLocale(window.location.pathname)\n : '';\n\n const subscribe = (callback: (pathname: string) => void): (() => void) => {\n const handleLocationChange = (): void => callback(getPathname());\n window.addEventListener('popstate', handleLocationChange);\n return () => window.removeEventListener('popstate', handleLocationChange);\n };\n\n return {\n pathname: getPathname(),\n subscribe,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,oBAAuC;CAClD,MAAM,oBACJ,OAAO,WAAW,cACd,qBAAqB,OAAO,SAAS,QAAQ,IAC7C;CAEN,MAAM,aAAa,aAAuD;EACxE,MAAM,6BAAmC,SAAS,YAAY,CAAC;EAC/D,OAAO,iBAAiB,YAAY,oBAAoB;EACxD,aAAa,OAAO,oBAAoB,YAAY,oBAAoB;CAC1E;CAEA,OAAO;EACL,UAAU,YAAY;EACtB;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRewriteURL.mjs","names":[],"sources":["../../../src/client/useRewriteURL.ts"],"sourcesContent":["import { routing } from '@intlayer/config/built';\nimport { getRewritePath } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getIntlayerClient } from './installIntlayer';\n\nconst rewrite = (locale: string): void => {\n if (typeof window === 'undefined' || !routing?.rewrite) return;\n\n const pathname = window.location.pathname;\n const targetPath = getRewritePath(\n pathname,\n locale as Locale,\n routing?.rewrite\n );\n\n if (targetPath && targetPath !== pathname) {\n window.history.replaceState(\n window.history.state,\n '',\n targetPath + window.location.search + window.location.hash\n );\n }\n};\n\n/**\n * Keep the browser URL in sync with the current locale.\n *\n * Rewrites the current URL immediately and subscribes to future locale changes.\n * Returns an `unsubscribe` function to stop listening.\n *\n * Uses `window.history.replaceState` — no full-page navigation.\n *\n * @returns A cleanup function that removes the locale change listener.\n *\n * @example\n * ```ts\n * import { installIntlayer, useRewriteURL } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const unsubscribe = useRewriteURL();\n *\n * // Later, if you want to stop URL rewriting:\n * unsubscribe();\n * ```\n */\nexport const useRewriteURL = (): (() => void) => {\n const client = getIntlayerClient();\n\n // Rewrite immediately for the current locale\n rewrite(client.locale);\n\n return client.subscribe((newLocale) => {\n rewrite(newLocale);\n });\n};\n"],"mappings":";;;;;AAKA,MAAM,WAAW,WAAyB;
|
|
1
|
+
{"version":3,"file":"useRewriteURL.mjs","names":[],"sources":["../../../src/client/useRewriteURL.ts"],"sourcesContent":["import { routing } from '@intlayer/config/built';\nimport { getRewritePath } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getIntlayerClient } from './installIntlayer';\n\nconst rewrite = (locale: string): void => {\n if (typeof window === 'undefined' || !routing?.rewrite) return;\n\n const pathname = window.location.pathname;\n const targetPath = getRewritePath(\n pathname,\n locale as Locale,\n routing?.rewrite\n );\n\n if (targetPath && targetPath !== pathname) {\n window.history.replaceState(\n window.history.state,\n '',\n targetPath + window.location.search + window.location.hash\n );\n }\n};\n\n/**\n * Keep the browser URL in sync with the current locale.\n *\n * Rewrites the current URL immediately and subscribes to future locale changes.\n * Returns an `unsubscribe` function to stop listening.\n *\n * Uses `window.history.replaceState` — no full-page navigation.\n *\n * @returns A cleanup function that removes the locale change listener.\n *\n * @example\n * ```ts\n * import { installIntlayer, useRewriteURL } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const unsubscribe = useRewriteURL();\n *\n * // Later, if you want to stop URL rewriting:\n * unsubscribe();\n * ```\n */\nexport const useRewriteURL = (): (() => void) => {\n const client = getIntlayerClient();\n\n // Rewrite immediately for the current locale\n rewrite(client.locale);\n\n return client.subscribe((newLocale) => {\n rewrite(newLocale);\n });\n};\n"],"mappings":";;;;;AAKA,MAAM,WAAW,WAAyB;CACxC,IAAI,OAAO,WAAW,eAAe,CAAC,SAAS,SAAS;CAExD,MAAM,WAAW,OAAO,SAAS;CACjC,MAAM,aAAa,eACjB,UACA,QACA,SAAS,OACX;CAEA,IAAI,cAAc,eAAe,UAC/B,OAAO,QAAQ,aACb,OAAO,QAAQ,OACf,IACA,aAAa,OAAO,SAAS,SAAS,OAAO,SAAS,IACxD;AAEJ;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,sBAAoC;CAC/C,MAAM,SAAS,kBAAkB;CAGjC,QAAQ,OAAO,MAAM;CAErB,OAAO,OAAO,WAAW,cAAc;EACrC,QAAQ,SAAS;CACnB,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useEditor.mjs","names":[],"sources":["../../../src/editor/useEditor.ts"],"sourcesContent":["import type { EditorStateManager } from '@intlayer/editor';\nimport { isEnabled } from '@intlayer/editor/isEnabled';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Initialises the Intlayer visual editor client.\n *\n * Does nothing when `INTLAYER_EDITOR_ENABLED` is `\"false\"` or the editor\n * package reports that it is disabled.\n *\n * Call this once at application startup.\n *\n * @returns A cleanup function that stops the editor.\n *\n * @example\n * ```ts\n * import { installIntlayer, useEditor } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n * const stopEditor = useEditor();\n * ```\n */\n\nexport const useEditor = (): (() => void) => {\n if (process.env.INTLAYER_EDITOR_ENABLED === 'false' || !isEnabled)\n return () => {};\n\n let unsubscribeLocale: (() => void) | null = null;\n let stopped = false;\n\n import('@intlayer/editor').then(({ initEditorClient }) => {\n if (stopped) return;\n const manager: EditorStateManager = initEditorClient();\n const client = getIntlayerClient();\n\n manager.currentLocale.set(client.locale as Locale);\n\n unsubscribeLocale = client.subscribe((newLocale) => {\n manager.currentLocale.set(newLocale as Locale);\n });\n });\n\n return () => {\n stopped = true;\n unsubscribeLocale?.();\n import('@intlayer/editor').then(({ stopEditorClient }) => {\n stopEditorClient();\n });\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,kBAAgC;
|
|
1
|
+
{"version":3,"file":"useEditor.mjs","names":[],"sources":["../../../src/editor/useEditor.ts"],"sourcesContent":["import type { EditorStateManager } from '@intlayer/editor';\nimport { isEnabled } from '@intlayer/editor/isEnabled';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Initialises the Intlayer visual editor client.\n *\n * Does nothing when `INTLAYER_EDITOR_ENABLED` is `\"false\"` or the editor\n * package reports that it is disabled.\n *\n * Call this once at application startup.\n *\n * @returns A cleanup function that stops the editor.\n *\n * @example\n * ```ts\n * import { installIntlayer, useEditor } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n * const stopEditor = useEditor();\n * ```\n */\n\nexport const useEditor = (): (() => void) => {\n if (process.env.INTLAYER_EDITOR_ENABLED === 'false' || !isEnabled)\n return () => {};\n\n let unsubscribeLocale: (() => void) | null = null;\n let stopped = false;\n\n import('@intlayer/editor').then(({ initEditorClient }) => {\n if (stopped) return;\n const manager: EditorStateManager = initEditorClient();\n const client = getIntlayerClient();\n\n manager.currentLocale.set(client.locale as Locale);\n\n unsubscribeLocale = client.subscribe((newLocale) => {\n manager.currentLocale.set(newLocale as Locale);\n });\n });\n\n return () => {\n stopped = true;\n unsubscribeLocale?.();\n import('@intlayer/editor').then(({ stopEditorClient }) => {\n stopEditorClient();\n });\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,kBAAgC;CAC3C,IAAI,QAAQ,IAAI,4BAA4B,WAAW,CAAC,WACtD,aAAa,CAAC;CAEhB,IAAI,oBAAyC;CAC7C,IAAI,UAAU;CAEd,OAAO,mBAAmB,CAAC,MAAM,EAAE,uBAAuB;EACxD,IAAI,SAAS;EACb,MAAM,UAA8B,iBAAiB;EACrD,MAAM,SAAS,kBAAkB;EAEjC,QAAQ,cAAc,IAAI,OAAO,MAAgB;EAEjD,oBAAoB,OAAO,WAAW,cAAc;GAClD,QAAQ,cAAc,IAAI,SAAmB;EAC/C,CAAC;CACH,CAAC;CAED,aAAa;EACX,UAAU;EACV,oBAAoB;EACpB,OAAO,mBAAmB,CAAC,MAAM,EAAE,uBAAuB;GACxD,iBAAiB;EACnB,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCompact.mjs","names":[],"sources":["../../../src/format/useCompact.ts"],"sourcesContent":["import { compact } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useCompact = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof compact>) =>\n compact(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,mBAAmB;CAC9B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useCompact.mjs","names":[],"sources":["../../../src/format/useCompact.ts"],"sourcesContent":["import { compact } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useCompact = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof compact>) =>\n compact(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,mBAAmB;CAC9B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,QAAQ,KAAK,IAAI;EACf,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCurrency.mjs","names":[],"sources":["../../../src/format/useCurrency.ts"],"sourcesContent":["import { currency } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useCurrency = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof currency>) =>\n currency(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,oBAAoB;CAC/B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useCurrency.mjs","names":[],"sources":["../../../src/format/useCurrency.ts"],"sourcesContent":["import { currency } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useCurrency = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof currency>) =>\n currency(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,oBAAoB;CAC/B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,SAAS,KAAK,IAAI;EAChB,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDate.mjs","names":[],"sources":["../../../src/format/useDate.ts"],"sourcesContent":["import { date, presets } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Vanilla JS hook that provides a localized date/time formatter.\n */\nexport const useDate = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof date>) => {\n const options =\n typeof args[1] === 'string'\n ? { ...presets[args[1]], locale: client.locale }\n : { ...args[1], locale: args[1]?.locale ?? client.locale };\n\n return date(args[0], options as Parameters<typeof date>[1]);\n };\n};\n"],"mappings":";;;;;;;AAMA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useDate.mjs","names":[],"sources":["../../../src/format/useDate.ts"],"sourcesContent":["import { date, presets } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Vanilla JS hook that provides a localized date/time formatter.\n */\nexport const useDate = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof date>) => {\n const options =\n typeof args[1] === 'string'\n ? { ...presets[args[1]], locale: client.locale }\n : { ...args[1], locale: args[1]?.locale ?? client.locale };\n\n return date(args[0], options as Parameters<typeof date>[1]);\n };\n};\n"],"mappings":";;;;;;;AAMA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SAAkC;EAC3C,MAAM,UACJ,OAAO,KAAK,OAAO,WACf;GAAE,GAAG,QAAQ,KAAK;GAAK,QAAQ,OAAO;EAAO,IAC7C;GAAE,GAAG,KAAK;GAAI,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;EAAO;EAE7D,OAAO,KAAK,KAAK,IAAI,OAAqC;CAC5D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIntl.mjs","names":[],"sources":["../../../src/format/useIntl.ts"],"sourcesContent":["import { bindIntl, type WrappedIntl } from '@intlayer/core/utils';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Get a locale-bound `Intl` object and subscribe to locale changes.\n *\n * The returned `intl` property acts like the native `Intl` namespace but\n * automatically uses the current application locale, so you do not need to\n * pass the locale manually to `NumberFormat`, `DateTimeFormat`, etc.\n *\n * @param locale - Optional locale override.\n * @returns An object with `intl: WrappedIntl` and a `subscribe` function.\n *\n * @example\n * ```ts\n * import { installIntlayer, useIntl } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const { intl, subscribe } = useIntl();\n *\n * console.log(new intl.NumberFormat({ style: 'currency', currency: 'USD' }).format(9.99));\n *\n * const unsubscribe = subscribe((newIntl) => {\n * console.log(new newIntl.NumberFormat({ style: 'currency', currency: 'USD' }).format(9.99));\n * });\n * ```\n */\nexport const useIntl = (\n locale?: LocalesValues\n): {\n intl: WrappedIntl;\n subscribe: (callback: (intl: WrappedIntl) => void) => () => void;\n} => {\n const client = getIntlayerClient();\n const intl = bindIntl(locale ?? client.locale);\n\n return {\n intl,\n subscribe: (callback) =>\n client.subscribe((newLocale) => {\n callback(bindIntl(locale ?? newLocale));\n }),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,WACX,WAIG;CACH,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useIntl.mjs","names":[],"sources":["../../../src/format/useIntl.ts"],"sourcesContent":["import { bindIntl, type WrappedIntl } from '@intlayer/core/utils';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Get a locale-bound `Intl` object and subscribe to locale changes.\n *\n * The returned `intl` property acts like the native `Intl` namespace but\n * automatically uses the current application locale, so you do not need to\n * pass the locale manually to `NumberFormat`, `DateTimeFormat`, etc.\n *\n * @param locale - Optional locale override.\n * @returns An object with `intl: WrappedIntl` and a `subscribe` function.\n *\n * @example\n * ```ts\n * import { installIntlayer, useIntl } from 'vanilla-intlayer';\n *\n * installIntlayer('en');\n *\n * const { intl, subscribe } = useIntl();\n *\n * console.log(new intl.NumberFormat({ style: 'currency', currency: 'USD' }).format(9.99));\n *\n * const unsubscribe = subscribe((newIntl) => {\n * console.log(new newIntl.NumberFormat({ style: 'currency', currency: 'USD' }).format(9.99));\n * });\n * ```\n */\nexport const useIntl = (\n locale?: LocalesValues\n): {\n intl: WrappedIntl;\n subscribe: (callback: (intl: WrappedIntl) => void) => () => void;\n} => {\n const client = getIntlayerClient();\n const intl = bindIntl(locale ?? client.locale);\n\n return {\n intl,\n subscribe: (callback) =>\n client.subscribe((newLocale) => {\n callback(bindIntl(locale ?? newLocale));\n }),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,WACX,WAIG;CACH,MAAM,SAAS,kBAAkB;CAGjC,OAAO;EACL,MAHW,SAAS,UAAU,OAAO,MAGlC;EACH,YAAY,aACV,OAAO,WAAW,cAAc;GAC9B,SAAS,SAAS,UAAU,SAAS,CAAC;EACxC,CAAC;CACL;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useList.mjs","names":[],"sources":["../../../src/format/useList.ts"],"sourcesContent":["import { list } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useList = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof list>) =>\n list(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useList.mjs","names":[],"sources":["../../../src/format/useList.ts"],"sourcesContent":["import { list } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useList = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof list>) =>\n list(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,KAAK,KAAK,IAAI;EACZ,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNumber.mjs","names":[],"sources":["../../../src/format/useNumber.ts"],"sourcesContent":["import { number } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Vanilla JS hook that provides a localized number formatter.\n */\nexport const useNumber = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof number>) =>\n number(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;;;;AAMA,MAAa,kBAAkB;CAC7B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useNumber.mjs","names":[],"sources":["../../../src/format/useNumber.ts"],"sourcesContent":["import { number } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\n/**\n * Vanilla JS hook that provides a localized number formatter.\n */\nexport const useNumber = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof number>) =>\n number(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;;;;AAMA,MAAa,kBAAkB;CAC7B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,OAAO,KAAK,IAAI;EACd,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePercentage.mjs","names":[],"sources":["../../../src/format/usePercentage.ts"],"sourcesContent":["import { percentage } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const usePercentage = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof percentage>) =>\n percentage(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,sBAAsB;CACjC,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"usePercentage.mjs","names":[],"sources":["../../../src/format/usePercentage.ts"],"sourcesContent":["import { percentage } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const usePercentage = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof percentage>) =>\n percentage(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,sBAAsB;CACjC,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,WAAW,KAAK,IAAI;EAClB,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRelativeTime.mjs","names":[],"sources":["../../../src/format/useRelativeTime.ts"],"sourcesContent":["import { relativeTime } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useRelativeTime = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof relativeTime>) =>\n relativeTime(args[0], args[1], {\n ...args[2],\n locale: args[2]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,wBAAwB;CACnC,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useRelativeTime.mjs","names":[],"sources":["../../../src/format/useRelativeTime.ts"],"sourcesContent":["import { relativeTime } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useRelativeTime = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof relativeTime>) =>\n relativeTime(args[0], args[1], {\n ...args[2],\n locale: args[2]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,wBAAwB;CACnC,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,aAAa,KAAK,IAAI,KAAK,IAAI;EAC7B,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useUnit.mjs","names":[],"sources":["../../../src/format/useUnit.ts"],"sourcesContent":["import { units } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useUnit = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof units>) =>\n units(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"useUnit.mjs","names":[],"sources":["../../../src/format/useUnit.ts"],"sourcesContent":["import { units } from '@intlayer/core/formatters';\nimport { getIntlayerClient } from '../client/installIntlayer';\n\nexport const useUnit = () => {\n const client = getIntlayerClient();\n\n return (...args: Parameters<typeof units>) =>\n units(args[0], {\n ...args[1],\n locale: args[1]?.locale ?? client.locale,\n });\n};\n"],"mappings":";;;;AAGA,MAAa,gBAAgB;CAC3B,MAAM,SAAS,kBAAkB;CAEjC,QAAQ,GAAG,SACT,MAAM,KAAK,IAAI;EACb,GAAG,KAAK;EACR,QAAQ,KAAK,EAAE,EAAE,UAAU,OAAO;CACpC,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDictionary.mjs","names":["getDictionaryCore"],"sources":["../../src/getDictionary.ts"],"sourcesContent":["import { getDictionary as getDictionaryCore } from '@intlayer/core/interpreter';\nimport type {\n Dictionary,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { type DeepTransformContent, getPlugins } from './plugins';\n\n/**\n * Transforms a dictionary (or qualified dictionary group) and returns its\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n */\nexport const getDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n ExtractSelectorLocale<A>\n> => {\n const locale = (\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector.locale\n : localeOrSelector\n ) as LocalesValues | undefined;\n\n return getDictionaryCore(\n dictionary,\n localeOrSelector,\n getPlugins(locale)\n ) as any;\n};\n"],"mappings":";;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAIG;
|
|
1
|
+
{"version":3,"file":"getDictionary.mjs","names":["getDictionaryCore"],"sources":["../../src/getDictionary.ts"],"sourcesContent":["import { getDictionary as getDictionaryCore } from '@intlayer/core/interpreter';\nimport type {\n Dictionary,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { type DeepTransformContent, getPlugins } from './plugins';\n\n/**\n * Transforms a dictionary (or qualified dictionary group) and returns its\n * content for the given locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n */\nexport const getDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n): DeepTransformContent<\n ResolveQualifiedDictionaryContent<T, A>,\n ExtractSelectorLocale<A>\n> => {\n const locale = (\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector.locale\n : localeOrSelector\n ) as LocalesValues | undefined;\n\n return getDictionaryCore(\n dictionary,\n localeOrSelector,\n getPlugins(locale)\n ) as any;\n};\n"],"mappings":";;;;;;;;;AAmBA,MAAa,iBAMX,YACA,qBAIG;CAOH,OAAOA,gBACL,YACA,kBACA,WARA,OAAO,qBAAqB,YAAY,qBAAqB,OACzD,iBAAiB,SACjB,gBAMa,CACnB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayer.mjs","names":["getIntlayerCore"],"sources":["../../src/getIntlayer.ts"],"sourcesContent":["import { getIntlayer as getIntlayerCore } from '@intlayer/core/interpreter';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n DictionarySelectorForKey,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { type DeepTransformContent, getPlugins } from './plugins';\n\n/**\n * Picks one dictionary by its key and returns its content for the given\n * locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n */\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): DeepTransformContent<\n DictionaryRegistryResult<T, A>,\n ExtractSelectorLocale<A>\n> => {\n const locale = (\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector.locale\n : localeOrSelector\n ) as LocalesValues | undefined;\n\n return getIntlayerCore(key, localeOrSelector, getPlugins(locale)) as any;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAa,eAIX,KACA,qBAIG;
|
|
1
|
+
{"version":3,"file":"getIntlayer.mjs","names":["getIntlayerCore"],"sources":["../../src/getIntlayer.ts"],"sourcesContent":["import { getIntlayer as getIntlayerCore } from '@intlayer/core/interpreter';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n DictionarySelectorForKey,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { type DeepTransformContent, getPlugins } from './plugins';\n\n/**\n * Picks one dictionary by its key and returns its content for the given\n * locale or selector (`{ item }`, `{ variant }`,\n * optionally combined with `locale`).\n */\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n): DeepTransformContent<\n DictionaryRegistryResult<T, A>,\n ExtractSelectorLocale<A>\n> => {\n const locale = (\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector.locale\n : localeOrSelector\n ) as LocalesValues | undefined;\n\n return getIntlayerCore(key, localeOrSelector, getPlugins(locale)) as any;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAa,eAIX,KACA,qBAIG;CAOH,OAAOA,cAAgB,KAAK,kBAAkB,WAL5C,OAAO,qBAAqB,YAAY,qBAAqB,OACzD,iBAAiB,SACjB,gBAGyD,CAAC;AAClE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HTMLRenderer.mjs","names":[],"sources":["../../../src/html/HTMLRenderer.ts"],"sourcesContent":["import { type RenderHTMLOptions, useHTML } from './installIntlayerHTML';\nimport type { HTMLComponents } from './types';\n\nexport type RenderHTMLProps = {\n components?: HTMLComponents<'permissive', {}>;\n};\n\n/**\n * Renders an HTML string directly, without a global provider.\n * Returns the raw string unchanged.\n */\nexport const renderHTML = (\n content: string,\n _props: RenderHTMLProps = {}\n): string => content;\n\n/**\n * Returns a render function that uses the global provider's configuration\n * (installed via `installIntlayerHTML`), falling back to identity.\n */\nexport const useHTMLRenderer = ({\n components,\n}: RenderHTMLProps = {}): ((content: string) => string) => {\n const context = useHTML();\n\n return (content: string) =>\n context.renderHTML(content, { components } as RenderHTMLOptions);\n};\n"],"mappings":";;;;;;;AAWA,MAAa,cACX,SACA,SAA0B,
|
|
1
|
+
{"version":3,"file":"HTMLRenderer.mjs","names":[],"sources":["../../../src/html/HTMLRenderer.ts"],"sourcesContent":["import { type RenderHTMLOptions, useHTML } from './installIntlayerHTML';\nimport type { HTMLComponents } from './types';\n\nexport type RenderHTMLProps = {\n components?: HTMLComponents<'permissive', {}>;\n};\n\n/**\n * Renders an HTML string directly, without a global provider.\n * Returns the raw string unchanged.\n */\nexport const renderHTML = (\n content: string,\n _props: RenderHTMLProps = {}\n): string => content;\n\n/**\n * Returns a render function that uses the global provider's configuration\n * (installed via `installIntlayerHTML`), falling back to identity.\n */\nexport const useHTMLRenderer = ({\n components,\n}: RenderHTMLProps = {}): ((content: string) => string) => {\n const context = useHTML();\n\n return (content: string) =>\n context.renderHTML(content, { components } as RenderHTMLOptions);\n};\n"],"mappings":";;;;;;;AAWA,MAAa,cACX,SACA,SAA0B,CAAC,MAChB;;;;;AAMb,MAAa,mBAAmB,EAC9B,eACmB,CAAC,MAAqC;CACzD,MAAM,UAAU,QAAQ;CAExB,QAAQ,YACN,QAAQ,WAAW,SAAS,EAAE,WAAW,CAAsB;AACnE"}
|
|
@@ -78,7 +78,8 @@ const useHTML = () => {
|
|
|
78
78
|
*/
|
|
79
79
|
const installIntlayerHTMLDynamic = async (loader) => {
|
|
80
80
|
if (instance) return instance;
|
|
81
|
-
|
|
81
|
+
const pluginOptions = await loader();
|
|
82
|
+
return installIntlayerHTML(pluginOptions);
|
|
82
83
|
};
|
|
83
84
|
|
|
84
85
|
//#endregion
|