@intlayer/ai 9.2.0 → 9.3.1

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/README.md CHANGED
@@ -47,27 +47,27 @@ With **per-locale content files**, **TypeScript autocompletion**, **tree-shakabl
47
47
 
48
48
  ## Keys benefits of Intlayer:
49
49
 
50
- | Feature | Description |
51
- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more. |
53
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content) |
54
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file) |
55
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/compiler.jpg?raw=true" alt="Feature" width="700"> | **Compiler**<br><br>The Intlayer Compiler extract automatically the content from the components and generate the dictionary files.<br><br> - [Compiler](https://intlayer.org/doc/compiler) |
56
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript) |
57
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
58
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app) |
59
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code) |
60
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer) |
61
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
62
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file) |
63
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms) |
64
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization) |
65
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs) |
66
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill) |
67
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md) |
68
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension) |
69
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, react-intl, vue-i18n. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) <br> - [Intlayer and vue-i18n](https://intlayer.org/blog/intlayer-with-vue-i18n) |
70
- | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/benchmark.png?raw=true" alt="Feature" width="700"> | **Performances & Benchmark**<br><br>Uses advanced tree-shaking and dynamic loading to boost performances and keep the solution as light as possible. <br><br> - [Performances & Benchmark](https://intlayer.org/doc/benchmark) |
50
+ | Feature | Description |
51
+ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more. |
53
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content) |
54
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file) |
55
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/compiler.jpg?raw=true" alt="Feature" width="700"> | **Compiler**<br><br>The Intlayer Compiler extract automatically the content from the components and generate the dictionary files.<br><br> - [Compiler](https://intlayer.org/doc/compiler) |
56
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript) |
57
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
58
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app) |
59
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code) |
60
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer) |
61
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
62
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file) |
63
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms) |
64
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization) |
65
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs) |
66
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill) |
67
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md) |
68
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension) |
69
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, react-intl, vue-i18n. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) <br> - [Intlayer and vue-i18n](https://intlayer.org/blog/intlayer-with-vue-i18n) <br> - [Intlayer compat adapters](https://intlayer.org/doc/compatibility) |
70
+ | <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/benchmark.png?raw=true" alt="Feature" width="700"> | **Performances & Benchmark**<br><br>Uses advanced tree-shaking and dynamic loading to boost performances and keep the solution as light as possible. <br><br> - [Performances & Benchmark](https://intlayer.org/doc/benchmark) |
71
71
 
72
72
  ---
73
73
 
@@ -162,7 +162,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
162
162
  <li><a href="https://intlayer.org/doc/concept/cms" rel=''>Intlayer CMS</a></li>
163
163
  <li><a href="https://intlayer.org/doc/concept/content" rel=''>Dictionary</a>
164
164
  <ul>
165
- <li><a href="https://intlayer.org/doc/concept/content/per-locale-file" rel=''>Per-Locale Content Declaration File</a></li>
165
+ <li><a href="https://intlayer.org/doc/concept/per-locale-file" rel=''>Per-Locale Content Declaration File</a></li>
166
166
  <li><a href="https://intlayer.org/doc/concept/content/translation" rel=''>Translation</a></li>
167
167
  <li><a href="https://intlayer.org/doc/concept/content/enumeration" rel=''>Enumeration</a></li>
168
168
  <li><a href="https://intlayer.org/doc/concept/content/condition" rel=''>Condition</a></li>
@@ -183,7 +183,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
183
183
  <ul>
184
184
  <li><a href="https://intlayer.org/doc/environment/nextjs/15" rel=''>Next.js 15</a></li>
185
185
  <li><a href="https://intlayer.org/doc/environment/nextjs/14" rel=''>Next.js 14 (App Router)</a></li>
186
- <li><a href="https://intlayer.org/doc/environment/nextjs/next-with-Page-Router" rel=''>Next.js Page Router</a></li>
186
+ <li><a href="https://intlayer.org/doc/environment/nextjs/next-with-page-router" rel=''>Next.js Page Router</a></li>
187
187
  <li><a href="https://intlayer.org/doc/environment/nextjs/compiler" rel=''>Next.js using Compiler</a></li>
188
188
  </ul>
189
189
  </li>
@@ -212,7 +212,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
212
212
  <li><a href="https://intlayer.org/doc/environment/sveltekit" rel=''>SvelteKit</a></li>
213
213
  <li><a href="https://intlayer.org/doc/environment/vite-and-preact" rel=''>Vite + Preact</a></li>
214
214
  <li><a href="https://intlayer.org/doc/environment/vite-and-vue" rel=''>Vite + Vue</a></li>
215
- <li><a href="https://intlayer.org/doc/environment/vite-and-nuxt" rel=''>Vite + Nuxt</a></li>
215
+ <li><a href="https://intlayer.org/doc/environment/nuxt-and-vue" rel=''>Vite + Nuxt</a></li>
216
216
  <li><a href="https://intlayer.org/doc/environment/vite-and-solid" rel=''>Vite + Solid</a></li>
217
217
  <li><a href="https://intlayer.org/doc/environment/angular" rel=''>Angular</a></li>
218
218
  <li>
@@ -19,11 +19,10 @@ var __copyProps = (to, from, except, desc) => {
19
19
  }
20
20
  return to;
21
21
  };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
23
  value: mod,
24
24
  enumerable: true
25
25
  }) : target, mod));
26
26
 
27
27
  //#endregion
28
-
29
28
  exports.__toESM = __toESM;
@@ -70,10 +70,11 @@ const readAsset = (relPath, encoding = "utf8") => {
70
70
  const distRoot = findDistRoot(here) ?? (0, node_path.resolve)(here, "..", "..", "dist");
71
71
  const assetsRoot = (0, node_path.join)(distRoot, "assets");
72
72
  const tried = [];
73
+ const callerDirAbs = getCallerDir();
73
74
  /**
74
75
  * Transform dist/(esm|cjs)/... and _virtual/ prefix to clean subpath (Windows-safe)
75
76
  */
76
- const callerSubpath = (0, node_path.relative)(distRoot, getCallerDir()).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
77
+ const callerSubpath = (0, node_path.relative)(distRoot, callerDirAbs).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
77
78
  if (relPath.startsWith("./") || relPath.startsWith("../")) {
78
79
  const fromCallerAbs = (0, node_path.resolve)(assetsRoot, callerSubpath, relPath);
79
80
  tried.push(fromCallerAbs);
@@ -182,6 +182,15 @@ const getLanguageModel = async (aiOptions, apiKey) => {
182
182
  ...otherOptions
183
183
  })(selectedModel);
184
184
  }
185
+ case _intlayer_types_config.AiProviders.MOONSHOTAI: {
186
+ const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
187
+ const { createMoonshotAI } = await loadModule("@ai-sdk/moonshotai");
188
+ return createMoonshotAI({
189
+ apiKey,
190
+ baseURL,
191
+ ...otherOptions
192
+ })(selectedModel);
193
+ }
185
194
  default: throw new Error(`Provider ${provider} not supported`);
186
195
  }
187
196
  };
@@ -1 +1 @@
1
- {"version":3,"file":"aiSdk.cjs","names":["AiProviders","x","ANSIColors"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type {\n createOpenAICompatible,\n OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\ntype LMStudioModel = Parameters<OpenAICompatibleProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\nexport type LMStudioProviderOptions = Parameters<\n typeof createOpenAICompatible\n>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | LMStudioModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({\n provider: AiProviders.LMSTUDIO | `${AiProviders.LMSTUDIO}`;\n } & LMStudioProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst isMaskedKey = (key?: string): boolean => !!key?.includes('*');\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n const apiKey =\n aiOptions?.apiKey && !isMaskedKey(aiOptions.apiKey)\n ? aiOptions.apiKey\n : undefined;\n\n if (accessType.includes('public')) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && apiKey) {\n return apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (\n isUserProvidedKey ||\n provider === AiProviders.OLLAMA ||\n provider === AiProviders.LMSTUDIO\n ) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n case AiProviders.LMSTUDIO: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAICompatible } = await loadModule<\n typeof import('@ai-sdk/openai-compatible')\n >('@ai-sdk/openai-compatible');\n\n const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: baseURL ?? 'http://localhost:1234/v1',\n ...otherOptions,\n });\n\n return lmstudio(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const mergeWithoutUndefined = (...sources: (AIOptions | undefined)[]) => {\n const result: Record<string, unknown> = { provider: DEFAULT_PROVIDER };\n for (const source of sources) {\n if (!source) continue;\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined) continue;\n if (key === 'apiKey' && isMaskedKey(value as string)) continue;\n result[key] = value;\n }\n }\n return result;\n };\n\n const aiOptions = mergeWithoutUndefined(\n defaultOptions,\n projectOptions,\n userOptions\n ) as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (\n !apiKey &&\n aiOptions.provider !== AiProviders.OLLAMA &&\n aiOptions.provider !== AiProviders.LMSTUDIO\n ) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;;;;AA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2BAAqB;GACnB,GAAG;GACH,UAAU,CACR;IACE,MAAM;IACN,SAAS;GACX,CACF;GACA,iBAAiB;EACnB,CAAC;EACD,OAAO,EAAE,aAAa,KAAK;CAC7B,SAAS,OAAO;EACd,OAAO;GAAE,aAAa;GAAO,OAAQ,MAAgB;EAAQ;CAC/D;AACF;;;;;;;;AASA,MAAa,cAAc,OACzB,SACA,kBAA2B,UACL;CACtB,MAAM,EACJ,aACA,gBACA,gBACA,aAAa,CAAC,iBAAiB,MAC7B;CAEJ,MAAM,yBAAyB,GAAG,YAAuC;EACvE,MAAM,SAAkC,EAAE,UAAU,iBAAiB;EACrE,KAAK,MAAM,UAAU,SAAS;GAC5B,IAAI,CAAC,QAAQ;GACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;IACjD,IAAI,UAAU,QAAW;IACzB,IAAI,QAAQ,YAAY,YAAY,KAAe,GAAG;IACtD,OAAO,OAAO;GAChB;EACF;EACA,OAAO;CACT;CAEA,MAAM,YAAY,sBAChB,gBACA,gBACA,WACF;CAEA,MAAM,SAAS,UAAU,YAAY,WAAW,eAAe;CAG/D,IACE,CAAC,UACD,UAAU,aAAaA,mCAAY,UACnC,UAAU,aAAaA,mCAAY,UAEnC,MAAM,IAAI,MAAM,eAAe,UAAU,SAAS,YAAY;CAKhE,OAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,MAAM;EAI5D,aAAa,UAAU;EACvB,mBAAmB,UAAU;CAC/B;AACF"}
1
+ {"version":3,"file":"aiSdk.cjs","names":["AiProviders","x","colorize","ANSIColors","generateTextFn"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createMoonshotAI, MoonshotAIProvider } from '@ai-sdk/moonshotai';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type {\n createOpenAICompatible,\n OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\ntype LMStudioModel = Parameters<OpenAICompatibleProvider>[0];\ntype MoonshotAIModel = Parameters<MoonshotAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\nexport type LMStudioProviderOptions = Parameters<\n typeof createOpenAICompatible\n>[0];\nexport type MoonshotAIProviderOptions = Parameters<typeof createMoonshotAI>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | LMStudioModel\n | MoonshotAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({\n provider: AiProviders.LMSTUDIO | `${AiProviders.LMSTUDIO}`;\n } & LMStudioProviderOptions)\n | ({\n provider: AiProviders.MOONSHOTAI | `${AiProviders.MOONSHOTAI}`;\n } & MoonshotAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst isMaskedKey = (key?: string): boolean => !!key?.includes('*');\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n const apiKey =\n aiOptions?.apiKey && !isMaskedKey(aiOptions.apiKey)\n ? aiOptions.apiKey\n : undefined;\n\n if (accessType.includes('public')) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && apiKey) {\n return apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (\n isUserProvidedKey ||\n provider === AiProviders.OLLAMA ||\n provider === AiProviders.LMSTUDIO\n ) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n case AiProviders.LMSTUDIO: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAICompatible } = await loadModule<\n typeof import('@ai-sdk/openai-compatible')\n >('@ai-sdk/openai-compatible');\n\n const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: baseURL ?? 'http://localhost:1234/v1',\n ...otherOptions,\n });\n\n return lmstudio(selectedModel as string);\n }\n\n case AiProviders.MOONSHOTAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMoonshotAI } =\n await loadModule<typeof import('@ai-sdk/moonshotai')>(\n '@ai-sdk/moonshotai'\n );\n\n const moonshotai = createMoonshotAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return moonshotai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const mergeWithoutUndefined = (...sources: (AIOptions | undefined)[]) => {\n const result: Record<string, unknown> = { provider: DEFAULT_PROVIDER };\n for (const source of sources) {\n if (!source) continue;\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined) continue;\n if (key === 'apiKey' && isMaskedKey(value as string)) continue;\n result[key] = value;\n }\n }\n return result;\n };\n\n const aiOptions = mergeWithoutUndefined(\n defaultOptions,\n projectOptions,\n userOptions\n ) as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (\n !apiKey &&\n aiOptions.provider !== AiProviders.OLLAMA &&\n aiOptions.provider !== AiProviders.LMSTUDIO\n ) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;;;;AA6CA,MAAM,mBAAmBA,mCAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AAkKpC,MAAM,eAAe,QAA0B,CAAC,CAAC,KAAK,SAAS,GAAG;AAElE,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;CACH,MAAM,SACJ,WAAW,UAAU,CAAC,YAAY,UAAU,MAAM,IAC9C,UAAU,SACV;CAEN,IAAI,WAAW,SAAS,QAAQ,GAC9B,OAAO,UAAU;CAGnB,IAAI,WAAW,SAAS,QAAQ,KAAK,QACnC,OAAO;CAGT,IAAI,WAAW,SAAS,iBAAiB,KAAK,iBAC5C,OAAO,UAAU;CAInB,IAAI,WAAW,SAAS,cAAc,KAAK,iBACzC,OAAO,UAAU;AAIrB;AAEA,MAAM,gBACJ,UACA,mBACA,cACU;CAEV,IACE,qBACA,aAAaA,mCAAY,UACzB,aAAaA,mCAAY,UACzB;EACA,IAAI,WACF,OAAO;EAIT,OAAO;CACT;CAIA,OAAO;AACT;AAEA,MAAM,mBAAmB,OACvB,WACA,WACG;CACH,MAAM,aAAa,OAAU,gBAAoC;EAC/D,IAAI;GACF,OAAQ,MAAM,OAAO;EACvB,QAAQ;GACN,oCACE,GAAGC,0BAAE,oBAAgBC,kCAAS,aAAaC,wBAAW,KAAK,EAAE,sEAAkED,kCAAS,eAAe,eAAeC,wBAAW,SAAS,KAC1L,EACE,OAAO,QACT,CACF;GACA,QAAQ,KAAK;EACf;CACF;CAEA,MAAM,WAAW,UAAU,YAAYH,mCAAY;CACnD,MAAM,gBAAgB,aACpB,UACA,CAAC,CAAC,UAAU,QACZ,UAAU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UAAU,aAAaA,mCAAY,UAEnC,MAAM,IAAI,MAAM,eAAe,UAAU,SAAS,YAAY;CAKhE,OAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,MAAM;EAI5D,aAAa,UAAU;EACvB,mBAAmB,UAAU;CAC/B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readAsset","Output","z"],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n system: prompt,\n messages: [\n { role: 'user', content: EXAMPLE_REQUEST },\n { role: 'assistant', content: EXAMPLE_RESPONSE },\n {\n role: 'user',\n content: fileContent,\n },\n ],\n });\n\n return {\n fileContent: output,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;AA0BA,MAAa,mBAA8B,CAE3C;;;;;;AAOA,MAAa,0BAA0B,OAAO,EAC5C,aACA,MACA,UACA,yBAGG;CACH,MAAM,kBAAkBA,+BAAU,aAAa;CAC/C,MAAM,kBAAkBA,+BAAU,sBAAsB;CACxD,MAAM,mBAAmBA,+BAAU,uBAAuB;CAG1D,MAAM,SAAS,gBAAgB,QAC7B,0BACA,sBAAsB,EACxB,CAAC,CAAC,QACA,YACA,OACI,KAAK,UACH,KACG,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,aAAa,CAAC,CACzD,KAAK,MAAM,GACd,MACA,CACF,IACA,EACN;CAEA,MAAM,EAAE,mBAAmB,GAAG,iBAAiB;CAC/C,MAAM,EAAE,QAAQ,eAAe,GAAG,kBAAkB;CAGpD,MAAM,EAAE,QAAQ,UAAU,2BAAmB;EAC3C,GAAG;EACH,QAAQC,UAAO,OAAO,EACpB,QAAQC,MAAE,OAAO;GACf,OAAOA,MAAE,OAAO;GAChB,aAAaA,MAAE,OAAO;GACtB,MAAMA,MAAE,MAAMA,MAAE,OAAO,CAAC;EAC1B,CAAC,EACH,CAAC;EACD,QAAQ;EACR,UAAU;GACR;IAAE,MAAM;IAAQ,SAAS;GAAgB;GACzC;IAAE,MAAM;IAAa,SAAS;GAAiB;GAC/C;IACE,MAAM;IACN,SAAS;GACX;EACF;CACF,CAAC;CAED,OAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;CACnC;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["readAsset","generateText","Output","z"],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n system: prompt,\n messages: [\n { role: 'user', content: EXAMPLE_REQUEST },\n { role: 'assistant', content: EXAMPLE_RESPONSE },\n {\n role: 'user',\n content: fileContent,\n },\n ],\n });\n\n return {\n fileContent: output,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;AA0BA,MAAa,mBAA8B,CAE3C;;;;;;AAOA,MAAa,0BAA0B,OAAO,EAC5C,aACA,MACA,UACA,yBAGG;CACH,MAAM,kBAAkBA,+BAAU,aAAa;CAC/C,MAAM,kBAAkBA,+BAAU,sBAAsB;CACxD,MAAM,mBAAmBA,+BAAU,uBAAuB;CAG1D,MAAM,SAAS,gBAAgB,QAC7B,0BACA,sBAAsB,EACxB,CAAC,CAAC,QACA,YACA,OACI,KAAK,UACH,KACG,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,aAAa,CAAC,CACzD,KAAK,MAAM,GACd,MACA,CACF,IACA,EACN;CAEA,MAAM,EAAE,mBAAmB,GAAG,iBAAiB;CAC/C,MAAM,EAAE,QAAQ,eAAe,GAAG,kBAAkB;CAGpD,MAAM,EAAE,QAAQ,UAAU,UAAMC,iBAAa;EAC3C,GAAG;EACH,QAAQC,UAAO,OAAO,EACpB,QAAQC,MAAE,OAAO;GACf,OAAOA,MAAE,OAAO;GAChB,aAAaA,MAAE,OAAO;GACtB,MAAMA,MAAE,MAAMA,MAAE,OAAO,CAAC;EAC1B,CAAC,EACH,CAAC;EACD,QAAQ;EACR,UAAU;GACR;IAAE,MAAM;IAAQ,SAAS;GAAgB;GACzC;IAAE,MAAM;IAAa,SAAS;GAAiB;GAC/C;IACE,MAAM;IACN,SAAS;GACX;EACF;CACF,CAAC;CAED,OAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;CACnC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"customQuery.cjs","names":[],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText, type SystemModelMessage } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n system?: string | SystemModelMessage | SystemModelMessage[];\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n system,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n system,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;AAcA,MAAa,mBAA8B,EACzC,OAAO,cAET;;;;;;AAOA,MAAa,cAAc,OAAO,EAChC,UACA,QACA,eACoE;CAEpE,MAAM,EAAE,MAAM,YAAY,UAAU,2BAAmB;EACrD,GAAG;EACH;EACA;CACF,CAAC;CAED,OAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;CACnC;AACF"}
1
+ {"version":3,"file":"customQuery.cjs","names":["generateText"],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText, type SystemModelMessage } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n system?: string | SystemModelMessage | SystemModelMessage[];\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n system,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n system,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;AAcA,MAAa,mBAA8B,EACzC,OAAO,cAET;;;;;;AAOA,MAAa,cAAc,OAAO,EAChC,UACA,QACA,eACoE;CAEpE,MAAM,EAAE,MAAM,YAAY,UAAU,UAAMA,iBAAa;EACrD,GAAG;EACH;EACA;CACF,CAAC;CAED,OAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;CACnC;AACF"}
@@ -91,8 +91,9 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
91
91
  ].join("\n")
92
92
  }]
93
93
  });
94
+ const cleanedText = text.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm, "$1").trim();
94
95
  return {
95
- fileContent: (0, _toon_format_toon.decode)(text.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm, "$1").trim()),
96
+ fileContent: (0, _toon_format_toon.decode)(cleanedText),
96
97
  tokenUsed: usage?.totalTokens ?? 0
97
98
  };
98
99
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["AIProvider","DEFAULT_LOCALE","z","readAsset","Output","extractJson"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,mCAAW;CACrB,OAAO;AACT;;;;;;;AAQA,MAAM,wBAAwB,WAC5B,GAAG,OAAO,mDAAkB,QAAQC,6CAAc;;;;;;;;AASpD,MAAM,yBAAyB,SAAwB;CACrD,IAAI,CAAC,QAAQ,KAAK,WAAW,GAC3B,OAAO;CAIT,OAAO;;EAEP,KAAK,KAAK,EAAE,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T_LOCALE","z","readAsset","encode","generateText","decode","Output","extractJson"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,mCAAW;CACrB,OAAO;AACT;;;;;;;AAQA,MAAM,wBAAwB,WAC5B,GAAG,OAAO,QAAIC,2CAAc,QAAQC,6CAAc;;;;;;;;AASpD,MAAM,yBAAyB,SAAwB;CACrD,IAAI,CAAC,QAAQ,KAAK,WAAW,GAC3B,OAAO;CAIT,OAAO;;EAEP,KAAK,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,aAAa,CAAC,CAAC,KAAK,MAAM;AAC5E;AAEA,MAAM,uBAAuB,SAAwC;CACnE,IAAI,SAAS,YACX,OAAO;CAGT,OAAO;AACT;AAEA,MAAM,aAAa,YAA+B;CAEhD,IAAI,OAAO,YAAY,UACrB,OAAOC,MAAE,OAAO;CAIlB,IAAI,OAAO,YAAY,UACrB,OAAOA,MAAE,OAAO;CAElB,IAAI,OAAO,YAAY,WACrB,OAAOA,MAAE,QAAQ;CAInB,IAAI,MAAM,QAAQ,OAAO,GAAG;EAE1B,IAAI,QAAQ,WAAW,GACrB,OAAOA,MAAE,MAAMA,MAAE,OAAO,CAAC;EAG3B,OAAOA,MAAE,MAAM,UAAU,QAAQ,EAAE,CAAC;CACtC;CAGA,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM;EACnD,MAAM,QAAsC,CAAC;EAC7C,KAAK,MAAM,OAAO,SAChB,MAAM,OAAO,UAAU,QAAQ,IAAI;EAErC,OAAOA,MAAE,OAAO,KAAK;CACvB;CAGA,OAAOA,MAAE,O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c,KACjB,QAAQ,qCAAqC,IAAI,CAAC,CAClD,KAAK;EAMR,OAAO;GACL,iBALkBC,0BAAO,WAKF;GACvB,WAAW,OAAO,eAAe;EACnC;CACF;CAMA,MAAM,kBAJY,UAAU,gBAII,KAAK;CAGrC,MAAM,EAAE,MAAM,UAAU,UAAMD,iBAAa;EACzC,GAAG;EAGH,QAAQ,kBAAkBE,UAAO,OAAO,EAAE,OAAO,CAAC,IAAI;EACtD,QAAQ;EACR,UAAU,CACR;GACE,MAAM;GACN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,KAAK,IAAI;EACb,CACF;CACF,CAAC;CAGD,MAAM,gBAAgBC,sCAAY,IAAI;CAGtC,OAAO;EACL,aAHuB,OAAO,MAAM,aAGR;EAC5B,WAAW,OAAO,eAAe;CACnC;AACF"}
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
2
  //#region src/utils/extractJSON.ts
4
3
  /**
5
4
  * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.
@@ -1 +1 @@
1
- {"version":3,"file":"extractJSON.cjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (!inString) {\n if (char === openChar) {\n depth++;\n } else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eAAwB,UAAqB;CACxD,MAAM,UAAU,MAAM,MAAM,MAAM;CAClC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,yCAAyC;CAEvE,MAAM,WAAW,QAAQ;CACzB,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,aAAa,MAAM,MAAM;CAE3C,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,UAAU,IAAI,MAAM,QAAQ,KAAK;EAC5C,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS;GACX,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAM;GACjB,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,WAAW,CAAC;GACZ;EACF;EAEA,IAAI,CAAC,UACH;OAAI,SAAS,UACX;QACK,IAAI,SAAS,WAAW;IAC7B;IACA,IAAI,UAAU,GAAG;KACf,MAAM,gBAAgB,MAAM,MAAM,UAAU,IAAI,CAAC;KACjD,IAAI;MACF,OAAO,KAAK,MAAM,aAAa;KACjC,SAAS,KAAK;MACZ,MAAM,IAAI,MAAM,yBAA0B,IAAc,SAAS;KACnE;IACF;GACF;;CAEJ;CAEA,MAAM,IAAI,MAAM,oDAAoD;AACtE"}
1
+ {"version":3,"file":"extractJSON.cjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (!inString) {\n if (char === openChar) {\n depth++;\n } else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eAAwB,UAAqB;CACxD,MAAM,UAAU,MAAM,MAAM,MAAM;CAClC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,yCAAyC;CAEvE,MAAM,WAAW,QAAQ;CACzB,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,aAAa,MAAM,MAAM;CAE3C,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,UAAU,IAAI,MAAM,QAAQ,KAAK;EAC5C,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS;GACX,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAM;GACjB,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,WAAW,CAAC;GACZ;EACF;EAEA,IAAI,CAAC,UAAU;GACb,IAAI,SAAS,UACX;QACK,IAAI,SAAS,WAAW;IAC7B;IACA,IAAI,UAAU,GAAG;KACf,MAAM,gBAAgB,MAAM,MAAM,UAAU,IAAI,CAAC;KACjD,IAAI;MACF,OAAO,KAAK,MAAM,aAAa;KACjC,SAAS,KAAK;MACZ,MAAM,IAAI,MAAM,yBAA0B,IAAc,SAAS;KACnE;IACF;GACF;EACF;CACF;CAEA,MAAM,IAAI,MAAM,oDAAoD;AACtE"}
@@ -70,10 +70,11 @@ const readAsset = (relPath, encoding = "utf8") => {
70
70
  const distRoot = findDistRoot(here) ?? resolve(here, "..", "..", "dist");
71
71
  const assetsRoot = join(distRoot, "assets");
72
72
  const tried = [];
73
+ const callerDirAbs = getCallerDir();
73
74
  /**
74
75
  * Transform dist/(esm|cjs)/... and _virtual/ prefix to clean subpath (Windows-safe)
75
76
  */
76
- const callerSubpath = relative(distRoot, getCallerDir()).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
77
+ const callerSubpath = relative(distRoot, callerDirAbs).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
77
78
  if (relPath.startsWith("./") || relPath.startsWith("../")) {
78
79
  const fromCallerAbs = resolve(assetsRoot, callerSubpath, relPath);
79
80
  tried.push(fromCallerAbs);
@@ -179,6 +179,15 @@ const getLanguageModel = async (aiOptions, apiKey) => {
179
179
  ...otherOptions
180
180
  })(selectedModel);
181
181
  }
182
+ case AiProviders.MOONSHOTAI: {
183
+ const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
184
+ const { createMoonshotAI } = await loadModule("@ai-sdk/moonshotai");
185
+ return createMoonshotAI({
186
+ apiKey,
187
+ baseURL,
188
+ ...otherOptions
189
+ })(selectedModel);
190
+ }
182
191
  default: throw new Error(`Provider ${provider} not supported`);
183
192
  }
184
193
  };
@@ -1 +1 @@
1
- {"version":3,"file":"aiSdk.mjs","names":["generateTextFn"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type {\n createOpenAICompatible,\n OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\ntype LMStudioModel = Parameters<OpenAICompatibleProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\nexport type LMStudioProviderOptions = Parameters<\n typeof createOpenAICompatible\n>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | LMStudioModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({\n provider: AiProviders.LMSTUDIO | `${AiProviders.LMSTUDIO}`;\n } & LMStudioProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst isMaskedKey = (key?: string): boolean => !!key?.includes('*');\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n const apiKey =\n aiOptions?.apiKey && !isMaskedKey(aiOptions.apiKey)\n ? aiOptions.apiKey\n : undefined;\n\n if (accessType.includes('public')) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && apiKey) {\n return apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (\n isUserProvidedKey ||\n provider === AiProviders.OLLAMA ||\n provider === AiProviders.LMSTUDIO\n ) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n case AiProviders.LMSTUDIO: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAICompatible } = await loadModule<\n typeof import('@ai-sdk/openai-compatible')\n >('@ai-sdk/openai-compatible');\n\n const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: baseURL ?? 'http://localhost:1234/v1',\n ...otherOptions,\n });\n\n return lmstudio(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const mergeWithoutUndefined = (...sources: (AIOptions | undefined)[]) => {\n const result: Record<string, unknown> = { provider: DEFAULT_PROVIDER };\n for (const source of sources) {\n if (!source) continue;\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined) continue;\n if (key === 'apiKey' && isMaskedKey(value as string)) continue;\n result[key] = value;\n }\n }\n return result;\n };\n\n const aiOptions = mergeWithoutUndefined(\n defaultOptions,\n projectOptions,\n userOptions\n ) as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (\n !apiKey &&\n aiOptions.provider !== AiProviders.OLLAMA &&\n aiOptions.provider !== AiProviders.LMSTUDIO\n ) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;AA4CA,MAAM,mBAAmB,YAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AA4JpC,MAAM,eAAe,QAA0B,CAAC,CAAC,KAAK,SAAS,GAAG;AAElE,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;CACH,MAAM,SACJ,WAAW,UAAU,CAAC,YAAY,UAAU,MAAM,IAC9C,UAAU,SACV;CAEN,IAAI,WAAW,SAAS,QAAQ,GAC9B,OAAO,UAAU;CAGnB,IAAI,WAAW,SAAS,QAAQ,KAAK,QACnC,OAAO;CAGT,IAAI,WAAW,SAAS,iBAAiB,KAAK,iBAC5C,OAAO,UAAU;CAInB,IAAI,WAAW,SAAS,cAAc,KAAK,iBACzC,OAAO,UAAU;AAIrB;AAEA,MAAM,gBACJ,UACA,mBACA,cACU;CAEV,IACE,qBACA,aAAa,YAAY,UACzB,aAAa,YAAY,UACzB;EACA,IAAI,WACF,OAAO;EAIT,OAAO;CACT;CAIA,OAAO;AACT;AAEA,MAAM,mBAAmB,OACvB,WACA,WACG;CACH,MAAM,aAAa,OAAU,gBAAoC;EAC/D,IAAI;GACF,OAAQ,MAAM,OAAO;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,YAAY,UAEnC,MAAM,IAAI,MAAM,eAAe,UAAU,SAAS,YAAY;CAKhE,OAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,MAAM;EAI5D,aAAa,UAAU;EACvB,mBAAmB,UAAU;CAC/B;AACF"}
1
+ {"version":3,"file":"aiSdk.mjs","names":["generateTextFn"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createMoonshotAI, MoonshotAIProvider } from '@ai-sdk/moonshotai';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type {\n createOpenAICompatible,\n OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\ntype LMStudioModel = Parameters<OpenAICompatibleProvider>[0];\ntype MoonshotAIModel = Parameters<MoonshotAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\nexport type LMStudioProviderOptions = Parameters<\n typeof createOpenAICompatible\n>[0];\nexport type MoonshotAIProviderOptions = Parameters<typeof createMoonshotAI>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | LMStudioModel\n | MoonshotAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({\n provider: AiProviders.LMSTUDIO | `${AiProviders.LMSTUDIO}`;\n } & LMStudioProviderOptions)\n | ({\n provider: AiProviders.MOONSHOTAI | `${AiProviders.MOONSHOTAI}`;\n } & MoonshotAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst isMaskedKey = (key?: string): boolean => !!key?.includes('*');\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n const apiKey =\n aiOptions?.apiKey && !isMaskedKey(aiOptions.apiKey)\n ? aiOptions.apiKey\n : undefined;\n\n if (accessType.includes('public')) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && apiKey) {\n return apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (\n isUserProvidedKey ||\n provider === AiProviders.OLLAMA ||\n provider === AiProviders.LMSTUDIO\n ) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n case AiProviders.LMSTUDIO: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAICompatible } = await loadModule<\n typeof import('@ai-sdk/openai-compatible')\n >('@ai-sdk/openai-compatible');\n\n const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: baseURL ?? 'http://localhost:1234/v1',\n ...otherOptions,\n });\n\n return lmstudio(selectedModel as string);\n }\n\n case AiProviders.MOONSHOTAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMoonshotAI } =\n await loadModule<typeof import('@ai-sdk/moonshotai')>(\n '@ai-sdk/moonshotai'\n );\n\n const moonshotai = createMoonshotAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return moonshotai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const mergeWithoutUndefined = (...sources: (AIOptions | undefined)[]) => {\n const result: Record<string, unknown> = { provider: DEFAULT_PROVIDER };\n for (const source of sources) {\n if (!source) continue;\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined) continue;\n if (key === 'apiKey' && isMaskedKey(value as string)) continue;\n result[key] = value;\n }\n }\n return result;\n };\n\n const aiOptions = mergeWithoutUndefined(\n defaultOptions,\n projectOptions,\n userOptions\n ) as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (\n !apiKey &&\n aiOptions.provider !== AiProviders.OLLAMA &&\n aiOptions.provider !== AiProviders.LMSTUDIO\n ) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;AA6CA,MAAM,mBAAmB,YAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AAkKpC,MAAM,eAAe,QAA0B,CAAC,CAAC,KAAK,SAAS,GAAG;AAElE,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;CACH,MAAM,SACJ,WAAW,UAAU,CAAC,YAAY,UAAU,MAAM,IAC9C,UAAU,SACV;CAEN,IAAI,WAAW,SAAS,QAAQ,GAC9B,OAAO,UAAU;CAGnB,IAAI,WAAW,SAAS,QAAQ,KAAK,QACnC,OAAO;CAGT,IAAI,WAAW,SAAS,iBAAiB,KAAK,iBAC5C,OAAO,UAAU;CAInB,IAAI,WAAW,SAAS,cAAc,KAAK,iBACzC,OAAO,UAAU;AAIrB;AAEA,MAAM,gBACJ,UACA,mBACA,cACU;CAEV,IACE,qBACA,aAAa,YAAY,UACzB,aAAa,YAAY,UACzB;EACA,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AAU,iBAAiB;EACrE,KAAK,MAAM,UAAU,SAAS;GAC5B,IAAI,CAAC,QAAQ;GACb,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;IACjD,IAAI,UAAU,QAAW;IACzB,IAAI,QAAQ,YAAY,YAAY,KAAe,GAAG;IACtD,OAAO,OAAO;GAChB;EACF;EACA,OAAO;CACT;CAEA,MAAM,YAAY,sBAChB,gBACA,gBACA,WACF;CAEA,MAAM,SAAS,UAAU,YAAY,WAAW,eAAe;CAG/D,IACE,CAAC,UACD,UAAU,aAAa,YAAY,UACnC,UAAU,aAAa,YAAY,UAEnC,MAAM,IAAI,MAAM,eAAe,UAAU,SAAS,YAAY;CAKhE,OAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,MAAM;EAI5D,aAAa,UAAU;EACvB,mBAAmB,UAAU;CAC/B;AACF"}
@@ -90,8 +90,9 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
90
90
  ].join("\n")
91
91
  }]
92
92
  });
93
+ const cleanedText = text.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm, "$1").trim();
93
94
  return {
94
- fileContent: decode(text.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm, "$1").trim()),
95
+ fileContent: decode(cleanedText),
95
96
  tokenUsed: usage?.totalTokens ?? 0
96
97
  };
97
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["AIProvider"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,YAAW;CACrB,OAAO;AACT;;;;;;;AAQA,MAAM,w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EACb,CACF;CACF,CAAC;CAGD,MAAM,gBAAgB,YAAY,IAAI;CAGtC,OAAO;EACL,aAHuB,OAAO,MAAM,aAGR;EAC5B,WAAW,OAAO,eAAe;CACnC;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["AIProvider"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,YAAW;CACrB,OAAO;AACT;;;;;;;AAQA,MAAM,wBAAwB,WAC5B,GAAG,OAAO,IAAI,cAAc,QAAQ,cAAc;;;;;;;;AASpD,MAAM,yBAAyB,SAAwB;CACrD,IAAI,CAAC,QAAQ,KAAK,WAAW,GAC3B,OAAO;CAIT,OAAO;;EAEP,KAAK,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,aAAa,CAAC,CAAC,KAAK,MAAM;AAC5E;AAEA,MAAM,uBAAuB,SAAwC;CACnE,IAAI,SAAS,YACX,OAAO;CAGT,OAAO;AACT;AAEA,MAAM,aAAa,YAA+B;CAEhD,IAAI,OAAO,YAAY,UACrB,OAAO,EAAE,OAAO;CAIlB,IAAI,OAAO,YAAY,UACrB,OAAO,EAAE,OAAO;CAElB,IAAI,OAAO,YAAY,WACrB,OAAO,EAAE,QAAQ;CAInB,IAAI,MAAM,QAAQ,OAAO,GAAG;EAE1B,IAAI,QAAQ,WAAW,GACrB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC;EAG3B,OAAO,EAAE,MAAM,UAAU,QAAQ,EAAE,CAAC;CACtC;CAGA,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM;EACnD,MAAM,QAAsC,CAAC;EAC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ACA;KACA,eAAe;KACf,aAAa;KACb;KACA;KACA;IACF,CAAC,CAAC,KAAK,IAAI;GACb,CACF;EACF,CAAC;EAGD,MAAM,cAAc,KACjB,QAAQ,qCAAqC,IAAI,CAAC,CAClD,KAAK;EAMR,OAAO;GACL,aALkB,OAAO,WAKF;GACvB,WAAW,OAAO,eAAe;EACnC;CACF;CAMA,MAAM,kBAJY,UAAU,gBAII,KAAK;CAGrC,MAAM,EAAE,MAAM,UAAU,MAAM,aAAa;EACzC,GAAG;EAGH,QAAQ,kBAAkB,OAAO,OAAO,EAAE,OAAO,CAAC,IAAI;EACtD,QAAQ;EACR,UAAU,CACR;GACE,MAAM;GACN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,KAAK,IAAI;EACb,CACF;CACF,CAAC;CAGD,MAAM,gBAAgB,YAAY,IAAI;CAGtC,OAAO;EACL,aAHuB,OAAO,MAAM,aAGR;EAC5B,WAAW,OAAO,eAAe;CACnC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"extractJSON.mjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (!inString) {\n if (char === openChar) {\n depth++;\n } else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eAAwB,UAAqB;CACxD,MAAM,UAAU,MAAM,MAAM,MAAM;CAClC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,yCAAyC;CAEvE,MAAM,WAAW,QAAQ;CACzB,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,aAAa,MAAM,MAAM;CAE3C,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,UAAU,IAAI,MAAM,QAAQ,KAAK;EAC5C,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS;GACX,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAM;GACjB,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,WAAW,CAAC;GACZ;EACF;EAEA,IAAI,CAAC,UACH;OAAI,SAAS,UACX;QACK,IAAI,SAAS,WAAW;IAC7B;IACA,IAAI,UAAU,GAAG;KACf,MAAM,gBAAgB,MAAM,MAAM,UAAU,IAAI,CAAC;KACjD,IAAI;MACF,OAAO,KAAK,MAAM,aAAa;KACjC,SAAS,KAAK;MACZ,MAAM,IAAI,MAAM,yBAA0B,IAAc,SAAS;KACnE;IACF;GACF;;CAEJ;CAEA,MAAM,IAAI,MAAM,oDAAoD;AACtE"}
1
+ {"version":3,"file":"extractJSON.mjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (!inString) {\n if (char === openChar) {\n depth++;\n } else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eAAwB,UAAqB;CACxD,MAAM,UAAU,MAAM,MAAM,MAAM;CAClC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,yCAAyC;CAEvE,MAAM,WAAW,QAAQ;CACzB,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,aAAa,MAAM,MAAM;CAE3C,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,UAAU,IAAI,MAAM,QAAQ,KAAK;EAC5C,MAAM,OAAO,MAAM;EAEnB,IAAI,SAAS;GACX,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAM;GACjB,UAAU;GACV;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,WAAW,CAAC;GACZ;EACF;EAEA,IAAI,CAAC,UAAU;GACb,IAAI,SAAS,UACX;QACK,IAAI,SAAS,WAAW;IAC7B;IACA,IAAI,UAAU,GAAG;KACf,MAAM,gBAAgB,MAAM,MAAM,UAAU,IAAI,CAAC;KACjD,IAAI;MACF,OAAO,KAAK,MAAM,aAAa;KACjC,SAAS,KAAK;MACZ,MAAM,IAAI,MAAM,yBAA0B,IAAc,SAAS;KACnE;IACF;GACF;EACF;CACF;CAEA,MAAM,IAAI,MAAM,oDAAoD;AACtE"}
@@ -8,6 +8,7 @@ import { GoogleVertexProvider, createVertex } from "@ai-sdk/google-vertex";
8
8
  import { GroqProvider, createGroq } from "@ai-sdk/groq";
9
9
  import { HuggingFaceProvider, createHuggingFace } from "@ai-sdk/huggingface";
10
10
  import { MistralProvider, createMistral } from "@ai-sdk/mistral";
11
+ import { MoonshotAIProvider, createMoonshotAI } from "@ai-sdk/moonshotai";
11
12
  import { OpenAIProvider, createOpenAI } from "@ai-sdk/openai";
12
13
  import { OpenAICompatibleProvider, createOpenAICompatible } from "@ai-sdk/openai-compatible";
13
14
  import { TogetherAIProvider, createTogetherAI } from "@ai-sdk/togetherai";
@@ -29,6 +30,7 @@ type GroqModel = Parameters<GroqProvider>[0];
29
30
  type HuggingFaceModel = Parameters<HuggingFaceProvider>[0];
30
31
  type TogetherAIModel = Parameters<TogetherAIProvider>[0];
31
32
  type LMStudioModel = Parameters<OpenAICompatibleProvider>[0];
33
+ type MoonshotAIModel = Parameters<MoonshotAIProvider>[0];
32
34
  type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];
33
35
  type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];
34
36
  type MistralProviderOptions = Parameters<typeof createMistral>[0];
@@ -43,12 +45,13 @@ type HuggingFaceProviderOptions = Parameters<typeof createHuggingFace>[0];
43
45
  type AmazonBedrockProviderOptions = Parameters<typeof createAmazonBedrock>[0];
44
46
  type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];
45
47
  type LMStudioProviderOptions = Parameters<typeof createOpenAICompatible>[0];
48
+ type MoonshotAIProviderOptions = Parameters<typeof createMoonshotAI>[0];
46
49
  type SystemMessage = string | SystemModelMessage | SystemModelMessage[] | undefined;
47
50
  type Messages = (UserModelMessage | AssistantModelMessage | ToolModelMessage)[];
48
51
  /**
49
52
  * Supported AI models
50
53
  */
51
- type Model = AnthropicModel | DeepSeekModel | MistralModel | OpenAIModel | OpenRouterModel | GoogleModel | VertexModel | AlibabaModel | AmazonBedrockModel | FireworksModel | GroqModel | HuggingFaceModel | TogetherAIModel | LMStudioModel | (string & {});
54
+ type Model = AnthropicModel | DeepSeekModel | MistralModel | OpenAIModel | OpenRouterModel | GoogleModel | VertexModel | AlibabaModel | AmazonBedrockModel | FireworksModel | GroqModel | HuggingFaceModel | TogetherAIModel | LMStudioModel | MoonshotAIModel | (string & {});
52
55
  /**
53
56
  * Supported AI SDK providers
54
57
  */
@@ -97,6 +100,8 @@ type AIOptions = (({
97
100
  } & TogetherAIProviderOptions) | ({
98
101
  provider: AiProviders.LMSTUDIO | `${AiProviders.LMSTUDIO}`;
99
102
  } & LMStudioProviderOptions) | ({
103
+ provider: AiProviders.MOONSHOTAI | `${AiProviders.MOONSHOTAI}`;
104
+ } & MoonshotAIProviderOptions) | ({
100
105
  provider?: undefined;
101
106
  } & OpenAIProviderOptions)) & CommonAIOptions;
102
107
  type ChatCompletionRequestMessage = {
@@ -135,5 +140,5 @@ declare const checkAISDKAccess: (aiConfig: AIConfig) => Promise<{
135
140
  */
136
141
  declare const getAIConfig: (options: AIConfigOptions, isAuthenticated?: boolean) => Promise<AIConfig>;
137
142
  //#endregion
138
- export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig };
143
+ export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, MoonshotAIProviderOptions, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig };
139
144
  //# sourceMappingURL=aiSdk.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"aiSdk.d.ts","names":[],"sources":["../../src/aiSdk.ts"],"mappings":";;;;;;;;;;;;;;;;;KAkDK,iBAAiB,WAAW;KAC5B,gBAAgB,WAAW;KAC3B,eAAe,WAAW;KAC1B,cAAc,WAAW;KACzB,kBAAkB,WAAW;KAC7B,cAAc,WAAW;KACzB,cAAc,WAAW;KACzB,eAAe,WAAW;KAC1B,qBAAqB,WAAW;KAChC,iBAAiB,WAAW;KAC5B,YAAY,WAAW;KACvB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AEF,UAAU,YAAY,aAAa,YAAY;IAC7C;EAEF,UAAU,YAAY,cAAc,YAAY;IAC9C;EAEF,UAAU,YAAY,YAAY,YAAY;IAC5C;EAEF,UACI,YAAY,wBACT,YAAY;IACjB;EAEF,UAAU,YAAY,YAAY,YAAY;IAC5C;EAEF,UAAU,YAAY,gBAAgB,YAAY;IAChD;EAEF,UAAU,YAAY,aAAa,YAAY;IAC7C;EAEF,UAAU,YAAY,eAAe,YAAY;IAC/C;EAEF,UAAU,YAAY,UAAU,YAAY;IAC1C;EAEF,UAAU,YAAY,iBAAiB,YAAY;IACjD;EAEF,UAAU,YAAY,aAAa,YAAY;IAC7C;EAEF,UAAU,YAAY,kBAAkB,YAAY;IAClD;EAEF,UAAU,YAAY,gBAAgB,YAAY;IAChD;EAEF,UAAU,YAAY,cAAc,YAAY;IAC9C;EAEF,UAAU,YAAY,gBAAgB,YAAY;IAChD;EACD;IAAyB,0BAE9B;KAGU;EACV;EACA;EACA,YAAY;;KAGT;KAofO,WAAW,KAAK,kBAAkB;EAC5C,kBAAkB;EAClB;EACA;;KAGU;EACV,cAAc;EACd,iBAAiB;EACjB,iBAAiB;EACjB,aAAa;;;;;;;;cASF,mBAAgB,UACjB,aACT;EAAU;EAAsB;;;;;;;;;cAyBtB,cAAW,SACb,iBAAe,8BAEvB,QAAQ"}
@@ -1,4 +1,4 @@
1
- import { AIConfig, AIConfigOptions, AIOptions, AIProvider as AiProviders, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig } from "./aiSdk.js";
1
+ import { AIConfig, AIConfigOptions, AIOptions, AIProvider as AiProviders, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, MoonshotAIProviderOptions, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig } from "./aiSdk.js";
2
2
  import { AuditDictionaryMetadataOptions, AuditFileResultData, auditDictionaryMetadata } from "./auditDictionaryMetadata/index.js";
3
3
  import { CustomQueryOptions, CustomQueryResultData, customQuery } from "./customQuery.js";
4
4
  import { TranslateJSONOptions, TranslateJSONResultData, translateJSON } from "./translateJSON/index.js";
@@ -22,8 +22,9 @@ declare module '@intlayer/types/config' {
22
22
  bedrock: AmazonBedrockProviderOptions;
23
23
  togetherai: TogetherAIProviderOptions;
24
24
  lmstudio: LMStudioProviderOptions;
25
+ moonshotai: MoonshotAIProviderOptions;
25
26
  }
26
27
  }
27
28
  //#endregion
28
- export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, type AuditDictionaryMetadataOptions, type AuditFileResultData, ChatCompletionRequestMessage, type CustomQueryOptions, type CustomQueryResultData, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, type Tool, type TranslateJSONOptions, type TranslateJSONResultData, VertexProviderOptions, auditDictionaryMetadata, checkAISDKAccess, customQuery, extractJson, generateText, getAIConfig, jsonSchema, stepCountIs, streamText, tool, translateJSON };
29
+ export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, type AuditDictionaryMetadataOptions, type AuditFileResultData, ChatCompletionRequestMessage, type CustomQueryOptions, type CustomQueryResultData, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, LMStudioProviderOptions, Messages, MistralProviderOptions, Model, MoonshotAIProviderOptions, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, type Tool, type TranslateJSONOptions, type TranslateJSONResultData, VertexProviderOptions, auditDictionaryMetadata, checkAISDKAccess, customQuery, extractJson, generateText, getAIConfig, jsonSchema, stepCountIs, streamText, tool, translateJSON };
29
30
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;YA6CY;IACR,QAAQ;IACR,WAAW;IACX,SAAS;IACT,UAAU;IACV,QAAQ;IACR,cAAc;IACd,QAAQ;IACR,YAAY;IACZ,SAAS;IACT,WAAW;IACX,MAAM;IACN,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;YA8CY;IACR,QAAQ;IACR,WAAW;IACX,SAAS;IACT,UAAU;IACV,QAAQ;IACR,cAAc;IACd,QAAQ;IACR,YAAY;IACZ,SAAS;IACT,WAAW;IACX,MAAM;IACN,aAAa;IACb,SAAS;IACT,YAAY;IACZ,UAAU;IACV,YAAY"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/ai",
3
- "version": "9.2.0",
3
+ "version": "9.3.1",
4
4
  "private": false,
5
5
  "description": "SDK that provides AI capabilities for Intlayer applications",
6
6
  "keywords": [
@@ -72,30 +72,31 @@
72
72
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
73
73
  },
74
74
  "dependencies": {
75
- "@ai-sdk/anthropic": "4.0.30",
76
- "@ai-sdk/openai": "4.0.30",
77
- "@intlayer/api": "9.2.0",
78
- "@intlayer/config": "9.2.0",
79
- "@intlayer/core": "9.2.0",
80
- "@intlayer/types": "9.2.0",
75
+ "@ai-sdk/anthropic": "4.0.38",
76
+ "@ai-sdk/openai": "4.0.40",
77
+ "@intlayer/api": "9.3.1",
78
+ "@intlayer/config": "9.3.1",
79
+ "@intlayer/core": "9.3.1",
80
+ "@intlayer/types": "9.3.1",
81
81
  "@toon-format/toon": "4.1.1",
82
- "ai": "7.0.52",
82
+ "ai": "7.0.62",
83
83
  "zod": "4.4.3"
84
84
  },
85
85
  "devDependencies": {
86
- "@ai-sdk/alibaba": "2.0.25",
87
- "@ai-sdk/amazon-bedrock": "5.0.43",
88
- "@ai-sdk/deepseek": "3.0.22",
89
- "@ai-sdk/fireworks": "3.0.25",
90
- "@ai-sdk/google": "4.0.34",
91
- "@ai-sdk/google-vertex": "5.0.41",
92
- "@ai-sdk/groq": "4.0.22",
93
- "@ai-sdk/huggingface": "2.0.23",
94
- "@ai-sdk/mistral": "4.0.23",
95
- "@ai-sdk/openai-compatible": "3.0.23",
96
- "@ai-sdk/togetherai": "3.0.24",
86
+ "@ai-sdk/alibaba": "2.0.31",
87
+ "@ai-sdk/amazon-bedrock": "5.0.54",
88
+ "@ai-sdk/deepseek": "3.0.28",
89
+ "@ai-sdk/fireworks": "3.0.32",
90
+ "@ai-sdk/google": "4.0.42",
91
+ "@ai-sdk/google-vertex": "5.0.51",
92
+ "@ai-sdk/groq": "4.0.28",
93
+ "@ai-sdk/huggingface": "2.0.30",
94
+ "@ai-sdk/mistral": "4.0.29",
95
+ "@ai-sdk/moonshotai": "3.0.34",
96
+ "@ai-sdk/openai-compatible": "3.0.30",
97
+ "@ai-sdk/togetherai": "3.0.31",
97
98
  "@openrouter/ai-sdk-provider": "3.0.0",
98
- "@types/node": "26.1.2",
99
+ "@types/node": "26.2.0",
99
100
  "@utils/ts-config": "1.0.4",
100
101
  "@utils/ts-config-types": "1.0.4",
101
102
  "@utils/tsdown-config": "1.0.4",
@@ -114,6 +115,7 @@
114
115
  "@ai-sdk/groq": "<=3.0.0",
115
116
  "@ai-sdk/huggingface": "<=1.0.0",
116
117
  "@ai-sdk/mistral": "<=3.0.0",
118
+ "@ai-sdk/moonshotai": "<=2.0.0",
117
119
  "@ai-sdk/openai-compatible": "<=2.0.0",
118
120
  "@ai-sdk/togetherai": "<=2.0.0",
119
121
  "@openrouter/ai-sdk-provider": "<=2.0.0"
@@ -146,6 +148,9 @@
146
148
  "@ai-sdk/mistral": {
147
149
  "optional": true
148
150
  },
151
+ "@ai-sdk/moonshotai": {
152
+ "optional": true
153
+ },
149
154
  "@ai-sdk/openai-compatible": {
150
155
  "optional": true
151
156
  },