i18n-works 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{t as e}from"../run-LTvFUSou.js";process.exitCode=await e(process.argv.slice(2));export{};
2
+ import{t as e}from"../run-MMec39Hn.js";process.exitCode=await e(process.argv.slice(2));export{};
package/dist/cli/index.js CHANGED
@@ -1 +1 @@
1
- export{s as DEFAULT_CATALOG_DIRECTORY,n as browse,r as listLanguages,o as prune,t as runCli,a as stats,i as translate}from"../run-LTvFUSou.js";
1
+ export{s as DEFAULT_CATALOG_DIRECTORY,n as browse,r as listLanguages,o as prune,t as runCli,a as stats,i as translate}from"../run-MMec39Hn.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{C as e,D as t,E as n,O as r,S as i,T as a,b as o,f as s,g as c,h as l,k as u,m as d,n as f,p,t as ee,v as m,w as h,x as g,y as _}from"./sync-CG2Hl5sp.js";import{a as v,i as y,o as b}from"./icu-Cui2dM71.js";import x from"node:path";import{i as te,n as ne,r as S,t as re}from"./pick-Bpdsmz-0.js";function C(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function w(e,t,n=!1){let r=Object.entries(e).map(([e,t])=>` ${C(e)}: () => import(${C(t)}).then(m => unwrapDefault(m).messages)`).join(`,
1
+ import{C as e,D as t,E as n,O as r,S as i,T as a,b as o,f as s,g as c,h as l,k as u,m as d,n as f,p,t as ee,v as m,w as h,x as g,y as _}from"./sync-CXMq5LNq.js";import{a as v,i as y,o as b}from"./icu-Cui2dM71.js";import x from"node:path";import{i as te,n as ne,r as S,t as re}from"./pick-Bpdsmz-0.js";function C(e){return JSON.stringify(e).replace(/[<>&\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function w(e,t,n=!1){let r=Object.entries(e).map(([e,t])=>` ${C(e)}: () => import(${C(t)}).then(m => unwrapDefault(m).messages)`).join(`,
2
2
  `),i=[`import { formatAutoPluralMessage, formatMessage } from ${C(m)};`,`const unwrapDefault = ${te.toString()};`,`const loaders = {\n${r}\n};`,`const sourceLocale = ${C(t)};`,`const resolveLocale = ${S.toString()};`,`const createLocaleLoader = ${ne.toString()};`,`const loadLocale = createLocaleLoader(loaders, sourceLocale);`,`const listeners = new Set();`,`let currentLocale = sourceLocale;`,`let messages = {};`,`let version = 0;`,`let latestRequest = 0;`,`export const locales = Object.keys(loaders);`,`export function getLocale() { return currentLocale; }`,`export function getVersion() { return version; }`,`export function resolveSupported(preferred) { return resolveLocale(preferred, locales, sourceLocale); }`,`async function applyLocale(locale) {`,` const request = ++latestRequest;`,` let selected = loaders[locale] ? locale : sourceLocale;`,` let catalog;`,` try {`,` catalog = await loadLocale(selected);`,` } catch (error) {`,` console.warn('${y}: could not load "' + selected + '", falling back to "' + sourceLocale + '".', error);`,` selected = sourceLocale;`,` try {`,` catalog = await loadLocale(selected);`,` } catch (fallbackError) {`,` // Keep the current locale and messages so the UI stays consistent. Texts without a catalogue show their source.`,` console.error('${y}: could not load the source catalogue "' + sourceLocale + '".', fallbackError);`,` return;`,` }`,` }`,` // A slower earlier request must not overwrite the locale the user picked last.`,` if (request !== latestRequest) return;`,` messages = catalog;`,` currentLocale = selected;`,` notify();`,`}`,`function notify() {`,` version++;`,` listeners.forEach(fn => fn(currentLocale));`,`}`,`export function subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; }`,`export function lookup(id, source, values) {`,` const text = messages[id] ?? source;`,` return values === undefined ? text : formatMessage(text, currentLocale, values);`,`}`,`export function lookupAutoPlural(id, source, values) {`,` const text = messages[id] ?? source;`,` return values === undefined ? text : formatAutoPluralMessage(text, currentLocale, values);`,`}`,`// Only literal t("...") and tauto("...") calls are translated at build time. Any other call returns its argument unchanged, formatted with values when given.`,`export function t(source, values) {`,` return values === undefined ? source : formatMessage(source, currentLocale, values);`,`}`,`export function tauto(source, valuesOrHint) {`,` const values = typeof valuesOrHint === "string" ? undefined : valuesOrHint;`,` return values === undefined ? source : formatMessage(source, currentLocale, values);`,`}`,`export function tt(source, values, hint) {`,` return values === undefined ? source : formatAutoPluralMessage(source, currentLocale, values);`,`}`],a=n?[`const localeStorageKey = ${C(`i18n-works:locale`)};`,`function storedLocale() {`,` try { return localStorage.getItem(localeStorageKey); } catch (error) { return null; }`,`}`,`function startupLocale() {`,` const stored = storedLocale();`,` return locales.includes(stored) ? stored : resolveSupported(navigator.languages);`,`}`,`// Module-scope lookups run while importers evaluate, so the chosen locale must be loaded before this module finishes.`,`await applyLocale(startupLocale());`,`// Module-scope messages were translated at import time, so a switch stores the choice and reloads the page.`,`export async function setLocale(locale) {`,` const selected = locales.includes(locale) ? locale : sourceLocale;`,` if (selected === currentLocale) return;`,` try {`,` localStorage.setItem(localeStorageKey, selected);`,` } catch (error) {`,` console.warn('${y}: could not save the locale, so module-scope texts keep their current language.', error);`,` return applyLocale(selected);`,` }`,` location.reload();`,`}`]:[`export { applyLocale as setLocale };`],o=[`// Dev server pushes the catalogues that changed after a source change; no page reload is needed.`,`if (import.meta.hot) {`,` import.meta.hot.on("i18n-works:update", data => {`,` for (const [locale, catalog] of Object.entries(data.catalogs)) loadLocale.prime(locale, catalog);`,` if (!data.catalogs[currentLocale]) return;`,` messages = data.catalogs[currentLocale];`,` notify();`,` });`,`}`];return[...i,...a,...o].join(`
3
3
  `)+`
4
- `}const T=`\0${_}`;function E(t){let n,r,a=``,s,l,u=!1;function d(){if(n.delivery!==`runtime`)return!1;for(let e of n.state.fileMessages.values())if(e.some(e=>e.component===`<module>`))return!0;return!1}function p(e){e.length&&s?.ws.send({type:`custom`,event:`i18n-works:update`,data:{catalogs:Object.fromEntries(e.map(e=>[e,n.state.catalogs.get(e)]))}})}function m(){if(!s||d()===u)return;let e=s.moduleGraph.getModuleById(T);e&&s.moduleGraph.invalidateModule(e),s.ws.send({type:`full-reload`})}async function g(e){try{p(await n.runSync(f(r.logger),e)),m()}catch(e){r.logger.error(b(`re-translation failed: ${e.message}`))}}function y(){clearTimeout(l),l=setTimeout(()=>void g(),150)}return{name:`i18n-works`,enforce:`pre`,config(r,i){let o=x.resolve(r.root??process.cwd()),s=t=>{h(t),n=new ee(t),a=e(o)},c=t(o,i);if(c instanceof Promise)return c.then(s);s(c)},configResolved(e){r=e,n.attach(e);let t=n.selectedLocale();if(t!==n.sourceLocale&&!n.locales.includes(t))throw v(`locale "${t}" is not one of the configured locales (${n.locales.join(`, `)}). Add it to locales in ${i}, or choose one of those locales for the locale option or the I18N_WORKS_LOCALE variable.`)},resolveId(e){if(e===`virtual:i18n-works`)return`\0${_}`},load(e){if(e===T)return u=d(),w(n.state.catalogFiles,n.sourceLocale,u)},configureServer(e){s=e,e.watcher.on(`add`,e=>{n.isSourceCandidate(e)&&y()}),e.watcher.on(`unlink`,e=>{n.state.fileMessages.has(e)&&y()}),e.watcher.on(`change`,t=>{x.resolve(t)===a&&e.restart().catch(e=>{let t=e instanceof Error?e.message:String(e);r.logger.error(b(`could not restart after ${i} changed: ${t}`))})})},closeBundle(){clearTimeout(l)},async buildStart(){await n.sync({info:e=>this.info(e),warn:e=>this.warn(e),error:e=>this.error(e)})},async transform(e,t){let i=t.split(`?`)[0];if(!n.state.fileMessages.has(i))return null;let a=c(e);a!==n.state.hashOf(i)&&await n.runSync(f(r.logger),i);let s=n.state.fileMessages.get(i);if(!s||a!==n.state.hashOf(i))return n.state.warnedFiles.has(i)||(n.state.warnedFiles.add(i),this.warn(b(`${i} changed while it was being indexed; its messages are left untranslated.`))),null;if(s.length===0)return null;let l=n.isServing()?n.sourceLocale:n.selectedLocale(),u=n.isServing()||!!r.build.sourcemap,d=o(e,i,s,l,n.state.catalogs.get(l)??{},n.delivery===`runtime`,n.sourceLocale,u);return{code:d.code,map:d.map}},async handleHotUpdate({file:e}){if(e.startsWith(n.localesDir()+x.sep))return[];n.state.fileMessages.has(e)&&await g(e)}}}const D=6e4;var O=class extends Error{retryable;retryAfterMs;constructor(e,t,n){super(e),this.retryable=t,this.retryAfterMs=n}};function ie(e,t=Date.now()){if(e===null||e===``)return;let n=Number(e);if(Number.isFinite(n))return Math.min(Math.max(n,0)*1e3,D);let r=Date.parse(e);if(!Number.isNaN(r))return Math.min(Math.max(r-t,0),D)}const ae=e=>new Promise(t=>setTimeout(t,e));function k(e){return`You are a professional software localization engine. Translate UI messages from ${e.sourceLocale} to ${e.targetLocale}. Preserve placeholders exactly. Some messages use ICU MessageFormat, such as {name}, {count, plural, one {# file} other {# files}} or {gender, select, ...}. Keep argument names, the keywords (one, other, select, plural, ...) and the # symbol unchanged, translate only the text inside the branches, and write the plural branches the target language needs. Messages marked "autoPlural" are natural-language count templates: convert their source to valid ICU plural syntax using the count argument, include language-appropriate categories (zero, one, two, few, many, other as needed), and include an explicit =0 branch when natural UI wording is different. A "hint" on an autoPlural message gives free-form source-author guidance for special count-dependent wording or thresholds; apply it naturally in the target language, using exact =N branches when a hint identifies specific counts and normal plural categories for ranges. Preserve {count} semantics and translate only the words inside branches. Respect context and UI conventions. When the source and target locales are the same, the source text is only a seed: rewrite it to apply the hint, keeping its placeholders. Keep the rewrite's length proportional to the seed: a one-word seed gets back one to three words, and a longer seed gets a proportionally longer rewrite, never a paragraph. A "hint" on a message without autoPlural is free-form author context, such as tone or audience; follow it in the wording while keeping every placeholder unchanged. Return ONLY a JSON object mapping message IDs to translated strings. Do not translate product names or code.`}function A(e){return JSON.stringify(e.map(e=>({id:e.id,text:e.source,context:e.context,...e.autoPlural===!0?{autoPlural:!0}:{},...e.hint!==void 0&&e.hint.length>0?{hint:e.hint}:{}})))}async function j(e){let t=e.status===408||e.status===409||e.status===429||e.status>=500;return await e.body?.cancel().catch(()=>void 0),new O(`Translation API failed (${e.status})`,t,ie(e.headers.get(`retry-after`)))}var M=class{options;slots;constructor(e){this.options=e,this.slots=new s(e.concurrency??4)}async translate(e){let t=Math.max(1,this.options.batchSize??40),n=[];for(let r=0;r<e.messages.length;r+=t)n.push(e.messages.slice(r,r+t));let r=await Promise.allSettled(n.map(t=>this.slots.run(()=>this.translateBatch({...e,messages:t})))),i={},a=[],o=0,s=0;if(r.forEach((e,t)=>{e.status===`fulfilled`?(s++,Object.assign(i,e.value)):(a.push(e.reason),o+=n[t].length)}),!a.length)return i;throw s?new l(`${o} messages failed to translate: ${a[0].message}`,i,o):a[0]}async translateBatch(e){let t=this.options.maxRetries??2,n=this.options.retryDelayMs??500;for(let r=0;;r++)try{return await this.request(e)}catch(e){if(e instanceof O&&!e.retryable||r>=t)throw e;let i=e instanceof O?e.retryAfterMs:void 0;await ae(i??n*2**r*(.5+Math.random()/2))}}async post(e,t,n){let r=await fetch(e,{method:`POST`,signal:AbortSignal.timeout(this.options.timeoutMs??6e4),headers:{...t,"content-type":`application/json`},body:JSON.stringify(n)});if(!r.ok)throw await j(r);return r.json()}async complete(e,t,n,r,i,a,o){let s=u(r,await this.post(e,t,n)),c=this.toCatalog(s.ok?i(s.value):void 0,a.messages);return a.onUsage?.({provider:o.provider,model:o.model,ids:a.messages.map(e=>e.id),...s.ok?o.tokens(s.value):{}}),c}toCatalog(e,t){let n=e?.trim().replace(/^```(?:json)?\s*|\s*```$/g,``);if(n===void 0||n===``)throw new O(`Translation provider returned no content`,!0);let i;try{i=JSON.parse(n)}catch{throw new O(`Translation provider returned invalid JSON`,!0)}let a=u(r,i);if(!a.ok)throw new O(`Translation provider returned a non-object`,!0);let o=new Set(t.map(e=>e.id)),s={};for(let[e,t]of Object.entries(a.value))o.has(e)&&typeof t==`string`&&t.trim()&&(s[e]=t);return s}};const N=`https://api.openai.com/v1`;var P=class extends M{async request(e){let{apiKey:t,model:r,baseURL:i=N}=this.options;return this.complete(`${i}/chat/completions`,t!==void 0&&t!==``?{Authorization:`Bearer ${t}`}:{},{model:r,temperature:0,response_format:{type:`json_object`},messages:[{role:`system`,content:k(e)},{role:`user`,content:A(e.messages)}]},n,e=>e.choices[0].message.content??void 0,e,{provider:i===N?`openai`:`openai-compatible`,model:r,tokens:e=>({inputTokens:e.usage?.prompt_tokens??void 0,outputTokens:e.usage?.completion_tokens??void 0})})}},F=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://api.anthropic.com/v1`}/messages`,{"x-api-key":this.options.apiKey,"anthropic-version":`2023-06-01`},{model:this.options.model,max_tokens:this.options.maxTokens??8192,system:k(e),messages:[{role:`user`,content:A(e.messages)}]},a,e=>e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),e,{provider:`anthropic`,model:this.options.model,tokens:e=>({inputTokens:e.usage?.input_tokens??void 0,outputTokens:e.usage?.output_tokens??void 0})})}},I=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://generativelanguage.googleapis.com/v1beta`}/models/${encodeURIComponent(this.options.model)}:generateContent`,{"x-goog-api-key":this.options.apiKey},{systemInstruction:{parts:[{text:k(e)}]},contents:[{role:`user`,parts:[{text:A(e.messages)}]}],generationConfig:{responseMimeType:`application/json`,maxOutputTokens:this.options.maxOutputTokens??8192}},t,e=>(e.candidates[0]?.content?.parts??[]).map(e=>e.text??``).join(``),e,{provider:`gemini`,model:this.options.model,tokens:e=>({inputTokens:e.usageMetadata?.promptTokenCount??void 0,outputTokens:e.usageMetadata?.candidatesTokenCount??void 0})})}};let oe=/* @__PURE__ */ function(e){return e.Anthropic=`anthropic`,e.Gemini=`gemini`,e.OpenAI=`openai`,e.Mistral=`mistral`,e.Groq=`groq`,e.DeepSeek=`deepseek`,e.OpenRouter=`openrouter`,e.XAI=`xai`,e.Cerebras=`cerebras`,e.Perplexity=`perplexity`,e.Together=`together`,e.Fireworks=`fireworks`,e.HuggingFace=`huggingface`,e.DeepInfra=`deepinfra`,e.SambaNova=`sambanova`,e.Moonshot=`moonshot`,e}({}),se=/* @__PURE__ */ function(e){return e.Ollama=`ollama`,e.LMStudio=`lmstudio`,e.LlamaCpp=`llamacpp`,e.VLLM=`vllm`,e.LocalAI=`localai`,e.DockerModelRunner=`dockermodelrunner`,e}({});const L={openai:{model:`gpt-4.1-mini`},mistral:{baseURL:`https://api.mistral.ai/v1`,model:`mistral-small-latest`},groq:{baseURL:`https://api.groq.com/openai/v1`,model:`llama-3.3-70b-versatile`},deepseek:{baseURL:`https://api.deepseek.com/v1`,model:`deepseek-chat`},openrouter:{baseURL:`https://openrouter.ai/api/v1`,model:`openai/gpt-4.1-mini`},xai:{baseURL:`https://api.x.ai/v1`,model:`grok-3-mini`},cerebras:{baseURL:`https://api.cerebras.ai/v1`,model:`llama-3.3-70b`},perplexity:{baseURL:`https://api.perplexity.ai`,model:`sonar`},together:{baseURL:`https://api.together.xyz/v1`,model:`meta-llama/Llama-3.3-70B-Instruct-Turbo`},fireworks:{baseURL:`https://api.fireworks.ai/inference/v1`,model:`accounts/fireworks/models/llama-v3p3-70b-instruct`},huggingface:{baseURL:`https://router.huggingface.co/v1`,model:`meta-llama/Llama-3.3-70B-Instruct`},deepinfra:{baseURL:`https://api.deepinfra.com/v1/openai`,model:`meta-llama/Meta-Llama-3.1-70B-Instruct`},sambanova:{baseURL:`https://api.sambanova.ai/v1`,model:`Meta-Llama-3.3-70B-Instruct`},moonshot:{baseURL:`https://api.moonshot.ai/v1`,model:`moonshot-v1-8k`}},ce={ollama:`http://localhost:11434/v1`,lmstudio:`http://localhost:1234/v1`,llamacpp:`http://localhost:8080/v1`,vllm:`http://localhost:8000/v1`,localai:`http://localhost:8080/v1`,dockermodelrunner:`http://localhost:12434/engines/v1`},R=e=>(t,n)=>new P({apiKey:t,baseURL:L[e].baseURL,model:n??L[e].model}),z={anthropic:(e,t)=>new F({apiKey:e,model:t??`claude-haiku-5-5`}),gemini:(e,t)=>new I({apiKey:e,model:t??`gemini-3.5-flash-lite`}),openai:R(`openai`),mistral:R(`mistral`),groq:R(`groq`),deepseek:R(`deepseek`),openrouter:R(`openrouter`),xai:R(`xai`),cerebras:R(`cerebras`),perplexity:R(`perplexity`),together:R(`together`),fireworks:R(`fireworks`),huggingface:R(`huggingface`),deepinfra:R(`deepinfra`),sambanova:R(`sambanova`),moonshot:R(`moonshot`)};function B(e,t,n){return t!==void 0&&t!==``?z[e](t,n):void 0}function V(e,t,n){if(t!==void 0&&t!==``)return new P({baseURL:n??ce[e],model:t})}function H(e,t){return B(e,t.apiKey,t.model)}function U(e,t){return V(e,t.model,t.baseURL)}const W=[`bg`,`cs`,`da`,`de`,`el`,`es`,`et`,`fi`,`fr`,`ga`,`hr`,`hu`,`it`,`lt`,`lv`,`mt`,`nl`,`pl`,`pt`,`ro`,`sk`,`sl`,`sv`],le=[`da`,`fi`,`is`,`no`,`sv`],ue=[`et`,`lv`,`lt`],de=[`bg`,`bs`,`el`,`hr`,`mk`,`ro`,`sq`,`sr`,`sl`],fe=[`nl`,`fr`,`lb`],pe=[.../* @__PURE__ */ new Set([...W,`no`,`is`,`sq`,`bs`,`mk`,`sr`,`uk`,`ru`,`be`,`ca`])],G=[`zh`,`ja`,`ko`,`mn`],K=[`hi`,`bn`,`ur`,`pa`,`ta`,`te`,`mr`,`gu`,`kn`,`ml`,`ne`,`si`],q=[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`],J=[`kk`,`ky`,`tg`,`tk`,`uz`],Y=[`hy`,`az`,`ka`],me=[.../* @__PURE__ */ new Set([...G,...K,...q,...J,...Y])],he=[`ar`,`fa`,`he`,`tr`,`ku`],X=[`ar`,`fr`,`pt`,`sw`,`am`,`ha`,`yo`,`ig`,`zu`,`xh`,`af`,`so`,`rw`,`wo`],Z=[`en`,`fr`,`es`],Q=[`es`,`en`,`fr`,`ht`,`nl`],$=[`es`,`pt`,`qu`,`gn`,`ay`],ge={EU:W,EUROPE:pe,NORDIC:le,BALTIC:ue,BALKANS:de,BENELUX:fe,EAST_ASIA:G,SOUTH_ASIA:K,SOUTHEAST_ASIA:q,CENTRAL_ASIA:J,CAUCASUS:Y,ASIA:me,MIDDLE_EAST:he,AFRICA:X,NORTH_AMERICA:Z,CENTRAL_AMERICA_CARIBBEAN:Q,SOUTH_AMERICA:$,AMERICAS:[.../* @__PURE__ */ new Set([...Z,...Q,...$])],OCEANIA:[`en`,`mi`,`sm`,`to`],ASEAN:[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`,`en`],MERCOSUR:[`es`,`pt`,`gn`],GCC:[`ar`,`en`],CIS:[`ru`,`be`,`hy`,`az`,`kk`,`ky`,`tg`,`uz`],G7:[`en`,`fr`,`de`,`it`,`ja`],FRANCOPHONE:[`fr`,`ht`,`wo`,`ln`,`rw`],WORLDWIDE_POPULAR:[`en`,`zh`,`hi`,`es`,`ar`,`bn`,`pt`,`ru`,`ja`,`de`,`fr`,`ko`,`it`,`tr`,`vi`,`id`,`ur`]};function _e(...e){if(e.length>0)throw v(`i18nWorks() no longer takes options. Move them to ${i} as the default export, then call i18nWorks() with no arguments in vite.config.`);return E(g)}export{F as AnthropicProvider,p as FallbackProvider,I as GeminiProvider,oe as HostedService,se as LocalService,P as OpenAICompatibleProvider,l as PartialTranslationError,_e as default,B as hosted,H as hostedFromEnv,V as local,U as localFromEnv,ge as locales,d as resolveProvider,re as tpick};
4
+ `}const T=`\0${_}`;function E(t){let n,r,a=``,s,l,u=!1;function d(){if(n.delivery!==`runtime`)return!1;for(let e of n.state.fileMessages.values())if(e.some(e=>e.component===`<module>`))return!0;return!1}function p(e){e.length&&s?.ws.send({type:`custom`,event:`i18n-works:update`,data:{catalogs:Object.fromEntries(e.map(e=>[e,n.state.catalogs.get(e)]))}})}function m(){if(!s||d()===u)return;let e=s.moduleGraph.getModuleById(T);e&&s.moduleGraph.invalidateModule(e),s.ws.send({type:`full-reload`})}async function g(e){try{p(await n.runSync(f(r.logger),e)),m()}catch(e){r.logger.error(b(`re-translation failed: ${e.message}`))}}function y(){clearTimeout(l),l=setTimeout(()=>void g(),150)}return{name:`i18n-works`,enforce:`pre`,config(r,i){let o=x.resolve(r.root??process.cwd()),s=t=>{h(t),n=new ee(t),a=e(o)},c=t(o,i);if(c instanceof Promise)return c.then(s);s(c)},configResolved(e){r=e,n.attach(e);let t=n.selectedLocale();if(t!==n.sourceLocale&&!n.locales.includes(t))throw v(`locale "${t}" is not one of the configured locales (${n.locales.join(`, `)}). Add it to locales in ${i}, or choose one of those locales for the locale option or the I18N_WORKS_LOCALE variable.`)},resolveId(e){if(e===`virtual:i18n-works`)return`\0${_}`},load(e){if(e===T)return u=d(),w(n.state.catalogFiles,n.sourceLocale,u)},configureServer(e){s=e,e.watcher.on(`add`,e=>{n.isSourceCandidate(e)&&y()}),e.watcher.on(`unlink`,e=>{n.state.fileMessages.has(e)&&y()}),e.watcher.on(`change`,t=>{x.resolve(t)===a&&e.restart().catch(e=>{let t=e instanceof Error?e.message:String(e);r.logger.error(b(`could not restart after ${i} changed: ${t}`))})})},closeBundle(){clearTimeout(l)},async buildStart(){await n.sync({info:e=>this.info(e),warn:e=>this.warn(e),error:e=>this.error(e)})},transform:{order:`pre`,async handler(e,t){let i=t.split(`?`)[0];if(!n.state.fileMessages.has(i))return null;let a=c(e);a!==n.state.hashOf(i)&&await n.runSync(f(r.logger),i);let s=n.state.fileMessages.get(i);if(!s||a!==n.state.hashOf(i))return n.state.warnedFiles.has(i)||(n.state.warnedFiles.add(i),this.warn(b(`${i} changed while it was being indexed; its messages are left untranslated.`))),null;if(s.length===0)return null;let l=n.isServing()?n.sourceLocale:n.selectedLocale(),u=n.isServing()||!!r.build.sourcemap,d=o(e,i,s,l,n.state.catalogs.get(l)??{},n.delivery===`runtime`,n.sourceLocale,u);return{code:d.code,map:d.map}}},async handleHotUpdate({file:e}){if(e.startsWith(n.localesDir()+x.sep))return[];n.state.fileMessages.has(e)&&await g(e)}}}const D=6e4;var O=class extends Error{retryable;retryAfterMs;constructor(e,t,n){super(e),this.retryable=t,this.retryAfterMs=n}};function ie(e,t=Date.now()){if(e===null||e===``)return;let n=Number(e);if(Number.isFinite(n))return Math.min(Math.max(n,0)*1e3,D);let r=Date.parse(e);if(!Number.isNaN(r))return Math.min(Math.max(r-t,0),D)}const ae=e=>new Promise(t=>setTimeout(t,e));function k(e){return`You are a professional software localization engine. Translate UI messages from ${e.sourceLocale} to ${e.targetLocale}. Preserve placeholders exactly. Some messages use ICU MessageFormat, such as {name}, {count, plural, one {# file} other {# files}} or {gender, select, ...}. Keep argument names, the keywords (one, other, select, plural, ...) and the # symbol unchanged, translate only the text inside the branches, and write the plural branches the target language needs. Messages marked "autoPlural" are natural-language count templates: convert their source to valid ICU plural syntax using the count argument, include language-appropriate categories (zero, one, two, few, many, other as needed), and include an explicit =0 branch when natural UI wording is different. A "hint" on an autoPlural message gives free-form source-author guidance for special count-dependent wording or thresholds; apply it naturally in the target language, using exact =N branches when a hint identifies specific counts and normal plural categories for ranges. Preserve {count} semantics and translate only the words inside branches. Respect context and UI conventions. When the source and target locales are the same, the source text is only a seed: rewrite it to apply the hint, keeping its placeholders. Keep the rewrite's length proportional to the seed: a one-word seed gets back one to three words, and a longer seed gets a proportionally longer rewrite, never a paragraph. A "hint" on a message without autoPlural is free-form author context, such as tone or audience; follow it in the wording while keeping every placeholder unchanged. Return ONLY a JSON object mapping message IDs to translated strings. Do not translate product names or code.`}function A(e){return JSON.stringify(e.map(e=>({id:e.id,text:e.source,context:e.context,...e.autoPlural===!0?{autoPlural:!0}:{},...e.hint!==void 0&&e.hint.length>0?{hint:e.hint}:{}})))}async function j(e){let t=e.status===408||e.status===409||e.status===429||e.status>=500;return await e.body?.cancel().catch(()=>void 0),new O(`Translation API failed (${e.status})`,t,ie(e.headers.get(`retry-after`)))}var M=class{options;slots;constructor(e){this.options=e,this.slots=new s(e.concurrency??4)}async translate(e){let t=Math.max(1,this.options.batchSize??40),n=[];for(let r=0;r<e.messages.length;r+=t)n.push(e.messages.slice(r,r+t));let r=await Promise.allSettled(n.map(t=>this.slots.run(()=>this.translateBatch({...e,messages:t})))),i={},a=[],o=0,s=0;if(r.forEach((e,t)=>{e.status===`fulfilled`?(s++,Object.assign(i,e.value)):(a.push(e.reason),o+=n[t].length)}),!a.length)return i;throw s?new l(`${o} messages failed to translate: ${a[0].message}`,i,o):a[0]}async translateBatch(e){let t=this.options.maxRetries??2,n=this.options.retryDelayMs??500;for(let r=0;;r++)try{return await this.request(e)}catch(e){if(e instanceof O&&!e.retryable||r>=t)throw e;let i=e instanceof O?e.retryAfterMs:void 0;await ae(i??n*2**r*(.5+Math.random()/2))}}async post(e,t,n){let r=await fetch(e,{method:`POST`,signal:AbortSignal.timeout(this.options.timeoutMs??6e4),headers:{...t,"content-type":`application/json`},body:JSON.stringify(n)});if(!r.ok)throw await j(r);return r.json()}async complete(e,t,n,r,i,a,o){let s=u(r,await this.post(e,t,n)),c=this.toCatalog(s.ok?i(s.value):void 0,a.messages);return a.onUsage?.({provider:o.provider,model:o.model,ids:a.messages.map(e=>e.id),...s.ok?o.tokens(s.value):{}}),c}toCatalog(e,t){let n=e?.trim().replace(/^```(?:json)?\s*|\s*```$/g,``);if(n===void 0||n===``)throw new O(`Translation provider returned no content`,!0);let i;try{i=JSON.parse(n)}catch{throw new O(`Translation provider returned invalid JSON`,!0)}let a=u(r,i);if(!a.ok)throw new O(`Translation provider returned a non-object`,!0);let o=new Set(t.map(e=>e.id)),s={};for(let[e,t]of Object.entries(a.value))o.has(e)&&typeof t==`string`&&t.trim()&&(s[e]=t);return s}};const N=`https://api.openai.com/v1`;var P=class extends M{async request(e){let{apiKey:t,model:r,baseURL:i=N}=this.options;return this.complete(`${i}/chat/completions`,t!==void 0&&t!==``?{Authorization:`Bearer ${t}`}:{},{model:r,temperature:0,response_format:{type:`json_object`},messages:[{role:`system`,content:k(e)},{role:`user`,content:A(e.messages)}]},n,e=>e.choices[0].message.content??void 0,e,{provider:i===N?`openai`:`openai-compatible`,model:r,tokens:e=>({inputTokens:e.usage?.prompt_tokens??void 0,outputTokens:e.usage?.completion_tokens??void 0})})}},F=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://api.anthropic.com/v1`}/messages`,{"x-api-key":this.options.apiKey,"anthropic-version":`2023-06-01`},{model:this.options.model,max_tokens:this.options.maxTokens??8192,system:k(e),messages:[{role:`user`,content:A(e.messages)}]},a,e=>e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),e,{provider:`anthropic`,model:this.options.model,tokens:e=>({inputTokens:e.usage?.input_tokens??void 0,outputTokens:e.usage?.output_tokens??void 0})})}},I=class extends M{async request(e){return this.complete(`${this.options.baseURL??`https://generativelanguage.googleapis.com/v1beta`}/models/${encodeURIComponent(this.options.model)}:generateContent`,{"x-goog-api-key":this.options.apiKey},{systemInstruction:{parts:[{text:k(e)}]},contents:[{role:`user`,parts:[{text:A(e.messages)}]}],generationConfig:{responseMimeType:`application/json`,maxOutputTokens:this.options.maxOutputTokens??8192}},t,e=>(e.candidates[0]?.content?.parts??[]).map(e=>e.text??``).join(``),e,{provider:`gemini`,model:this.options.model,tokens:e=>({inputTokens:e.usageMetadata?.promptTokenCount??void 0,outputTokens:e.usageMetadata?.candidatesTokenCount??void 0})})}};let oe=/* @__PURE__ */ function(e){return e.Anthropic=`anthropic`,e.Gemini=`gemini`,e.OpenAI=`openai`,e.Mistral=`mistral`,e.Groq=`groq`,e.DeepSeek=`deepseek`,e.OpenRouter=`openrouter`,e.XAI=`xai`,e.Cerebras=`cerebras`,e.Perplexity=`perplexity`,e.Together=`together`,e.Fireworks=`fireworks`,e.HuggingFace=`huggingface`,e.DeepInfra=`deepinfra`,e.SambaNova=`sambanova`,e.Moonshot=`moonshot`,e}({}),se=/* @__PURE__ */ function(e){return e.Ollama=`ollama`,e.LMStudio=`lmstudio`,e.LlamaCpp=`llamacpp`,e.VLLM=`vllm`,e.LocalAI=`localai`,e.DockerModelRunner=`dockermodelrunner`,e}({});const L={openai:{model:`gpt-4.1-mini`},mistral:{baseURL:`https://api.mistral.ai/v1`,model:`mistral-small-latest`},groq:{baseURL:`https://api.groq.com/openai/v1`,model:`llama-3.3-70b-versatile`},deepseek:{baseURL:`https://api.deepseek.com/v1`,model:`deepseek-chat`},openrouter:{baseURL:`https://openrouter.ai/api/v1`,model:`openai/gpt-4.1-mini`},xai:{baseURL:`https://api.x.ai/v1`,model:`grok-3-mini`},cerebras:{baseURL:`https://api.cerebras.ai/v1`,model:`llama-3.3-70b`},perplexity:{baseURL:`https://api.perplexity.ai`,model:`sonar`},together:{baseURL:`https://api.together.xyz/v1`,model:`meta-llama/Llama-3.3-70B-Instruct-Turbo`},fireworks:{baseURL:`https://api.fireworks.ai/inference/v1`,model:`accounts/fireworks/models/llama-v3p3-70b-instruct`},huggingface:{baseURL:`https://router.huggingface.co/v1`,model:`meta-llama/Llama-3.3-70B-Instruct`},deepinfra:{baseURL:`https://api.deepinfra.com/v1/openai`,model:`meta-llama/Meta-Llama-3.1-70B-Instruct`},sambanova:{baseURL:`https://api.sambanova.ai/v1`,model:`Meta-Llama-3.3-70B-Instruct`},moonshot:{baseURL:`https://api.moonshot.ai/v1`,model:`moonshot-v1-8k`}},ce={ollama:`http://localhost:11434/v1`,lmstudio:`http://localhost:1234/v1`,llamacpp:`http://localhost:8080/v1`,vllm:`http://localhost:8000/v1`,localai:`http://localhost:8080/v1`,dockermodelrunner:`http://localhost:12434/engines/v1`},R=e=>(t,n)=>new P({apiKey:t,baseURL:L[e].baseURL,model:n??L[e].model}),z={anthropic:(e,t)=>new F({apiKey:e,model:t??`claude-haiku-5-5`}),gemini:(e,t)=>new I({apiKey:e,model:t??`gemini-3.5-flash-lite`}),openai:R(`openai`),mistral:R(`mistral`),groq:R(`groq`),deepseek:R(`deepseek`),openrouter:R(`openrouter`),xai:R(`xai`),cerebras:R(`cerebras`),perplexity:R(`perplexity`),together:R(`together`),fireworks:R(`fireworks`),huggingface:R(`huggingface`),deepinfra:R(`deepinfra`),sambanova:R(`sambanova`),moonshot:R(`moonshot`)};function B(e,t,n){return t!==void 0&&t!==``?z[e](t,n):void 0}function V(e,t,n){if(t!==void 0&&t!==``)return new P({baseURL:n??ce[e],model:t})}function H(e,t){return B(e,t.apiKey,t.model)}function U(e,t){return V(e,t.model,t.baseURL)}const W=[`bg`,`cs`,`da`,`de`,`el`,`es`,`et`,`fi`,`fr`,`ga`,`hr`,`hu`,`it`,`lt`,`lv`,`mt`,`nl`,`pl`,`pt`,`ro`,`sk`,`sl`,`sv`],le=[`da`,`fi`,`is`,`no`,`sv`],ue=[`et`,`lv`,`lt`],de=[`bg`,`bs`,`el`,`hr`,`mk`,`ro`,`sq`,`sr`,`sl`],fe=[`nl`,`fr`,`lb`],pe=[.../* @__PURE__ */ new Set([...W,`no`,`is`,`sq`,`bs`,`mk`,`sr`,`uk`,`ru`,`be`,`ca`])],G=[`zh`,`ja`,`ko`,`mn`],K=[`hi`,`bn`,`ur`,`pa`,`ta`,`te`,`mr`,`gu`,`kn`,`ml`,`ne`,`si`],q=[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`],J=[`kk`,`ky`,`tg`,`tk`,`uz`],Y=[`hy`,`az`,`ka`],me=[.../* @__PURE__ */ new Set([...G,...K,...q,...J,...Y])],he=[`ar`,`fa`,`he`,`tr`,`ku`],X=[`ar`,`fr`,`pt`,`sw`,`am`,`ha`,`yo`,`ig`,`zu`,`xh`,`af`,`so`,`rw`,`wo`],Z=[`en`,`fr`,`es`],Q=[`es`,`en`,`fr`,`ht`,`nl`],$=[`es`,`pt`,`qu`,`gn`,`ay`],ge={EU:W,EUROPE:pe,NORDIC:le,BALTIC:ue,BALKANS:de,BENELUX:fe,EAST_ASIA:G,SOUTH_ASIA:K,SOUTHEAST_ASIA:q,CENTRAL_ASIA:J,CAUCASUS:Y,ASIA:me,MIDDLE_EAST:he,AFRICA:X,NORTH_AMERICA:Z,CENTRAL_AMERICA_CARIBBEAN:Q,SOUTH_AMERICA:$,AMERICAS:[.../* @__PURE__ */ new Set([...Z,...Q,...$])],OCEANIA:[`en`,`mi`,`sm`,`to`],ASEAN:[`id`,`ms`,`my`,`km`,`lo`,`fil`,`th`,`vi`,`en`],MERCOSUR:[`es`,`pt`,`gn`],GCC:[`ar`,`en`],CIS:[`ru`,`be`,`hy`,`az`,`kk`,`ky`,`tg`,`uz`],G7:[`en`,`fr`,`de`,`it`,`ja`],FRANCOPHONE:[`fr`,`ht`,`wo`,`ln`,`rw`],WORLDWIDE_POPULAR:[`en`,`zh`,`hi`,`es`,`ar`,`bn`,`pt`,`ru`,`ja`,`de`,`fr`,`ko`,`it`,`tr`,`vi`,`id`,`ur`]};function _e(...e){if(e.length>0)throw v(`i18nWorks() no longer takes options. Move them to ${i} as the default export, then call i18nWorks() with no arguments in vite.config.`);return E(g)}export{F as AnthropicProvider,p as FallbackProvider,I as GeminiProvider,oe as HostedService,se as LocalService,P as OpenAICompatibleProvider,l as PartialTranslationError,_e as default,B as hosted,H as hostedFromEnv,V as local,U as localFromEnv,ge as locales,d as resolveProvider,re as tpick};
@@ -1,4 +1,4 @@
1
- import{S as e,a as t,c as n,d as r,i,l as a,o,r as s,s as c,t as l,u,w as d,x as f}from"./sync-CG2Hl5sp.js";import{o as p}from"./icu-Cui2dM71.js";import m from"node:path";import{existsSync as h,readFileSync as g}from"node:fs";import{emitKeypressEvents as _}from"node:readline";import{readFile as v,readdir as y,rm as b}from"node:fs/promises";import{parseArgs as x}from"node:util";const ee=()=>({calls:0,inputTokens:0,outputTokens:0,cost:0,unpriced:0});function S(e,t){e.calls+=1,e.inputTokens+=t.inputTokens??0,e.outputTokens+=t.outputTokens??0,t.cost===void 0?e.unpriced+=1:e.cost+=t.cost}function te(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e)??ee();S(i,r),n.set(e,i)}return[...n].map(([e,t])=>({label:e,totals:t}))}function ne(e){let t=ee();for(let n of e)S(t,n);return{totals:t,models:te(e,e=>`${e.provider} ${e.model}`).sort((e,t)=>t.totals.cost-e.totals.cost||e.label.localeCompare(t.label)),months:te(e,e=>e.at.slice(0,7)).sort((e,t)=>e.label.localeCompare(t.label))}}const C=ne([]);function re(e){try{return g(e,`utf8`)}catch{return}}function ie(e,t){let n=/* @__PURE__ */ new Map;return{entry:t=>Object.hasOwn(e,t)?e[t]:void 0,readSource:e=>(n.has(e)||n.set(e,re(m.resolve(t,e))),n.get(e))}}const ae={title:[`1;4`,`22;24`],language:[`1`,`22`],left:[`1;36`,`22;39`],right:[`1;35`,`22;39`],source:[`34`,`39`],complete:[`32`,`39`],partial:[`33`,`39`],empty:[`31`,`39`],missing:[`3;31`,`23;39`],cursor:[`1;36`,`22;39`],selected:[`7`,`27`],key:[`1`,`22`],hint:[`2`,`22`],rule:[`2`,`22`],focus:[`1;33`,`22;39`]},w=(e,t)=>t;function T(e){return e?(e,t)=>{let[n,r]=ae[e];return`\x1b[${n}m${t}\x1b[${r}m`}:w}function E(e,t){let n=t.NO_COLOR;return e===!0&&(n===void 0||n===``)&&t.TERM!==`dumb`}const D={entry:()=>void 0,readSource:()=>void 0};function oe(e){return{status:`unavailable`,message:e instanceof Error?e.message:String(e)}}function se(e){if(e?.status!==`ready`)return!1;let{orphanedEntries:t,staleKeys:n,unconfiguredFiles:r}=e.summary;return t+n+r>0}const ce=` │ `,le=`› `,O=(e,t,n)=>Math.min(Math.max(e,t),n),k=(e,t)=>(e+t)%t,ue=e=>e.replace(/\s*\r?\n\s*/g,` `);function A(e,t,n){let r=Math.max(1,n),i=O(e-Math.floor(r/2),0,Math.max(0,t-r));return{start:i,end:Math.min(t,i+r)}}function j(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function de(e,t){return[.../* @__PURE__ */ new Set([...Object.keys(e.messages),...Object.keys(t.messages)])].map(n=>({id:n,source:j(e.sources,n)??j(t.sources,n),left:j(e.messages,n),right:j(t.messages,n)}))}function fe(e){return new Set(e.flatMap(({file:e})=>Object.keys(e.messages))).size}const M=({file:e})=>Object.keys(e.messages).length;function pe(e,t){let n=/* @__PURE__ */ new Map;for(let{file:t}of e)for(let[e,r]of Object.entries(t.sources))n.has(e)||n.set(e,r);let r=Object.fromEntries(n);return e.map(e=>e.locale===t?{...e,file:{...e.file,messages:{...r,...e.file.messages}}}:e)}const N=(e,t)=>e.map(({role:e,text:n})=>e===void 0?n:t(e,n)).join(``),P=e=>e.reduce((e,{text:t})=>e+t.length,0);function F(e,t){let n=e.map(({role:e,text:t})=>({role:e,text:ue(t)}));if(P(n)<=t)return n;let r=[],i=Math.max(0,t-1);for(let e of n){let t=e.text.slice(0,i);t.length>0&&r.push({role:e.role,text:t}),i-=t.length}return[...r,{role:r.at(-1)?.role,text:`…`}]}function I(e,t){let n=F(e,t),r=P(n);return r<t?[...n,{text:` `.repeat(t-r)}]:n}const L=(e,t,n)=>N(F(e,t),n);function R(e,t,n){return e?n(`cursor`,le)+n(`selected`,N(t,n)):` `+N(t,n)}function z(e){let t=[];for(let[n,[r,i]]of e.entries())n>0&&t.push({role:`hint`,text:` · `}),t.push({role:`key`,text:r},{role:`hint`,text:i});return t}function B(e,t){return e===0?`empty`:e===t?`complete`:`partial`}const V=e=>`${(e*100).toFixed(1)}%`;function me(e){return[{text:` (${V(e.coverage)})`},{text:` · ${e.missing.length} missing · ${e.outdated.length} outdated · ${e.orphanedKeys.length} orphaned`}]}function he(e,t,n){let r=fe(e),i=Math.max(...e.map(({locale:e})=>e.length));return e.map(e=>{let a=e.locale===t?[{role:`source`,text:` (source)`}]:[],o=n?.locales.find(({locale:t})=>t===e.locale),s=o===void 0?[{role:B(M(e),r),text:`${M(e)}/${r}`},{text:` translated`}]:[{role:B(o.translated,o.total),text:`${o.translated}/${o.total}`},{text:` translated`},...me(o)];return[{role:`language`,text:e.locale.padEnd(i)},{text:` `},...s,...a]})}function ge(e){if(e===void 0)return[];let{total:t,active:n,orphaned:r}=e.registry,i=e.averageCoverage===null?[]:[{text:` · average coverage ${V(e.averageCoverage)}`}];return[{role:`title`,text:`Registry:`},{text:` ${t} entries (${n} active, ${r} orphaned)`},...i]}function _e(e){let t=Object.entries(e?.registry.byComponent??{}).sort(([e],[t])=>e.localeCompare(t));return t.length===0?[]:[{role:`hint`,text:`By component:`},{text:` ${t.map(([e,t])=>`${e} ${t}`).join(`, `)}`}]}function ve(e,t,n,r=w){let i=he(e,t,n).map(e=>N(e,r));return n===void 0?i:[...[ge(n),_e(n)].filter(e=>e.length>0).map(e=>N(e,r)),``,...i]}function ye(e,t,n,r,i=!1,a=C){return t.name===`q`||t.ctrl===!0&&t.name===`c`?null:e.view===`compare`?Ce(e,t,n):e.view===`costs`?we(e,t,a):e.view===`prune`?{view:`languages`,selected:e.selected}:be(e.selected,t,n,r,i)}function be(e,t,n,r,i){let a=n.length-1;switch(t.name){case`up`:case`k`:return{view:`languages`,selected:O(e-1,0,a)};case`down`:case`j`:return{view:`languages`,selected:O(e+1,0,a)};case`return`:case`enter`:return a<0?{view:`languages`,selected:e}:xe(e,n,r);case`x`:return i?{view:`prune`,selected:e}:{view:`languages`,selected:e};case`c`:return{view:`costs`,selected:e,row:0};default:return{view:`languages`,selected:e}}}function xe(e,t,n){let r=t.findIndex(({locale:e})=>e===n);return{view:`compare`,left:e,right:r!==-1&&r!==e?r:k(e+1,t.length),row:0,preview:!0}}function Se(e,t,n){return Math.max(0,de(e[t].file,e[n].file).length-1)}function Ce(e,t,n){let r=n.length,i=Se(n,e.left,e.right),a=t=>({...e,row:O(t,0,i)}),o=(t,r)=>({...e,left:t,right:r,row:O(e.row,0,Se(n,t,r))});switch(t.name){case`up`:case`k`:return a(e.row-1);case`down`:case`j`:return a(e.row+1);case`pageup`:return a(e.row-10);case`pagedown`:return a(e.row+10);case`home`:return a(0);case`end`:return a(i);case`left`:return o(k(e.left-1,r),e.right);case`right`:return o(k(e.left+1,r),e.right);case`tab`:return o(e.left,k(e.right+(t.shift===!0?-1:1),r));case`p`:return{...e,preview:!e.preview};case`escape`:case`backspace`:return{view:`languages`,selected:e.left};default:return e}}function we(e,t,n){let r=Math.max(0,je(n).length-1),i=t=>({...e,row:O(t,0,r)});switch(t.name){case`up`:case`k`:return i(e.row-1);case`down`:case`j`:return i(e.row+1);case`pageup`:return i(e.row-10);case`pagedown`:return i(e.row+10);case`home`:return i(0);case`end`:return i(r);case`escape`:case`backspace`:return{view:`languages`,selected:e.selected};default:return e}}function Te(e,t,n,r,i=w,a=D,o,s,c,l=C){return e.view===`compare`?Re(e,t,r,i,a):e.view===`costs`?Me(e,l,r,i):De(e,t,n,r,i,o,s,c)}function Ee(e){let t={role:`title`,text:`Prune:`};if(e===void 0)return[];if(e.status===`unavailable`)return[t,{role:`missing`,text:` unavailable (${e.message})`}];if(!se(e))return[t,{text:` nothing to remove.`}];let{orphanedEntries:n,staleKeys:r,unconfiguredFiles:i}=e.summary;return[t,{text:` ${[n>0&&`${n} orphaned ${n===1?`entry`:`entries`}`,r>0&&`${r} stale ${r===1?`key`:`keys`}`,i>0&&`${i} unconfigured locale ${i===1?`file`:`files`}`].filter(e=>typeof e==`string`).join(`, `)}.`}]}function De(e,t,n,r,i,a,o,s){let{selected:c}=e,l=he(t,n,o),{start:u,end:d}=A(c,l.length,r.height-8),f=l.slice(u,d).map((e,t)=>R(u+t===c,I(e,r.width-2),i)),p=e.view===`prune`?z([[`y`,` prune now`],[`any other key`,` cancel`]]):z([[`↑/↓`,` move`],[`Enter`,` compare`],[`x`,` prune`],[`t`,` translate`],[`c`,` costs`],[`q`,` quit`]]);return[L([{role:`title`,text:`Translation files:`},{text:` ${t.length} languages, source `},{role:`language`,text:n}],r.width,i),L(Ee(a),r.width,i),L(ge(o),r.width,i),L(_e(o),r.width,i),L(s===void 0?[]:[{text:s}],r.width,i),``,...f,``,L(p,r.width,i)].join(`
1
+ import{S as e,a as t,c as n,d as r,i,l as a,o,r as s,s as c,t as l,u,w as d,x as f}from"./sync-CXMq5LNq.js";import{o as p}from"./icu-Cui2dM71.js";import m from"node:path";import{existsSync as h,readFileSync as g}from"node:fs";import{emitKeypressEvents as _}from"node:readline";import{readFile as v,readdir as y,rm as b}from"node:fs/promises";import{parseArgs as x}from"node:util";const ee=()=>({calls:0,inputTokens:0,outputTokens:0,cost:0,unpriced:0});function S(e,t){e.calls+=1,e.inputTokens+=t.inputTokens??0,e.outputTokens+=t.outputTokens??0,t.cost===void 0?e.unpriced+=1:e.cost+=t.cost}function te(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=n.get(e)??ee();S(i,r),n.set(e,i)}return[...n].map(([e,t])=>({label:e,totals:t}))}function ne(e){let t=ee();for(let n of e)S(t,n);return{totals:t,models:te(e,e=>`${e.provider} ${e.model}`).sort((e,t)=>t.totals.cost-e.totals.cost||e.label.localeCompare(t.label)),months:te(e,e=>e.at.slice(0,7)).sort((e,t)=>e.label.localeCompare(t.label))}}const C=ne([]);function re(e){try{return g(e,`utf8`)}catch{return}}function ie(e,t){let n=/* @__PURE__ */ new Map;return{entry:t=>Object.hasOwn(e,t)?e[t]:void 0,readSource:e=>(n.has(e)||n.set(e,re(m.resolve(t,e))),n.get(e))}}const ae={title:[`1;4`,`22;24`],language:[`1`,`22`],left:[`1;36`,`22;39`],right:[`1;35`,`22;39`],source:[`34`,`39`],complete:[`32`,`39`],partial:[`33`,`39`],empty:[`31`,`39`],missing:[`3;31`,`23;39`],cursor:[`1;36`,`22;39`],selected:[`7`,`27`],key:[`1`,`22`],hint:[`2`,`22`],rule:[`2`,`22`],focus:[`1;33`,`22;39`]},w=(e,t)=>t;function T(e){return e?(e,t)=>{let[n,r]=ae[e];return`\x1b[${n}m${t}\x1b[${r}m`}:w}function E(e,t){let n=t.NO_COLOR;return e===!0&&(n===void 0||n===``)&&t.TERM!==`dumb`}const D={entry:()=>void 0,readSource:()=>void 0};function oe(e){return{status:`unavailable`,message:e instanceof Error?e.message:String(e)}}function se(e){if(e?.status!==`ready`)return!1;let{orphanedEntries:t,staleKeys:n,unconfiguredFiles:r}=e.summary;return t+n+r>0}const ce=` │ `,le=`› `,O=(e,t,n)=>Math.min(Math.max(e,t),n),k=(e,t)=>(e+t)%t,ue=e=>e.replace(/\s*\r?\n\s*/g,` `);function A(e,t,n){let r=Math.max(1,n),i=O(e-Math.floor(r/2),0,Math.max(0,t-r));return{start:i,end:Math.min(t,i+r)}}function j(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function de(e,t){return[.../* @__PURE__ */ new Set([...Object.keys(e.messages),...Object.keys(t.messages)])].map(n=>({id:n,source:j(e.sources,n)??j(t.sources,n),left:j(e.messages,n),right:j(t.messages,n)}))}function fe(e){return new Set(e.flatMap(({file:e})=>Object.keys(e.messages))).size}const M=({file:e})=>Object.keys(e.messages).length;function pe(e,t){let n=/* @__PURE__ */ new Map;for(let{file:t}of e)for(let[e,r]of Object.entries(t.sources))n.has(e)||n.set(e,r);let r=Object.fromEntries(n);return e.map(e=>e.locale===t?{...e,file:{...e.file,messages:{...r,...e.file.messages}}}:e)}const N=(e,t)=>e.map(({role:e,text:n})=>e===void 0?n:t(e,n)).join(``),P=e=>e.reduce((e,{text:t})=>e+t.length,0);function F(e,t){let n=e.map(({role:e,text:t})=>({role:e,text:ue(t)}));if(P(n)<=t)return n;let r=[],i=Math.max(0,t-1);for(let e of n){let t=e.text.slice(0,i);t.length>0&&r.push({role:e.role,text:t}),i-=t.length}return[...r,{role:r.at(-1)?.role,text:`…`}]}function I(e,t){let n=F(e,t),r=P(n);return r<t?[...n,{text:` `.repeat(t-r)}]:n}const L=(e,t,n)=>N(F(e,t),n);function R(e,t,n){return e?n(`cursor`,le)+n(`selected`,N(t,n)):` `+N(t,n)}function z(e){let t=[];for(let[n,[r,i]]of e.entries())n>0&&t.push({role:`hint`,text:` · `}),t.push({role:`key`,text:r},{role:`hint`,text:i});return t}function B(e,t){return e===0?`empty`:e===t?`complete`:`partial`}const V=e=>`${(e*100).toFixed(1)}%`;function me(e){return[{text:` (${V(e.coverage)})`},{text:` · ${e.missing.length} missing · ${e.outdated.length} outdated · ${e.orphanedKeys.length} orphaned`}]}function he(e,t,n){let r=fe(e),i=Math.max(...e.map(({locale:e})=>e.length));return e.map(e=>{let a=e.locale===t?[{role:`source`,text:` (source)`}]:[],o=n?.locales.find(({locale:t})=>t===e.locale),s=o===void 0?[{role:B(M(e),r),text:`${M(e)}/${r}`},{text:` translated`}]:[{role:B(o.translated,o.total),text:`${o.translated}/${o.total}`},{text:` translated`},...me(o)];return[{role:`language`,text:e.locale.padEnd(i)},{text:` `},...s,...a]})}function ge(e){if(e===void 0)return[];let{total:t,active:n,orphaned:r}=e.registry,i=e.averageCoverage===null?[]:[{text:` · average coverage ${V(e.averageCoverage)}`}];return[{role:`title`,text:`Registry:`},{text:` ${t} entries (${n} active, ${r} orphaned)`},...i]}function _e(e){let t=Object.entries(e?.registry.byComponent??{}).sort(([e],[t])=>e.localeCompare(t));return t.length===0?[]:[{role:`hint`,text:`By component:`},{text:` ${t.map(([e,t])=>`${e} ${t}`).join(`, `)}`}]}function ve(e,t,n,r=w){let i=he(e,t,n).map(e=>N(e,r));return n===void 0?i:[...[ge(n),_e(n)].filter(e=>e.length>0).map(e=>N(e,r)),``,...i]}function ye(e,t,n,r,i=!1,a=C){return t.name===`q`||t.ctrl===!0&&t.name===`c`?null:e.view===`compare`?Ce(e,t,n):e.view===`costs`?we(e,t,a):e.view===`prune`?{view:`languages`,selected:e.selected}:be(e.selected,t,n,r,i)}function be(e,t,n,r,i){let a=n.length-1;switch(t.name){case`up`:case`k`:return{view:`languages`,selected:O(e-1,0,a)};case`down`:case`j`:return{view:`languages`,selected:O(e+1,0,a)};case`return`:case`enter`:return a<0?{view:`languages`,selected:e}:xe(e,n,r);case`x`:return i?{view:`prune`,selected:e}:{view:`languages`,selected:e};case`c`:return{view:`costs`,selected:e,row:0};default:return{view:`languages`,selected:e}}}function xe(e,t,n){let r=t.findIndex(({locale:e})=>e===n);return{view:`compare`,left:e,right:r!==-1&&r!==e?r:k(e+1,t.length),row:0,preview:!0}}function Se(e,t,n){return Math.max(0,de(e[t].file,e[n].file).length-1)}function Ce(e,t,n){let r=n.length,i=Se(n,e.left,e.right),a=t=>({...e,row:O(t,0,i)}),o=(t,r)=>({...e,left:t,right:r,row:O(e.row,0,Se(n,t,r))});switch(t.name){case`up`:case`k`:return a(e.row-1);case`down`:case`j`:return a(e.row+1);case`pageup`:return a(e.row-10);case`pagedown`:return a(e.row+10);case`home`:return a(0);case`end`:return a(i);case`left`:return o(k(e.left-1,r),e.right);case`right`:return o(k(e.left+1,r),e.right);case`tab`:return o(e.left,k(e.right+(t.shift===!0?-1:1),r));case`p`:return{...e,preview:!e.preview};case`escape`:case`backspace`:return{view:`languages`,selected:e.left};default:return e}}function we(e,t,n){let r=Math.max(0,je(n).length-1),i=t=>({...e,row:O(t,0,r)});switch(t.name){case`up`:case`k`:return i(e.row-1);case`down`:case`j`:return i(e.row+1);case`pageup`:return i(e.row-10);case`pagedown`:return i(e.row+10);case`home`:return i(0);case`end`:return i(r);case`escape`:case`backspace`:return{view:`languages`,selected:e.selected};default:return e}}function Te(e,t,n,r,i=w,a=D,o,s,c,l=C){return e.view===`compare`?Re(e,t,r,i,a):e.view===`costs`?Me(e,l,r,i):De(e,t,n,r,i,o,s,c)}function Ee(e){let t={role:`title`,text:`Prune:`};if(e===void 0)return[];if(e.status===`unavailable`)return[t,{role:`missing`,text:` unavailable (${e.message})`}];if(!se(e))return[t,{text:` nothing to remove.`}];let{orphanedEntries:n,staleKeys:r,unconfiguredFiles:i}=e.summary;return[t,{text:` ${[n>0&&`${n} orphaned ${n===1?`entry`:`entries`}`,r>0&&`${r} stale ${r===1?`key`:`keys`}`,i>0&&`${i} unconfigured locale ${i===1?`file`:`files`}`].filter(e=>typeof e==`string`).join(`, `)}.`}]}function De(e,t,n,r,i,a,o,s){let{selected:c}=e,l=he(t,n,o),{start:u,end:d}=A(c,l.length,r.height-8),f=l.slice(u,d).map((e,t)=>R(u+t===c,I(e,r.width-2),i)),p=e.view===`prune`?z([[`y`,` prune now`],[`any other key`,` cancel`]]):z([[`↑/↓`,` move`],[`Enter`,` compare`],[`x`,` prune`],[`t`,` translate`],[`c`,` costs`],[`q`,` quit`]]);return[L([{role:`title`,text:`Translation files:`},{text:` ${t.length} languages, source `},{role:`language`,text:n}],r.width,i),L(Ee(a),r.width,i),L(ge(o),r.width,i),L(_e(o),r.width,i),L(s===void 0?[]:[{text:s}],r.width,i),``,...f,``,L(p,r.width,i)].join(`
2
2
  `)}function Oe(e){if(e.calls===e.unpriced)return`unknown`;let t=`$${e.cost.toFixed(6)}`;return e.unpriced===0?t:`${t} (+${e.unpriced} unpriced)`}function ke(e){return[W(`Totals`),H(`calls`,U(String(e.calls))),H(`tokens in`,U(String(e.inputTokens))),H(`tokens out`,U(String(e.outputTokens))),H(`cost`,U(Oe(e))),[]]}function Ae(e,t,n){let r=Math.max(t.length,...n.map(({label:e})=>e.length)),i=[{role:`hint`,text:t.padEnd(r)},{role:`hint`,text:`calls`.padStart(8)},{role:`hint`,text:`tokens in`.padStart(12)},{role:`hint`,text:`tokens out`.padStart(12)},{role:`hint`,text:` cost`}];return[W(e),i,...n.map(({label:e,totals:t})=>[{text:e.padEnd(r)},{text:String(t.calls).padStart(8)},{text:String(t.inputTokens).padStart(12)},{text:String(t.outputTokens).padStart(12)},{text:` ${Oe(t)}`}]),[]]}function je(e){return e.totals.calls===0?[[{role:`hint`,text:`No AI calls recorded yet. Enable the costs option to record them.`}]]:[...ke(e.totals),...Ae(`Models`,`model`,e.models),...Ae(`Months (UTC)`,`month`,e.months)]}function Me(e,t,n,r){let i=je(t),a=Math.max(1,n.height-4),{start:o,end:s}=A(e.row,i.length,a),c=r(`rule`,`─`.repeat(n.width));return[L([{role:`title`,text:`Costs`},{role:`hint`,text:` estimated USD`}],n.width,r),c,...i.slice(o,s).map(e=>L(e,n.width,r)),c,L(z([[`↑/↓`,` scroll`],[`PgUp/PgDn`,` page`],[`Esc`,` languages`],[`q`,` quit`]]),n.width,r)].join(`
3
3
  `)}function Ne(e){return e===void 0?[]:[{role:`source`,text:`source: `},e.source===void 0?{role:`missing`,text:`(not recorded)`}:{role:`source`,text:e.source}]}const H=(e,t)=>[{role:`hint`,text:e.padEnd(11)},...t],U=e=>[{text:e}],W=e=>[{role:`title`,text:e}];function Pe(e,t){let n={column:Math.max(8,Math.floor((e-2-3)/2)),pane:0};if(!t)return n;let r=O(Math.floor(e*.4),24,48),i=Math.floor((e-2-6-r)/2);return i>=12?{column:i,pane:r}:n}function Fe(e,t){if(!(!Number.isInteger(t)||t<0||t>e.length))return e.slice(0,t).split(`
4
4
  `).length}function Ie(e,t,n){if(e===void 0)return[[{role:`missing`,text:`(source file cannot be read)`}]];if(t===void 0)return[[{role:`missing`,text:`(the file is shorter than the recorded location)`}]];let r=e.split(`
@@ -0,0 +1,7 @@
1
+ import{a as e,i as t,n,o as r,r as i}from"./icu-Cui2dM71.js";import{createRequire as a}from"node:module";import{existsSync as o}from"node:fs";import{loadConfigFromFile as s}from"vite";import c,{basename as l,extname as u}from"node:path";import{createHash as d,randomUUID as f}from"node:crypto";import{parseSync as p}from"rolldown/utils";import m from"magic-string";import{glob as h,mkdir as g,readFile as _,rename as v,rm as y,stat as ee,writeFile as te}from"node:fs/promises";const b=Symbol(`failed`),x=(e,t)=>(e.push({path:[],message:t}),b),ne=(e,t,n,r)=>{let i=r.length,a=e.check(t,r);if(a===b)for(let e=i;e<r.length;e++)r[e]={path:[n,...r[e].path],message:r[e].message};return a},S=e=>`must be ${e}`,C=(e,t)=>({expected:e,check:(n,r)=>t(n)?n:x(r,S(e))}),w=C(`a string`,e=>typeof e==`string`),T=C(`a finite number`,e=>typeof e==`number`&&Number.isFinite(e)),E=C(`a boolean`,e=>typeof e==`boolean`),D=C(`an object`,e=>typeof e==`object`&&!!e||typeof e==`function`);function O(e){let t=typeof e==`string`?JSON.stringify(e):String(e);return C(t,t=>t===e)}function k(e,t,n){return{expected:n,check:(r,i)=>{let a=e.check(r,i);return a===b?b:t(a)?a:x(i,S(n))}}}function A(e,{nonEmpty:t=!1}={}){let n=t?`a non-empty array`:`an array`;return{expected:n,check:(r,i)=>{if(!Array.isArray(r)||t&&r.length===0)return x(i,S(n));let a=!1,o=[];for(let[t,n]of r.entries()){let r=ne(e,n,t,i);r===b?a=!0:o.push(r)}return a?b:o}}}function j(...e){let t=e.map(e=>e.expected).join(` or `);return{expected:t,check:(n,r)=>{for(let t of e){let e=t.check(n,[]);if(e!==b)return e}return x(r,S(t))}}}function M(e){return{...e,optional:!0}}function N(e,t=`ignore`){let n=Object.entries(e),r=new Set(Object.keys(e));return{expected:`an object`,check:(e,i)=>{let a=D.check(e,i);if(a===b)return b;let o=!1,s={};for(let[e,t]of n){if(!Object.hasOwn(a,e)){t.optional!==!0&&(i.push({path:[e],message:`is required`}),o=!0);continue}let n=ne(t,a[e],e,i);n===b?o=!0:s[e]=n}if(t===`reject`)for(let e of Object.keys(a))r.has(e)||(i.push({path:[e],message:`is not a known key`}),o=!0);return o?b:s}}}function P(e,t){let n=[],r=e.check(t,n);return r===b?{ok:!1,issues:n}:{ok:!0,value:r}}const F=e=>M(j(e,O(void 0))),I=M(j(T,O(null))),re=N({choices:A(N({message:N({content:M(j(w,O(null)))})}),{nonEmpty:!0}),usage:M(j(N({prompt_tokens:I,completion_tokens:I}),O(null)))}),ie=N({content:A(N({type:w,text:M(w)})),usage:M(j(N({input_tokens:I,output_tokens:I}),O(null)))}),ae=N({candidates:A(N({content:M(N({parts:M(A(N({text:M(w)})))}))})),usageMetadata:M(j(N({promptTokenCount:I,candidatesTokenCount:I}),O(null)))}),oe=D,se=N({messages:D,sources:D}),ce=N({id:w,source:w,component:w,fingerprint:w,autoPlural:F(E),hint:F(w),location:w,status:j(O(`active`),O(`orphaned`)),firstSeen:w,lastSeen:w}),le=N({id:w,at:w,sourceLocale:w,locale:w,provider:w,model:w,ids:A(w),inputTokens:F(T),outputTokens:F(T),cost:F(T)}),ue=N({version:O(1),entries:D,costs:M(D)}),de=k(w,e=>e.length>0,`a non-empty string`),fe=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,L=k(w,e=>fe.test(e),`a locale tag`),pe=N({locales:A(L),sourceLocale:F(L),delivery:F(j(O(`build`),O(`runtime`))),locale:F(L),include:F(A(w)),exclude:F(A(w)),directory:F(de),provider:F(D),failOnMissingProvider:F(E),onAmbiguous:F(j(O(`warn`),O(`error`))),orphanRetentionMinutes:F(j(k(T,e=>e>=0,`a number >= 0`),O(1/0))),localeConcurrency:F(k(T,e=>e>=1,`a number >= 1`)),debug:F(E),costs:F(E)},`reject`),R=`vite-i18n.config.js`;function me(e){return c.resolve(e,R)}function he(t){let n=P(pe,t);if(n.ok)return;let r=n.issues.map(e=>`${e.path.join(`.`)||`options`}: ${e.message}`).join(`; `);throw e(`invalid options in ${R} (${r}). Fix or remove these keys; the README lists every option.`)}const ge=async(t,n)=>{let r=me(t);if(!o(r))throw e(`${R} was not found in ${t}. Create it next to vite.config with the plugin options as the default export, for example:\n\n export default {
2
+ locales: ["en", "de"],
3
+ sourceLocale: "en",
4
+ };\n\nThe README lists every option.`);try{return(await s(n,r,t))?.config}catch(t){let n=t instanceof Error?t.message:String(t);throw e(`could not load ${R}: ${n}. Check the file for syntax errors and make sure it has a default export that is an object.`)}};function z(e){return e.replace(/\s+/g,` `).trim()}function _e(e){let t=e.autoPlural===!0?`tt`:`t`;return d(`sha256`).update(`${t}\u0000${z(e.source)}\u0000${z(e.hint??``)}`).digest(`hex`).slice(0,24)}function B(e,t){let n=p(t,e,{lang:`tsx`,sourceType:`unambiguous`});if(n.errors.length)throw SyntaxError(`${t}: ${n.errors[0].message}`);return n.program}function ve(e,t){let n=[],r=e=>{if(t(e,n)!==!1){n.push(e);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];Array.isArray(n)?n.forEach(e=>V(e)&&r(e)):V(n)&&r(n)}n.pop()}};r(e)}function V(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function H(e){return V(e)&&e.type===`Literal`&&typeof e.value==`string`}const ye=a(import.meta.url);function be(t,n,r){try{return ye(t)}catch{throw e(`${r} files need the "${n}" package. Install it with your package manager.`)}}let xe;function Se(e,t){xe??=be(`@astrojs/compiler/sync`,`@astrojs/compiler`,`Astro`);let{ast:n,diagnostics:r}=xe.parse(e,{position:!0}),i=r.find(e=>e.severity===1);if(i)throw SyntaxError(`${t}: ${i.text}`);let a=Ce(e),o=l(t,u(t)),s=[],c=(n,r)=>{let i=e.slice(n,r);i.trim()!==``&&s.push({root:B(`[${i}\n]`,t),offset:n-1,component:o})},d=e=>{if(e.type===`comment`)return;if(e.type===`expression`)return f(e.children??[]);let t=a(e.position.start.offset);return e.type===`text`?{start:t,end:t+e.value.length}:{start:t,end:a(e.position.end.offset)}},f=e=>{let t=e.map(d).filter(e=>e!==void 0);if(t.length!==0)return{start:t[0].start,end:t[t.length-1].end}},p=t=>{let n=a(t.position.start.offset),r=e.indexOf(t.value,n+t.name.length);c(r,r+t.value.length)},m=e=>{if(e.type===`frontmatter`){let n=a(e.position.start.offset)+3;s.push({root:B(e.value,t),offset:n,component:o})}else if(e.type===`expression`){let t=d(e);t&&c(t.start,t.end)}else{for(let t of e.attributes??[])t.kind===`expression`&&p(t);for(let t of e.children??[])m(t)}};return m(n),s}function Ce(e){let t=Buffer.byteLength(e);if(t===e.length)return e=>e;let n=new Uint32Array(t+1),r=0;for(let t=0;t<e.length;){let i=e.codePointAt(t),a=Buffer.byteLength(String.fromCodePoint(i));n.fill(t,r,r+a),r+=a,t+=i>65535?2:1}return n[r]=e.length,e=>n[e]}let we;function U(e,t){we??=be(`svelte/compiler`,`svelte`,`Svelte`);try{return we.parse(e,{modern:!0})}catch(e){throw SyntaxError(`${t}: ${e.message}`,{cause:e})}}function Te(e,t){let n=U(e,t),r=l(t,u(t)),i=[];return n.module&&i.push({root:n.module.content,offset:0}),n.instance&&i.push({root:n.instance.content,offset:0,component:r}),i.push({root:n.fragment,offset:0,component:r}),i}function Ee(e,t){let n=U(e,t),r=n.instance??n.module;return r?r.content.start:0}function De(e,t){switch(u(t)){case`.svelte`:return{regions:Te(e,t)};case`.astro`:return{regions:Se(e,t)};default:return{regions:[{root:B(e,t),offset:0}]}}}const W=`virtual:i18n-works`,G=`i18n-works/runtime`,K=`__i18nWorksT`,Oe=`__i18nWorksFormat`,ke=`__i18nWorksFormatAutoPlural`,Ae=String.raw`\s*(["'])[^"'\n]*\1[ \t]*;?[ \t]*(?:\r?\n|$)`,q=new RegExp(Ae,`y`);function je(e){let t=0;if(e.startsWith(`#!`)){let n=e.indexOf(`
5
+ `);t=n===-1?e.length:n+1}q.lastIndex=t;for(let n=q.exec(e);n;n=q.exec(e))t=q.lastIndex;return t}function Me(e,t){switch(u(t)){case`.svelte`:return{offset:Ee(e,t),format:e=>`\n${e}`};case`.astro`:return{offset:3,format:e=>`\n${e}`};default:return{offset:je(e),format:e=>`${e}\n`}}}function Ne(e,t,n,r,i,a=!1,o=`en`,s=!0){let c=new m(e),l=e=>r===o&&e.hint===void 0?e.source:i[e.id]??e.source;for(let e of n){if(e.valuesStart===void 0){let t=a?`${K}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)})`:JSON.stringify(l(e));c.overwrite(e.start,e.end,t);continue}let t;t=a&&e.autoPlural===!0?`__i18nWorksLookupAutoPlural(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:a?`${K}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:e.autoPlural===!0?`${ke}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `:`${Oe}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `,c.overwrite(e.start,e.valuesStart,t)}let u=[];if(a&&n.length&&u.push(`import { lookup as ${K} } from "${W}";`),a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { lookupAutoPlural as __i18nWorksLookupAutoPlural } from "${W}";`),!a&&n.some(e=>e.valuesStart!==void 0)&&u.push(`import { formatMessage as ${Oe} } from "${G}";`),!a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { formatAutoPluralMessage as ${ke} } from "${G}";`),u.length){let n=Me(e,t);c.appendLeft(n.offset,n.format(u.join(`
6
+ `)))}return{code:c.toString(),map:s?c.generateMap({source:t,hires:!0,includeContent:!1}):null}}const Pe=`<module>`,Fe=e=>/[A-Za-z]/.test(e);function Ie(e,t){try{n(e)}catch(e){throw SyntaxError(`${t}: t() message is not valid ICU MessageFormat: ${e.message}`,{cause:e})}}function Le(e){let t={t:/* @__PURE__ */ new Set,tt:/* @__PURE__ */ new Set,tauto:/* @__PURE__ */ new Set};for(let{root:n}of e)if(n.type===`Program`){for(let e of n.body)if(e.type===`ImportDeclaration`&&e.source.value===`virtual:i18n-works`)for(let n of e.specifiers){if(n.type!==`ImportSpecifier`)continue;let e=n.imported.type===`Identifier`?n.imported.name:n.imported.value;e===`t`&&t.t.add(n.local.name),e===`tt`&&t.tt.add(n.local.name),e===`tauto`&&t.tauto.add(n.local.name)}}return t}const Re=(e,t)=>e.type===`FunctionExpression`?!(t?.type===`MethodDefinition`||t?.type===`Property`&&(t.method||t.kind!==`init`)):e.type===`FunctionDeclaration`||e.type===`ArrowFunctionExpression`;function ze(e,t){let n=e.length-1;for(;n>=0&&!Re(e[n],e[n-1]);)n--;if(n<0)return t;let r=e[n],i=n>0?e[n-1]:void 0;return i?.type===`VariableDeclarator`&&i.id.type===`Identifier`?i.id.name:r.type===`FunctionDeclaration`&&r.id?r.id.name:`<anonymous>`}function Be(e,t,n){if(n===void 0&&!e.includes(`virtual:i18n-works`))return[];let{regions:r}=n??De(e,t),i=Le(r),a=[];for(let e of r){let{root:n,offset:r}=e;ve(n,(n,o)=>{if(n.type!==`CallExpression`||n.callee.type!==`Identifier`)return;let s=i.tt.has(n.callee.name),c=s||i.tauto.has(n.callee.name);if(!c&&!i.t.has(n.callee.name))return;let l=i.tauto.has(n.callee.name)&&H(n.arguments.at(1));if(n.arguments.length>(c&&!l?3:2))return;let[u]=n.arguments,d=l?void 0:n.arguments.at(1),f=c?n.arguments.at(l?1:2):void 0;if(!H(u)||d?.type===`SpreadElement`||f!==void 0&&!H(f))return;let p=z(u.value);if(!p||!Fe(p))return;d&&Ie(p,t);let m=H(f)?z(f.value):void 0;a.push({source:p,file:t,start:r+n.start,end:r+n.end,valuesStart:d===void 0?void 0:r+d.start,autoPlural:s||void 0,hint:m!==void 0&&m.length>0?m:void 0,component:ze(o,e.component??`<module>`),fingerprint:_e({source:p,autoPlural:s,hint:m})})})}return a.sort((e,t)=>e.start-t.start)}const Ve=e=>JSON.stringify(e,null,2)+`
7
+ `,He=e=>d(`sha256`).update(e).digest(`hex`);async function Ue(e,t,n){let i;try{i=await _(e,`utf8`)}catch(i){return i.code===`ENOENT`||n?.(r(`could not read ${e}: ${i.message}`)),t}try{return JSON.parse(i)}catch(i){let a=`${e}.corrupt-${Date.now()}`;return await v(e,a).catch(()=>void 0),n?.(r(`${e} is not valid JSON (${i.message}); moved to ${a} and starting fresh.`)),t}}async function We(e,t){await g(c.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${f()}.tmp`;await te(n,t,`utf8`),await v(n,e)}async function Ge(e,t){await _(e,`utf8`).catch(()=>void 0)!==t&&await We(e,t)}var Ke=class extends Error{partial;failed;constructor(e,t,n){super(e),this.partial=t,this.failed=n,this.name=`PartialTranslationError`}};function qe(e){return e instanceof Error&&e.name===`PartialTranslationError`&&`partial`in e}var Je=class{providers;onFallback;constructor(e,t=()=>{}){this.providers=e,this.onFallback=t}async translate(e){let t={},n=e.messages,r,i;for(let[a,{name:o,provider:s}]of this.providers.entries()){try{Object.assign(t,await s.translate({...e,messages:n}))}catch(e){r??=e,i=e,qe(e)&&Object.assign(t,e.partial);let s=this.providers.at(a+1);s&&n.some(e=>!Object.hasOwn(t,e.id))&&this.onFallback(`${o} failed (${Ye(e)}); sending the rest to ${s.name}.`)}if(n=n.filter(e=>!Object.hasOwn(t,e.id)),!n.length)return t}throw Object.keys(t).length===0?r:new Ke(`${n.length} messages failed to translate: ${Ye(i)}`,t,n.length)}};const Ye=e=>e instanceof Error?e.message:String(e),Xe=e=>typeof e==`object`&&!!e&&typeof e.translate==`function`;function Ze(t,n){if(t===void 0)return;if(Xe(t))return t;let{primary:r,...i}=t,a=[];for(let[t,n]of Object.entries(i))if(n!==void 0){if(!Xe(n))throw e(`provider "${t}" must be an object with a translate(input) method. Use hosted(), local(), or a provider class exported by i18n-works.`);a.push({name:t,provider:n})}if(r!==void 0){let t=a.findIndex(e=>e.name===r);if(t<0)throw e(`primary provider "${r}" is not configured. Add it under provider in vite-i18n.config.js, or change primary to one of: ${a.map(e=>e.name).join(`, `)||`none`}.`);a.unshift(...a.splice(t,1))}if(a.length!==0)return a.length===1?a[0].provider:new Je(a,n)}async function Qe(e,t,n){let r=Array(e.length),i=0;return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},async()=>{for(;i<e.length;){let t=i++;try{r[t]={status:`fulfilled`,value:await n(e[t])}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var $e=class{available;waiters=[];constructor(e){this.available=Math.max(1,Math.floor(e))}async run(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.available>0?(this.available--,Promise.resolve()):new Promise(e=>this.waiters.push(e))}release(){let e=this.waiters.shift();e?e():this.available++}};const et={anthropic:{"claude-haiku-5-5":{input:.1,output:.5},"claude-haiku-4-5":{input:1,output:5}},openai:{"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-5-mini":{input:.25,output:2},"gpt-5-nano":{input:.05,output:.4}}};function tt(e){let t=et[e.provider]?.[e.model];if(t!==void 0&&e.inputTokens!==void 0&&e.outputTokens!==void 0)return(e.inputTokens*t.input+e.outputTokens*t.output)/1e6}const nt=e=>console.log(`[${t} costs] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);function rt(e,t,n){let r=n.inputTokens===void 0||n.outputTokens===void 0?`tokens not reported`:`${n.inputTokens} input + ${n.outputTokens} output tokens`,i=tt(n),a=i===void 0?`cost unknown`:`cost $${i.toFixed(6)}`;nt(`${e} -> ${t} ${n.ids.length} messages (${n.ids.join(`, `)}) via ${n.provider} ${n.model}: ${r}, ${a}`)}function it(e,t,n){nt(`${e} -> ${t} ${n} messages translated, provider reported no usage: cost unknown`)}const at=43200,ot=()=>({version:1,entries:{},costs:{}});function st(e,t,n,r,i=(/* @__PURE__ */ new Date()).toISOString()){let a=`call_${f().replaceAll(`-`,``).slice(0,16)}`,o=tt(r);return e.costs[a]={id:a,at:i,sourceLocale:t,locale:n,provider:r.provider,model:r.model,ids:r.ids,...r.inputTokens===void 0?{}:{inputTokens:r.inputTokens},...r.outputTokens===void 0?{}:{outputTokens:r.outputTokens},...o===void 0?{}:{cost:o}},a}function ct(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function lt(e){let t=e.lastIndexOf(`:`);return{file:e.slice(0,t),start:Number(e.slice(t+1))}}function ut(e){let{file:t,start:n}=lt(e);return ct(t,n)}function J(e,t){if(e.length<2)return;let n=new Map(e.map(e=>[e,t(e)]));e.sort((e,t)=>n.get(e).localeCompare(n.get(t)))}function dt(e,t){let n=Array(e.length),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map;for(let e of t){let t=i.get(e.component)??[];t.push(e),i.set(e.component,t)}e.forEach((e,t)=>{let a=i.get(e.component)?.shift();a&&(n[t]=a,r.add(a))});let a=t.filter(e=>!r.has(e)),o=0;return e.forEach((e,t)=>{n[t]===void 0&&o<a.length&&(n[t]=a[o++])}),n}function ft(t,n){let r=(/* @__PURE__ */ new Date()).toISOString(),i=Object.values(t.entries),a=/* @__PURE__ */ new Map;for(let e of i){let t=a.get(e.fingerprint)??[];t.push(e),a.set(e.fingerprint,t)}let o=/* @__PURE__ */ new Map;for(let e of n){let t=o.get(e.fingerprint)??[];t.push(e),o.set(e.fingerprint,t)}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=[];for(let[e,n]of o){let i=a.get(e)??[],o=i.filter(e=>e.status===`active`),u=i.filter(e=>e.status===`orphaned`);J(n,e=>ct(e.file,e.start)),J(o,e=>ut(e.location)),J(u,e=>ut(e.location)),n.length!==o.length&&(n.length>1||o.length>1)&&l.push(n[0].source);let d=dt(n,o),p=n.flatMap((e,t)=>d[t]===void 0?[t]:[]),m=dt(p.map(e=>n[e]),u);p.forEach((e,t)=>{d[e]=m[t]});for(let[e,i]of n.entries()){let n=d[e];if(n)s.set(i,n.id),n.status=`active`,n.lastSeen=r,n.source=i.source,n.component=i.component,n.autoPlural=i.autoPlural,n.hint=i.hint,n.location=`${i.file}:${i.start}`,c.add(n.id);else{let e=`msg_${f().replaceAll(`-`,``).slice(0,16)}`;s.set(i,e),t.entries[e]={id:e,source:i.source,component:i.component,fingerprint:i.fingerprint,autoPlural:i.autoPlural,hint:i.hint,location:`${i.file}:${i.start}`,status:`active`,firstSeen:r,lastSeen:r},c.add(e)}}}for(let e of Object.values(t.entries))c.has(e.id)||(e.status=`orphaned`);return{registry:t,ambiguous:l,messages:n.map(t=>{let n=s.get(t);if(n===void 0)throw e(`no message ID was assigned to ${t.file}:${t.start}`);return{...t,id:n}})}}function pt(e,t,n=Date.now()){let r=n-t*6e4,i=[];for(let[t,n]of Object.entries(e.entries))n.status===`orphaned`&&Date.parse(n.lastSeen)<=r&&(delete e.entries[t],i.push(n));return i}const mt=()=>({messages:{},sources:{}});function Y(t,n){if(!fe.test(n))throw e(`"${n}" is not a valid locale tag.`);return c.join(t,`${n}.json`)}const ht=(e,t,n)=>{let i={};for(let[a,o]of Object.entries(e))typeof o==`string`?i[a]=o:t?.(r(`dropped non-text value for "${a}" in ${n}.`));return i};async function gt(e,t){let n=await Ue(e,null,t),r=P(se,n);return r.ok?{messages:ht(r.value.messages,t,e),sources:ht(r.value.sources,t,e)}:mt()}const _t=(e,t)=>Ge(e,Ve(t));function vt(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))t.has(i)?n[i]=a:r.push(i);return{catalog:n,removed:r}}function yt(e,t){let n=vt(e.messages,t),r=vt(e.sources,t);return{file:{messages:n.catalog,sources:r.catalog},removed:[.../* @__PURE__ */ new Set([...n.removed,...r.removed])]}}async function bt(e,t){let n=await Ue(e,null,t);if(n===null)return ot();let i=P(ue,n);if(!i.ok)return t?.(r(`${e} has an unsupported format; message IDs will be regenerated.`)),ot();let a={};for(let[n,o]of Object.entries(i.value.entries)){let i=P(ce,o);i.ok?a[n]=i.value:t?.(r(`dropped invalid registry entry "${n}" in ${e}.`))}let o={};for(let[n,a]of Object.entries(i.value.costs??{})){let i=P(le,a);i.ok?o[n]=i.value:t?.(r(`dropped invalid cost record "${n}" in ${e}.`))}return{version:1,entries:a,costs:o}}async function xt(e,t){await Ge(e,Ve(t))}const X=e=>console.log(`[${t} debug] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);async function St(e){let{provider:t,sourceLocale:n,locale:r,requests:a,previous:o,debug:s,costs:c}=e,{messages:l,sources:u}=yt(o,new Set(a.map(e=>e.id))).file,d=a.filter(e=>!Object.hasOwn(l,e.id)||u[e.id]!==e.source),f={},p=0,m,h=[];if(d.length&&t){if(s===!0)for(let e of d)X(`sent ${n} -> ${r} ${e.id}: ${JSON.stringify(e.source)} (context: ${e.context})`);let e=c===!0?e=>{h.push(e),rt(n,r,e)}:void 0;try{f=await t.translate({sourceLocale:n,targetLocale:r,messages:d,...e===void 0?{}:{onUsage:e}})}catch(e){if(!qe(e))throw e;f=e.partial,p=e.failed,m=e.message}if(c===!0&&h.length===0&&it(n,r,Object.keys(f).length),s===!0)for(let e of d){let t=f[e.id];X(`received ${n} -> ${r} ${e.id}: ${typeof t==`string`?JSON.stringify(t):`(no translation)`}`)}}let g={...l},_={...u};for(let e of d){delete g[e.id],delete _[e.id];let t=f[e.id];if(e.autoPlural===!0&&!(typeof t==`string`&&t.includes(`{count`)&&t.includes(`, plural,`)&&t.includes(`other`)))continue;let n=e.autoPlural===!0?[`count`]:[];typeof t==`string`&&t.trim()&&i(e.source,t,n)&&(g[e.id]=t,_[e.id]=e.source)}let v=a.filter(e=>!Object.hasOwn(g,e.id)).length;return{file:{messages:g,sources:_},untranslated:v,requested:d.length,failed:p,failure:m,calls:h}}async function Ct(e){let t=structuredClone(e.registry),{ambiguous:n,messages:r}=ft(t,e.files.flatMap(e=>e.messages)),i=pt(t,e.orphanRetentionMinutes),a={};for(let e of r)a[e.id]=e.source;let o=r.map(e=>({id:e.id,source:e.source,context:e.component,autoPlural:e.autoPlural,hint:e.hint})),s=o.some(e=>e.hint!==void 0)&&!e.locales.includes(e.sourceLocale)?[...e.locales,e.sourceLocale]:e.locales,c=await Qe(s,e.localeConcurrency,t=>St({provider:e.provider,sourceLocale:e.sourceLocale,locale:t,requests:t===e.sourceLocale?o.filter(e=>e.hint!==void 0):o,previous:e.previous.get(t)??mt(),debug:e.debug,costs:e.costs})),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;return c.forEach((n,r)=>{let i=s[r];if(n.status===`fulfilled`){l.set(i,n.value);for(let r of n.value.calls)st(t,e.sourceLocale,i,r);if(i===e.sourceLocale)for(let[e,t]of Object.entries(n.value.file.messages))a[e]=t}else u.set(i,n.reason)}),{registry:t,ambiguous:n,pruned:i,messages:r,sourceFile:{messages:a,sources:{}},locales:l,failures:u}}async function Z(e){try{let t=await ee(e);return`${t.mtimeMs}:${t.size}`}catch{return}}var Q=class{entries=/* @__PURE__ */ new Map;async read(e,t){let n=await Z(e),r=this.entries.get(e);if(n!==void 0&&r?.stamp===n)return r.value;let i=await t();return n!==void 0&&this.entries.set(e,{stamp:n,value:i,written:!1}),i}async holds(e,t,n){let r=this.entries.get(e);return r?.written!==!0||!n(r.value,t)?!1:await Z(e)===r.stamp}async write(e,t,n){await n();let r=await Z(e);r!==void 0&&this.entries.set(e,{stamp:r,value:t,written:!0})}};function $(e,t){if(!e)return!1;let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>e[n]===t[n])}function wt(e,t){return $(e.messages,t.messages)&&$(e.sources,t.sources)}var Tt=class{extractions=/* @__PURE__ */ new Map;fileMessages=/* @__PURE__ */ new Map;catalogs=/* @__PURE__ */ new Map;catalogFiles={};warnedFiles=/* @__PURE__ */ new Set;legacySidecarsRemoved=!1;locales=new Q;registries=new Q;hashOf(e){return this.extractions.get(e)?.hash}readLocale(e,t){return this.locales.read(e,()=>gt(e,t))}async writeLocale(e,t){if(!await this.locales.holds(e,t,wt))return this.locales.write(e,t,()=>_t(e,t))}readRegistry(e,t){return this.registries.read(e,()=>bt(e,t))}writeRegistry(e,t){return this.registries.write(e,t,()=>xt(e,t))}};const Et=[`src/**/*.{tsx,jsx,ts,js,svelte,astro}`],Dt=[`**/*.test.*`,`**/node_modules/**`],Ot=e=>({info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t)});async function kt(e,t){await Promise.all(t.map(t=>y(c.join(e,`${t}.sources.json`),{force:!0})))}var At=class{options;sourceLocale;locales;delivery;state=new Tt;provider;directory;debug;costs;orphanRetentionMinutes;include;exclude;activeReport;config;queue=Promise.resolve();constructor(e){this.options=e,this.sourceLocale=e.sourceLocale??`en`,this.locales=e.locales,this.directory=e.directory??`.i18n-works`,this.delivery=e.delivery??`build`,this.debug=e.debug??!1,this.costs=e.costs??!1,this.orphanRetentionMinutes=e.orphanRetentionMinutes??43200,this.include=e.include??Et,this.exclude=e.exclude??Dt,this.provider=Ze(e.provider,e=>this.activeReport?.warn(e))}attach(e){this.config=e}explicitLocale(){return this.options.locale??process.env.I18N_WORKS_LOCALE}selectedLocale(){return this.explicitLocale()??this.sourceLocale}isServing(){return this.config.command===`serve`}localesDir(){return c.resolve(this.config.root,this.directory,`locales`)}registryFile(){return c.resolve(this.config.root,this.directory,`registry.json`)}isSourceCandidate(e){if(!/\.(?:[jt]sx?|svelte|astro)$/.test(e))return!1;let t=c.relative(this.config.root,e).split(c.sep).join(`/`);return this.include.some(e=>c.matchesGlob(t,e))&&!this.exclude.some(e=>c.matchesGlob(t,e))}localesToTranslate(){let e=this.locales.filter(e=>e!==this.sourceLocale),t=this.explicitLocale();return this.delivery===`build`&&t!==void 0&&t!==``&&!this.isServing()?e.filter(e=>e===t):e}async collectFiles(){let e=[];for await(let t of h(this.include,{cwd:this.config.root,exclude:this.exclude}))e.push(c.resolve(this.config.root,t));return e}async extractFiles(e,t,n){let r=await Qe(e,16,e=>this.extractFile(e,t,n)),i=/* @__PURE__ */ new Map,a=[];return e.forEach((e,t)=>{let n=r[t];if(n.status===`rejected`)throw n.reason;i.set(e,n.value),a.push({file:e,messages:n.value.messages})}),{nextExtractions:i,indexed:a}}async extractFile(e,t,n){let r=this.state.extractions.get(e);if(r&&t&&e!==n)return r;let i=await _(e,`utf8`),a=He(i);return r?.hash===a?r:{hash:a,messages:Be(i,e)}}reportLocales(e,t){for(let[n,i]of t.locales){if(i.requested>0&&!this.provider&&this.options.failOnMissingProvider===!0&&e.error(`Missing ${i.requested} ${n} translations and no provider is configured. Add a provider to ${R}, for example provider: hosted(HostedService.OpenAI, apiKey), or set failOnMissingProvider to false.`),i.untranslated){let t=this.provider?e.warn:e.info,a=this.provider?``:` No provider is configured; add one to ${R} to translate them.`;t(r(`${i.untranslated} ${n} messages have no translation and fall back to the source text.${a}`))}i.failed&&e.warn(r(`${i.failed} ${n} translation batches failed (${i.failure}); they will be requested again on the next build.`))}}async sync(e,t){let n=this.state,i=this.sourceLocale;this.activeReport=e;let a=t!==void 0&&n.extractions.has(t),o=a?[...n.extractions.keys()]:await this.collectFiles(),{nextExtractions:s,indexed:c}=await this.extractFiles(o,a,t),l=this.localesDir(),u=this.localesToTranslate(),d=[i,...u],[f,...p]=await Promise.all([n.readRegistry(this.registryFile(),e.warn),...d.map(t=>n.readLocale(Y(l,t),e.warn))]),m=new Map(d.map((e,t)=>[e,p[t]])),h=await Ct({files:c,registry:f,orphanRetentionMinutes:this.orphanRetentionMinutes,sourceLocale:i,locales:u,localeConcurrency:Math.max(1,Math.floor(this.options.localeConcurrency??2)),previous:m,provider:this.provider,debug:this.debug,costs:this.costs});if(this.debug)for(let e of h.pruned)X(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);if(h.pruned.length&&e.info(r(`removed ${h.pruned.length} registry entries no longer in the source.`)),await n.writeRegistry(this.registryFile(),h.registry),h.ambiguous.length){let t=r(`${h.ambiguous.length} duplicated texts changed occurrence count, so their IDs may have moved (e.g. "${h.ambiguous[0]}").`);this.options.onAmbiguous===`error`?e.error(t):e.warn(t)}await n.writeLocale(Y(l,i),h.sourceFile),n.legacySidecarsRemoved||=(await kt(l,[i,...this.locales]),!0),await Promise.all([...h.locales].map(([e,t])=>n.writeLocale(Y(l,e),t.file)));let g=/* @__PURE__ */ new Map([[i,h.sourceFile.messages]]);for(let[e,t]of h.locales)g.set(e,t.file.messages);for(let e of h.failures.keys())g.set(e,m.get(e)?.messages??{});let _=[...g].filter(([e,t])=>!$(n.catalogs.get(e),t)).map(([e])=>e),v=0;n.fileMessages=/* @__PURE__ */ new Map;for(let{file:e,messages:t}of c)n.fileMessages.set(e,h.messages.slice(v,v+t.length)),v+=t.length;n.extractions=s,n.catalogs=g,n.catalogFiles=Object.fromEntries(this.locales.map(e=>[e,Y(l,e)])),this.reportLocales(e,h),h.messages.length&&e.info(r(`indexed ${h.messages.length} messages across ${o.length} files.`));let y=[...h.failures];for(let[t,n]of y.slice(1))e.warn(r(`${t} translation failed: ${n.message}`));if(y.length)throw y[0][1];return _}runSync(e,t){let n=this.queue.then(()=>this.sync(e,t));return this.queue=n.then(()=>void 0,()=>void 0),n}};export{me as C,ae as D,re as E,oe as O,R as S,ie as T,Pe as _,yt as a,Ne as b,_t as c,pt as d,$e as f,He as g,Ke as h,bt as i,P as k,at as l,Ze as m,Ot as n,gt as o,Je as p,X as r,xt as s,At as t,lt as u,G as v,he as w,ge as x,W as y};
package/llms.txt CHANGED
@@ -63,21 +63,49 @@ export default defineConfig({
63
63
 
64
64
  ### Runtime API (`virtual:i18n-works`, runtime delivery only)
65
65
 
66
- ```tsx
66
+ ```ts
67
67
  import { getLocale, getVersion, locales, resolveSupported, setLocale, subscribe } from "virtual:i18n-works";
68
68
 
69
69
  setLocale(resolveSupported(navigator.languages)); // call before the first render
70
- // In a component: re-render when the locale or any catalogue changes
70
+ // React: re-render when the locale or any catalogue changes
71
71
  useSyncExternalStore(subscribe, getVersion, getVersion);
72
72
  ```
73
73
 
74
+ - Solid: `const [version, setVersion] = createSignal(getVersion()); const off = subscribe(() => setVersion(getVersion())); onCleanup(off);` and read `version()` in the component.
75
+ - Svelte: `export const version = readable(getVersion(), (set) => subscribe(() => set(getVersion())));` and read `$version` in markup.
76
+ - Astro: runtime delivery is not verified. Use build delivery, which renders one locale per bundle.
74
77
  - `locales`: the codes this build ships. `getLocale()`: current code. `subscribe(fn)`: returns an unsubscribe function. `getVersion()`: changes on any locale or catalogue change.
75
78
  - `setLocale(code)` is async and loads the catalogue for that code.
76
79
  - If the build has module-level `t()` calls (outside any function), the locale is stored in `localStorage` (`i18n-works:locale`) and applied before any module runs (top-level await). `setLocale(code)` then saves the choice and reloads the page. Do not call `setLocale` at startup in that case, because it overwrites the saved choice. The build target must support top-level await.
77
- - Memoized components (`memo`) must subscribe themselves, or they keep old text until their props change.
80
+ - React memoized components (`memo`) must subscribe themselves, or they keep old text until their props change.
78
81
  - Add a type declaration for `virtual:i18n-works` in a `.d.ts` file if TypeScript reports it missing. The example app has one at `example/src/i18n-works-virtual.d.ts`.
79
82
  - `tpick`, `createLocaleLoader` and `resolveLocale` are also exported from the `i18n-works/tools` subpath, which holds only the browser-safe runtime helpers, so plugin code stays out of client bundles. Import `tpick` from there in client code. `tpick(variable, options, fallback = "other")` returns the option whose key equals the value of a single variable, for example `tpick({ status }, { online: t("Online"), other: t("Unknown") })`.
80
83
 
84
+ ## Frameworks
85
+
86
+ The plugin is not tied to React. It reads these source files:
87
+
88
+ | Files | Framework | Parser |
89
+ | ------------------------ | --------- | --------------------------------------------------------------------------------------- |
90
+ | `.tsx`, `.jsx`, `.ts`, `.js` | React, Solid | Built in (Oxc). |
91
+ | `.svelte` | Svelte | `svelte` 5 compiler, an optional peer dependency. Its `<script>` and `<script module>` blocks and markup are scanned. |
92
+ | `.astro` | Astro | `@astrojs/compiler`, an optional peer dependency. Frontmatter, markup and `{}` expressions are scanned. |
93
+
94
+ - Install `svelte` or `@astrojs/compiler` only for the files you use. Astro 7 does not install `@astrojs/compiler`, so add it to Astro projects. A missing compiler fails the build with the package name.
95
+ - Tested versions (full table in `reference/framework-support`): Vite 8.0.0 to 8.4.1 on Node.js 26.7.0; React 19.0.0 to 19.3.1; Svelte 5.46.4 to 5.60.2 with `@sveltejs/vite-plugin-svelte` 7.0.0 to 7.3.3; `solid-js` 1.9.16 to 1.9.20 with `vite-plugin-solid` 2.11.17; Astro 7.0.0 to 7.4.14 with `@astrojs/compiler` 4.0.0 (build delivery only). Untested: Solid 2.x, Svelte 4, Astro 6 and earlier, and two frameworks in one project.
96
+ - Svelte: a `t()` call in the instance script is named after the component file, and one in `<script module>` is named `<module>`.
97
+ - Astro: `t()` in frontmatter and in markup is supported. Expressions that contain nested HTML with void tags such as `<br>` cannot be parsed as JavaScript, so move that markup out of the expression.
98
+ - Only files that import `t` from `virtual:i18n-works` are parsed, so Svelte and Astro files without the import are unchanged.
99
+
100
+ ```ts
101
+ // vite.config.ts for Svelte
102
+ import { svelte } from "@sveltejs/vite-plugin-svelte";
103
+ import i18nWorks from "i18n-works";
104
+ import { defineConfig } from "vite";
105
+
106
+ export default defineConfig({ plugins: [i18nWorks(), svelte()] });
107
+ ```
108
+
81
109
  ## What is extracted
82
110
 
83
111
  Only string literals passed to `t("...")`, imported from `virtual:i18n-works`, with an optional second argument of values. Variables, template literals, and spread values are not extracted. Values use ICU MessageFormat, for example `t("{count, plural, one {# file} other {# files}}", { count })`. A message that is not valid ICU fails the build. At runtime `t(source, values)` formats its source and otherwise returns it unchanged.
@@ -99,7 +127,7 @@ const items = [{ label: t("Shared with your team") }, { label: "Private" }]; //
99
127
  | `sourceLocale` | `"en"` | Language the `t()` strings are written in. Fallback when a translation is missing. |
100
128
  | `delivery` | `"build"` | `"build"` or `"runtime"`. |
101
129
  | `locale` | `sourceLocale` | Locale compiled in build delivery. `I18N_WORKS_LOCALE` is also read; this option wins. |
102
- | `include` | `["src/**/*.{tsx,jsx,ts,js}"]` | Globs of source files to scan, relative to the Vite root. |
130
+ | `include` | `["src/**/*.{tsx,jsx,ts,js,svelte,astro}"]` | Globs of source files to scan, relative to the Vite root. |
103
131
  | `exclude` | `["**/*.test.*", "**/node_modules/**"]` | Globs of files to skip. |
104
132
  | `directory` | `".i18n-works"` | Folder for `registry.json` and `locales/`. |
105
133
  | `provider` | `undefined` | One provider, or a map `{ primary?, [name]: provider \| undefined }`. `undefined` entries are skipped. |
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "i18n-works",
3
- "version": "0.1.8",
4
- "description": "Build-time AI localization for strings marked with t() in React applications",
3
+ "version": "0.1.9",
4
+ "description": "Build-time AI localization for strings marked with t() in React, Solid, Svelte and Astro applications",
5
5
  "keywords": [
6
6
  "ai",
7
+ "astro",
7
8
  "i18n",
8
9
  "internationalization",
9
10
  "localization",
10
- "react-i18n",
11
+ "react",
11
12
  "rolldown",
13
+ "solid",
14
+ "svelte",
12
15
  "translation",
13
16
  "vite",
14
17
  "vite-plugin"
@@ -74,21 +77,33 @@
74
77
  "magic-string": "^1.4.5"
75
78
  },
76
79
  "devDependencies": {
80
+ "@astrojs/compiler": "4.0.0",
77
81
  "@types/node": "26.6.11",
78
82
  "@vitest/coverage-v8": "5.1.2",
79
83
  "eslint-plugin-import": "^2.32.0",
80
84
  "eslint-plugin-unused-imports": "^4.4.1",
81
85
  "rolldown": "1.3.4",
82
86
  "rollup-plugin-visualizer": "7.3.0",
87
+ "svelte": "5.60.2",
83
88
  "tsdown": "0.23.8",
84
89
  "typescript": "^7.1.0-beta",
85
90
  "vite": "8.4.1",
86
91
  "vitest": "5.1.2"
87
92
  },
88
93
  "peerDependencies": {
94
+ "@astrojs/compiler": "^4.0.0",
89
95
  "rolldown": ">=1.4.0",
96
+ "svelte": ">=5.46.4",
90
97
  "vite": ">=8.0.0"
91
98
  },
99
+ "peerDependenciesMeta": {
100
+ "@astrojs/compiler": {
101
+ "optional": true
102
+ },
103
+ "svelte": {
104
+ "optional": true
105
+ }
106
+ },
92
107
  "engines": {
93
108
  "node": ">=26.0.0"
94
109
  },
@@ -1,7 +0,0 @@
1
- import{a as e,i as t,n,o as r,r as i}from"./icu-Cui2dM71.js";import{existsSync as a}from"node:fs";import{loadConfigFromFile as o}from"vite";import s from"node:path";import{createHash as c,randomUUID as l}from"node:crypto";import{parseSync as u}from"rolldown/utils";import d from"magic-string";import{glob as f,mkdir as p,readFile as m,rename as h,rm as g,stat as _,writeFile as v}from"node:fs/promises";const y=Symbol(`failed`),b=(e,t)=>(e.push({path:[],message:t}),y),ee=(e,t,n,r)=>{let i=r.length,a=e.check(t,r);if(a===y)for(let e=i;e<r.length;e++)r[e]={path:[n,...r[e].path],message:r[e].message};return a},x=e=>`must be ${e}`,S=(e,t)=>({expected:e,check:(n,r)=>t(n)?n:b(r,x(e))}),C=S(`a string`,e=>typeof e==`string`),w=S(`a finite number`,e=>typeof e==`number`&&Number.isFinite(e)),T=S(`a boolean`,e=>typeof e==`boolean`),E=S(`an object`,e=>typeof e==`object`&&!!e||typeof e==`function`);function D(e){let t=typeof e==`string`?JSON.stringify(e):String(e);return S(t,t=>t===e)}function O(e,t,n){return{expected:n,check:(r,i)=>{let a=e.check(r,i);return a===y?y:t(a)?a:b(i,x(n))}}}function k(e,{nonEmpty:t=!1}={}){let n=t?`a non-empty array`:`an array`;return{expected:n,check:(r,i)=>{if(!Array.isArray(r)||t&&r.length===0)return b(i,x(n));let a=!1,o=[];for(let[t,n]of r.entries()){let r=ee(e,n,t,i);r===y?a=!0:o.push(r)}return a?y:o}}}function A(...e){let t=e.map(e=>e.expected).join(` or `);return{expected:t,check:(n,r)=>{for(let t of e){let e=t.check(n,[]);if(e!==y)return e}return b(r,x(t))}}}function j(e){return{...e,optional:!0}}function M(e,t=`ignore`){let n=Object.entries(e),r=new Set(Object.keys(e));return{expected:`an object`,check:(e,i)=>{let a=E.check(e,i);if(a===y)return y;let o=!1,s={};for(let[e,t]of n){if(!Object.hasOwn(a,e)){t.optional!==!0&&(i.push({path:[e],message:`is required`}),o=!0);continue}let n=ee(t,a[e],e,i);n===y?o=!0:s[e]=n}if(t===`reject`)for(let e of Object.keys(a))r.has(e)||(i.push({path:[e],message:`is not a known key`}),o=!0);return o?y:s}}}function N(e,t){let n=[],r=e.check(t,n);return r===y?{ok:!1,issues:n}:{ok:!0,value:r}}const P=e=>j(A(e,D(void 0))),F=j(A(w,D(null))),te=M({choices:k(M({message:M({content:j(A(C,D(null)))})}),{nonEmpty:!0}),usage:j(A(M({prompt_tokens:F,completion_tokens:F}),D(null)))}),ne=M({content:k(M({type:C,text:j(C)})),usage:j(A(M({input_tokens:F,output_tokens:F}),D(null)))}),re=M({candidates:k(M({content:j(M({parts:j(k(M({text:j(C)})))}))})),usageMetadata:j(A(M({promptTokenCount:F,candidatesTokenCount:F}),D(null)))}),ie=E,ae=M({messages:E,sources:E}),oe=M({id:C,source:C,component:C,fingerprint:C,autoPlural:P(T),hint:P(C),location:C,status:A(D(`active`),D(`orphaned`)),firstSeen:C,lastSeen:C}),se=M({id:C,at:C,sourceLocale:C,locale:C,provider:C,model:C,ids:k(C),inputTokens:P(w),outputTokens:P(w),cost:P(w)}),ce=M({version:D(1),entries:E,costs:j(E)}),le=O(C,e=>e.length>0,`a non-empty string`),ue=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,I=O(C,e=>ue.test(e),`a locale tag`),de=M({locales:k(I),sourceLocale:P(I),delivery:P(A(D(`build`),D(`runtime`))),locale:P(I),include:P(k(C)),exclude:P(k(C)),directory:P(le),provider:P(E),failOnMissingProvider:P(T),onAmbiguous:P(A(D(`warn`),D(`error`))),orphanRetentionMinutes:P(A(O(w,e=>e>=0,`a number >= 0`),D(1/0))),localeConcurrency:P(O(w,e=>e>=1,`a number >= 1`)),debug:P(T),costs:P(T)},`reject`),L=`vite-i18n.config.js`;function fe(e){return s.resolve(e,L)}function pe(t){let n=N(de,t);if(n.ok)return;let r=n.issues.map(e=>`${e.path.join(`.`)||`options`}: ${e.message}`).join(`; `);throw e(`invalid options in ${L} (${r}). Fix or remove these keys; the README lists every option.`)}const me=async(t,n)=>{let r=fe(t);if(!a(r))throw e(`${L} was not found in ${t}. Create it next to vite.config with the plugin options as the default export, for example:\n\n export default {
2
- locales: ["en", "de"],
3
- sourceLocale: "en",
4
- };\n\nThe README lists every option.`);try{return(await o(n,r,t))?.config}catch(t){let n=t instanceof Error?t.message:String(t);throw e(`could not load ${L}: ${n}. Check the file for syntax errors and make sure it has a default export that is an object.`)}};function R(e){return e.replace(/\s+/g,` `).trim()}function he(e){let t=e.autoPlural===!0?`tt`:`t`;return c(`sha256`).update(`${t}\u0000${R(e.source)}\u0000${R(e.hint??``)}`).digest(`hex`).slice(0,24)}function ge(e,t){let n=u(t,e,{lang:`tsx`,sourceType:`unambiguous`});if(n.errors.length)throw SyntaxError(`${t}: ${n.errors[0].message}`);return{program:n.program}}function _e(e,t){let n=[],r=e=>{if(t(e,n)!==!1){n.push(e);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];Array.isArray(n)?n.forEach(e=>z(e)&&r(e)):z(n)&&r(n)}n.pop()}};r(e)}function z(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function B(e){return z(e)&&e.type===`Literal`&&typeof e.value==`string`}const V=`virtual:i18n-works`,H=`i18n-works/runtime`,U=`__i18nWorksT`,W=`__i18nWorksFormat`,G=`__i18nWorksFormatAutoPlural`,ve=String.raw`\s*(["'])[^"'\n]*\1[ \t]*;?[ \t]*(?:\r?\n|$)`,K=new RegExp(ve,`y`);function ye(e){let t=0;if(e.startsWith(`#!`)){let n=e.indexOf(`
5
- `);t=n===-1?e.length:n+1}K.lastIndex=t;for(let n=K.exec(e);n;n=K.exec(e))t=K.lastIndex;return t}function be(e,t,n,r,i,a=!1,o=`en`,s=!0){let c=new d(e),l=e=>r===o&&e.hint===void 0?e.source:i[e.id]??e.source;for(let e of n){if(e.valuesStart===void 0){let t=a?`${U}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)})`:JSON.stringify(l(e));c.overwrite(e.start,e.end,t);continue}let t;t=a&&e.autoPlural===!0?`__i18nWorksLookupAutoPlural(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:a?`${U}(${JSON.stringify(e.id)}, ${JSON.stringify(e.source)}, `:e.autoPlural===!0?`${G}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `:`${W}(${JSON.stringify(l(e))}, ${JSON.stringify(r)}, `,c.overwrite(e.start,e.valuesStart,t)}let u=[];return a&&n.length&&u.push(`import { lookup as ${U} } from "${V}";`),a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { lookupAutoPlural as __i18nWorksLookupAutoPlural } from "${V}";`),!a&&n.some(e=>e.valuesStart!==void 0)&&u.push(`import { formatMessage as ${W} } from "${H}";`),!a&&n.some(e=>e.autoPlural===!0)&&u.push(`import { formatAutoPluralMessage as ${G} } from "${H}";`),u.length&&c.appendLeft(ye(e),`${u.join(`
6
- `)}\n`),{code:c.toString(),map:s?c.generateMap({source:t,hires:!0,includeContent:!1}):null}}const q=`<module>`,xe=e=>/[A-Za-z]/.test(e);function Se(e,t){try{n(e)}catch(e){throw SyntaxError(`${t}: t() message is not valid ICU MessageFormat: ${e.message}`,{cause:e})}}function Ce(e){let t={t:/* @__PURE__ */ new Set,tt:/* @__PURE__ */ new Set,tauto:/* @__PURE__ */ new Set};if(e.type!==`Program`)return t;for(let n of e.body)if(n.type===`ImportDeclaration`&&n.source.value===`virtual:i18n-works`)for(let e of n.specifiers){if(e.type!==`ImportSpecifier`)continue;let n=e.imported.type===`Identifier`?e.imported.name:e.imported.value;n===`t`&&t.t.add(e.local.name),n===`tt`&&t.tt.add(e.local.name),n===`tauto`&&t.tauto.add(e.local.name)}return t}const we=(e,t)=>e.type===`FunctionExpression`?!(t?.type===`MethodDefinition`||t?.type===`Property`&&(t.method||t.kind!==`init`)):e.type===`FunctionDeclaration`||e.type===`ArrowFunctionExpression`;function Te(e){let t=e.length-1;for(;t>=0&&!we(e[t],e[t-1]);)t--;if(t<0)return q;let n=e[t],r=t>0?e[t-1]:void 0;return r?.type===`VariableDeclarator`&&r.id.type===`Identifier`?r.id.name:n.type===`FunctionDeclaration`&&n.id?n.id.name:`<anonymous>`}function Ee(e,t,n){if(n===void 0&&!e.includes(`virtual:i18n-works`))return[];let{program:r}=n??ge(e,t),i=Ce(r),a=[];return _e(r,(e,n)=>{if(e.type!==`CallExpression`||e.callee.type!==`Identifier`)return;let r=i.tt.has(e.callee.name),o=r||i.tauto.has(e.callee.name);if(!o&&!i.t.has(e.callee.name))return;let s=i.tauto.has(e.callee.name)&&B(e.arguments.at(1));if(e.arguments.length>(o&&!s?3:2))return;let[c]=e.arguments,l=s?void 0:e.arguments.at(1),u=o?e.arguments.at(s?1:2):void 0;if(!B(c)||l?.type===`SpreadElement`||u!==void 0&&!B(u))return;let d=R(c.value);if(!d||!xe(d))return;l&&Se(d,t);let f=B(u)?R(u.value):void 0;a.push({source:d,file:t,start:e.start,end:e.end,valuesStart:l?.start,autoPlural:r||void 0,hint:f!==void 0&&f.length>0?f:void 0,component:Te(n),fingerprint:he({source:d,autoPlural:r,hint:f})})}),a.sort((e,t)=>e.start-t.start)}const De=e=>JSON.stringify(e,null,2)+`
7
- `,Oe=e=>c(`sha256`).update(e).digest(`hex`);async function ke(e,t,n){let i;try{i=await m(e,`utf8`)}catch(i){return i.code===`ENOENT`||n?.(r(`could not read ${e}: ${i.message}`)),t}try{return JSON.parse(i)}catch(i){let a=`${e}.corrupt-${Date.now()}`;return await h(e,a).catch(()=>void 0),n?.(r(`${e} is not valid JSON (${i.message}); moved to ${a} and starting fresh.`)),t}}async function Ae(e,t){await p(s.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${l()}.tmp`;await v(n,t,`utf8`),await h(n,e)}async function je(e,t){await m(e,`utf8`).catch(()=>void 0)!==t&&await Ae(e,t)}var Me=class extends Error{partial;failed;constructor(e,t,n){super(e),this.partial=t,this.failed=n,this.name=`PartialTranslationError`}};function Ne(e){return e instanceof Error&&e.name===`PartialTranslationError`&&`partial`in e}var Pe=class{providers;onFallback;constructor(e,t=()=>{}){this.providers=e,this.onFallback=t}async translate(e){let t={},n=e.messages,r,i;for(let[a,{name:o,provider:s}]of this.providers.entries()){try{Object.assign(t,await s.translate({...e,messages:n}))}catch(e){r??=e,i=e,Ne(e)&&Object.assign(t,e.partial);let s=this.providers.at(a+1);s&&n.some(e=>!Object.hasOwn(t,e.id))&&this.onFallback(`${o} failed (${Fe(e)}); sending the rest to ${s.name}.`)}if(n=n.filter(e=>!Object.hasOwn(t,e.id)),!n.length)return t}throw Object.keys(t).length===0?r:new Me(`${n.length} messages failed to translate: ${Fe(i)}`,t,n.length)}};const Fe=e=>e instanceof Error?e.message:String(e),Ie=e=>typeof e==`object`&&!!e&&typeof e.translate==`function`;function Le(t,n){if(t===void 0)return;if(Ie(t))return t;let{primary:r,...i}=t,a=[];for(let[t,n]of Object.entries(i))if(n!==void 0){if(!Ie(n))throw e(`provider "${t}" must be an object with a translate(input) method. Use hosted(), local(), or a provider class exported by i18n-works.`);a.push({name:t,provider:n})}if(r!==void 0){let t=a.findIndex(e=>e.name===r);if(t<0)throw e(`primary provider "${r}" is not configured. Add it under provider in vite-i18n.config.js, or change primary to one of: ${a.map(e=>e.name).join(`, `)||`none`}.`);a.unshift(...a.splice(t,1))}if(a.length!==0)return a.length===1?a[0].provider:new Pe(a,n)}async function Re(e,t,n){let r=Array(e.length),i=0;return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},async()=>{for(;i<e.length;){let t=i++;try{r[t]={status:`fulfilled`,value:await n(e[t])}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var ze=class{available;waiters=[];constructor(e){this.available=Math.max(1,Math.floor(e))}async run(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.available>0?(this.available--,Promise.resolve()):new Promise(e=>this.waiters.push(e))}release(){let e=this.waiters.shift();e?e():this.available++}};const Be={anthropic:{"claude-haiku-5-5":{input:.1,output:.5},"claude-haiku-4-5":{input:1,output:5}},openai:{"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-5-mini":{input:.25,output:2},"gpt-5-nano":{input:.05,output:.4}}};function Ve(e){let t=Be[e.provider]?.[e.model];if(t!==void 0&&e.inputTokens!==void 0&&e.outputTokens!==void 0)return(e.inputTokens*t.input+e.outputTokens*t.output)/1e6}const He=e=>console.log(`[${t} costs] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);function Ue(e,t,n){let r=n.inputTokens===void 0||n.outputTokens===void 0?`tokens not reported`:`${n.inputTokens} input + ${n.outputTokens} output tokens`,i=Ve(n),a=i===void 0?`cost unknown`:`cost $${i.toFixed(6)}`;He(`${e} -> ${t} ${n.ids.length} messages (${n.ids.join(`, `)}) via ${n.provider} ${n.model}: ${r}, ${a}`)}function We(e,t,n){He(`${e} -> ${t} ${n} messages translated, provider reported no usage: cost unknown`)}const Ge=43200,Ke=()=>({version:1,entries:{},costs:{}});function qe(e,t,n,r,i=(/* @__PURE__ */ new Date()).toISOString()){let a=`call_${l().replaceAll(`-`,``).slice(0,16)}`,o=Ve(r);return e.costs[a]={id:a,at:i,sourceLocale:t,locale:n,provider:r.provider,model:r.model,ids:r.ids,...r.inputTokens===void 0?{}:{inputTokens:r.inputTokens},...r.outputTokens===void 0?{}:{outputTokens:r.outputTokens},...o===void 0?{}:{cost:o}},a}function Je(e,t){return`${e}:${String(t).padStart(12,`0`)}`}function Ye(e){let t=e.lastIndexOf(`:`);return{file:e.slice(0,t),start:Number(e.slice(t+1))}}function Xe(e){let{file:t,start:n}=Ye(e);return Je(t,n)}function J(e,t){if(e.length<2)return;let n=new Map(e.map(e=>[e,t(e)]));e.sort((e,t)=>n.get(e).localeCompare(n.get(t)))}function Ze(e,t){let n=Array(e.length),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map;for(let e of t){let t=i.get(e.component)??[];t.push(e),i.set(e.component,t)}e.forEach((e,t)=>{let a=i.get(e.component)?.shift();a&&(n[t]=a,r.add(a))});let a=t.filter(e=>!r.has(e)),o=0;return e.forEach((e,t)=>{n[t]===void 0&&o<a.length&&(n[t]=a[o++])}),n}function Qe(t,n){let r=(/* @__PURE__ */ new Date()).toISOString(),i=Object.values(t.entries),a=/* @__PURE__ */ new Map;for(let e of i){let t=a.get(e.fingerprint)??[];t.push(e),a.set(e.fingerprint,t)}let o=/* @__PURE__ */ new Map;for(let e of n){let t=o.get(e.fingerprint)??[];t.push(e),o.set(e.fingerprint,t)}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,u=[];for(let[e,n]of o){let i=a.get(e)??[],o=i.filter(e=>e.status===`active`),d=i.filter(e=>e.status===`orphaned`);J(n,e=>Je(e.file,e.start)),J(o,e=>Xe(e.location)),J(d,e=>Xe(e.location)),n.length!==o.length&&(n.length>1||o.length>1)&&u.push(n[0].source);let f=Ze(n,o),p=n.flatMap((e,t)=>f[t]===void 0?[t]:[]),m=Ze(p.map(e=>n[e]),d);p.forEach((e,t)=>{f[e]=m[t]});for(let[e,i]of n.entries()){let n=f[e];if(n)s.set(i,n.id),n.status=`active`,n.lastSeen=r,n.source=i.source,n.component=i.component,n.autoPlural=i.autoPlural,n.hint=i.hint,n.location=`${i.file}:${i.start}`,c.add(n.id);else{let e=`msg_${l().replaceAll(`-`,``).slice(0,16)}`;s.set(i,e),t.entries[e]={id:e,source:i.source,component:i.component,fingerprint:i.fingerprint,autoPlural:i.autoPlural,hint:i.hint,location:`${i.file}:${i.start}`,status:`active`,firstSeen:r,lastSeen:r},c.add(e)}}}for(let e of Object.values(t.entries))c.has(e.id)||(e.status=`orphaned`);return{registry:t,ambiguous:u,messages:n.map(t=>{let n=s.get(t);if(n===void 0)throw e(`no message ID was assigned to ${t.file}:${t.start}`);return{...t,id:n}})}}function $e(e,t,n=Date.now()){let r=n-t*6e4,i=[];for(let[t,n]of Object.entries(e.entries))n.status===`orphaned`&&Date.parse(n.lastSeen)<=r&&(delete e.entries[t],i.push(n));return i}const et=()=>({messages:{},sources:{}});function Y(t,n){if(!ue.test(n))throw e(`"${n}" is not a valid locale tag.`);return s.join(t,`${n}.json`)}const tt=(e,t,n)=>{let i={};for(let[a,o]of Object.entries(e))typeof o==`string`?i[a]=o:t?.(r(`dropped non-text value for "${a}" in ${n}.`));return i};async function nt(e,t){let n=await ke(e,null,t),r=N(ae,n);return r.ok?{messages:tt(r.value.messages,t,e),sources:tt(r.value.sources,t,e)}:et()}const rt=(e,t)=>je(e,De(t));function it(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))t.has(i)?n[i]=a:r.push(i);return{catalog:n,removed:r}}function X(e,t){let n=it(e.messages,t),r=it(e.sources,t);return{file:{messages:n.catalog,sources:r.catalog},removed:[.../* @__PURE__ */ new Set([...n.removed,...r.removed])]}}async function at(e,t){let n=await ke(e,null,t);if(n===null)return Ke();let i=N(ce,n);if(!i.ok)return t?.(r(`${e} has an unsupported format; message IDs will be regenerated.`)),Ke();let a={};for(let[n,o]of Object.entries(i.value.entries)){let i=N(oe,o);i.ok?a[n]=i.value:t?.(r(`dropped invalid registry entry "${n}" in ${e}.`))}let o={};for(let[n,a]of Object.entries(i.value.costs??{})){let i=N(se,a);i.ok?o[n]=i.value:t?.(r(`dropped invalid cost record "${n}" in ${e}.`))}return{version:1,entries:a,costs:o}}async function ot(e,t){await je(e,De(t))}const Z=e=>console.log(`[${t} debug] ${(/* @__PURE__ */ new Date()).toISOString()} ${e}`);async function st(e){let{provider:t,sourceLocale:n,locale:r,requests:a,previous:o,debug:s,costs:c}=e,{messages:l,sources:u}=X(o,new Set(a.map(e=>e.id))).file,d=a.filter(e=>!Object.hasOwn(l,e.id)||u[e.id]!==e.source),f={},p=0,m,h=[];if(d.length&&t){if(s===!0)for(let e of d)Z(`sent ${n} -> ${r} ${e.id}: ${JSON.stringify(e.source)} (context: ${e.context})`);let e=c===!0?e=>{h.push(e),Ue(n,r,e)}:void 0;try{f=await t.translate({sourceLocale:n,targetLocale:r,messages:d,...e===void 0?{}:{onUsage:e}})}catch(e){if(!Ne(e))throw e;f=e.partial,p=e.failed,m=e.message}if(c===!0&&h.length===0&&We(n,r,Object.keys(f).length),s===!0)for(let e of d){let t=f[e.id];Z(`received ${n} -> ${r} ${e.id}: ${typeof t==`string`?JSON.stringify(t):`(no translation)`}`)}}let g={...l},_={...u};for(let e of d){delete g[e.id],delete _[e.id];let t=f[e.id];if(e.autoPlural===!0&&!(typeof t==`string`&&t.includes(`{count`)&&t.includes(`, plural,`)&&t.includes(`other`)))continue;let n=e.autoPlural===!0?[`count`]:[];typeof t==`string`&&t.trim()&&i(e.source,t,n)&&(g[e.id]=t,_[e.id]=e.source)}let v=a.filter(e=>!Object.hasOwn(g,e.id)).length;return{file:{messages:g,sources:_},untranslated:v,requested:d.length,failed:p,failure:m,calls:h}}async function ct(e){let t=structuredClone(e.registry),{ambiguous:n,messages:r}=Qe(t,e.files.flatMap(e=>e.messages)),i=$e(t,e.orphanRetentionMinutes),a={};for(let e of r)a[e.id]=e.source;let o=r.map(e=>({id:e.id,source:e.source,context:e.component,autoPlural:e.autoPlural,hint:e.hint})),s=o.some(e=>e.hint!==void 0)&&!e.locales.includes(e.sourceLocale)?[...e.locales,e.sourceLocale]:e.locales,c=await Re(s,e.localeConcurrency,t=>st({provider:e.provider,sourceLocale:e.sourceLocale,locale:t,requests:t===e.sourceLocale?o.filter(e=>e.hint!==void 0):o,previous:e.previous.get(t)??et(),debug:e.debug,costs:e.costs})),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;return c.forEach((n,r)=>{let i=s[r];if(n.status===`fulfilled`){l.set(i,n.value);for(let r of n.value.calls)qe(t,e.sourceLocale,i,r);if(i===e.sourceLocale)for(let[e,t]of Object.entries(n.value.file.messages))a[e]=t}else u.set(i,n.reason)}),{registry:t,ambiguous:n,pruned:i,messages:r,sourceFile:{messages:a,sources:{}},locales:l,failures:u}}async function Q(e){try{let t=await _(e);return`${t.mtimeMs}:${t.size}`}catch{return}}var lt=class{entries=/* @__PURE__ */ new Map;async read(e,t){let n=await Q(e),r=this.entries.get(e);if(n!==void 0&&r?.stamp===n)return r.value;let i=await t();return n!==void 0&&this.entries.set(e,{stamp:n,value:i,written:!1}),i}async holds(e,t,n){let r=this.entries.get(e);return r?.written!==!0||!n(r.value,t)?!1:await Q(e)===r.stamp}async write(e,t,n){await n();let r=await Q(e);r!==void 0&&this.entries.set(e,{stamp:r,value:t,written:!0})}};function $(e,t){if(!e)return!1;let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>e[n]===t[n])}function ut(e,t){return $(e.messages,t.messages)&&$(e.sources,t.sources)}var dt=class{extractions=/* @__PURE__ */ new Map;fileMessages=/* @__PURE__ */ new Map;catalogs=/* @__PURE__ */ new Map;catalogFiles={};warnedFiles=/* @__PURE__ */ new Set;legacySidecarsRemoved=!1;locales=new lt;registries=new lt;hashOf(e){return this.extractions.get(e)?.hash}readLocale(e,t){return this.locales.read(e,()=>nt(e,t))}async writeLocale(e,t){if(!await this.locales.holds(e,t,ut))return this.locales.write(e,t,()=>rt(e,t))}readRegistry(e,t){return this.registries.read(e,()=>at(e,t))}writeRegistry(e,t){return this.registries.write(e,t,()=>ot(e,t))}};const ft=[`src/**/*.{tsx,jsx,ts,js}`],pt=[`**/*.test.*`,`**/node_modules/**`],mt=e=>({info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t)});async function ht(e,t){await Promise.all(t.map(t=>g(s.join(e,`${t}.sources.json`),{force:!0})))}var gt=class{options;sourceLocale;locales;delivery;state=new dt;provider;directory;debug;costs;orphanRetentionMinutes;include;exclude;activeReport;config;queue=Promise.resolve();constructor(e){this.options=e,this.sourceLocale=e.sourceLocale??`en`,this.locales=e.locales,this.directory=e.directory??`.i18n-works`,this.delivery=e.delivery??`build`,this.debug=e.debug??!1,this.costs=e.costs??!1,this.orphanRetentionMinutes=e.orphanRetentionMinutes??43200,this.include=e.include??ft,this.exclude=e.exclude??pt,this.provider=Le(e.provider,e=>this.activeReport?.warn(e))}attach(e){this.config=e}explicitLocale(){return this.options.locale??process.env.I18N_WORKS_LOCALE}selectedLocale(){return this.explicitLocale()??this.sourceLocale}isServing(){return this.config.command===`serve`}localesDir(){return s.resolve(this.config.root,this.directory,`locales`)}registryFile(){return s.resolve(this.config.root,this.directory,`registry.json`)}isSourceCandidate(e){if(!/\.[jt]sx?$/.test(e))return!1;let t=s.relative(this.config.root,e).split(s.sep).join(`/`);return this.include.some(e=>s.matchesGlob(t,e))&&!this.exclude.some(e=>s.matchesGlob(t,e))}localesToTranslate(){let e=this.locales.filter(e=>e!==this.sourceLocale),t=this.explicitLocale();return this.delivery===`build`&&t!==void 0&&t!==``&&!this.isServing()?e.filter(e=>e===t):e}async collectFiles(){let e=[];for await(let t of f(this.include,{cwd:this.config.root,exclude:this.exclude}))e.push(s.resolve(this.config.root,t));return e}async extractFiles(e,t,n){let r=await Re(e,16,e=>this.extractFile(e,t,n)),i=/* @__PURE__ */ new Map,a=[];return e.forEach((e,t)=>{let n=r[t];if(n.status===`rejected`)throw n.reason;i.set(e,n.value),a.push({file:e,messages:n.value.messages})}),{nextExtractions:i,indexed:a}}async extractFile(e,t,n){let r=this.state.extractions.get(e);if(r&&t&&e!==n)return r;let i=await m(e,`utf8`),a=Oe(i);return r?.hash===a?r:{hash:a,messages:Ee(i,e)}}reportLocales(e,t){for(let[n,i]of t.locales){if(i.requested>0&&!this.provider&&this.options.failOnMissingProvider===!0&&e.error(`Missing ${i.requested} ${n} translations and no provider is configured. Add a provider to ${L}, for example provider: hosted(HostedService.OpenAI, apiKey), or set failOnMissingProvider to false.`),i.untranslated){let t=this.provider?e.warn:e.info,a=this.provider?``:` No provider is configured; add one to ${L} to translate them.`;t(r(`${i.untranslated} ${n} messages have no translation and fall back to the source text.${a}`))}i.failed&&e.warn(r(`${i.failed} ${n} translation batches failed (${i.failure}); they will be requested again on the next build.`))}}async sync(e,t){let n=this.state,i=this.sourceLocale;this.activeReport=e;let a=t!==void 0&&n.extractions.has(t),o=a?[...n.extractions.keys()]:await this.collectFiles(),{nextExtractions:s,indexed:c}=await this.extractFiles(o,a,t),l=this.localesDir(),u=this.localesToTranslate(),d=[i,...u],[f,...p]=await Promise.all([n.readRegistry(this.registryFile(),e.warn),...d.map(t=>n.readLocale(Y(l,t),e.warn))]),m=new Map(d.map((e,t)=>[e,p[t]])),h=await ct({files:c,registry:f,orphanRetentionMinutes:this.orphanRetentionMinutes,sourceLocale:i,locales:u,localeConcurrency:Math.max(1,Math.floor(this.options.localeConcurrency??2)),previous:m,provider:this.provider,debug:this.debug,costs:this.costs});if(this.debug)for(let e of h.pruned)Z(`removed ${e.id} ${JSON.stringify(e.source)} (last seen ${e.lastSeen})`);if(h.pruned.length&&e.info(r(`removed ${h.pruned.length} registry entries no longer in the source.`)),await n.writeRegistry(this.registryFile(),h.registry),h.ambiguous.length){let t=r(`${h.ambiguous.length} duplicated texts changed occurrence count, so their IDs may have moved (e.g. "${h.ambiguous[0]}").`);this.options.onAmbiguous===`error`?e.error(t):e.warn(t)}await n.writeLocale(Y(l,i),h.sourceFile),n.legacySidecarsRemoved||=(await ht(l,[i,...this.locales]),!0),await Promise.all([...h.locales].map(([e,t])=>n.writeLocale(Y(l,e),t.file)));let g=/* @__PURE__ */ new Map([[i,h.sourceFile.messages]]);for(let[e,t]of h.locales)g.set(e,t.file.messages);for(let e of h.failures.keys())g.set(e,m.get(e)?.messages??{});let _=[...g].filter(([e,t])=>!$(n.catalogs.get(e),t)).map(([e])=>e),v=0;n.fileMessages=/* @__PURE__ */ new Map;for(let{file:e,messages:t}of c)n.fileMessages.set(e,h.messages.slice(v,v+t.length)),v+=t.length;n.extractions=s,n.catalogs=g,n.catalogFiles=Object.fromEntries(this.locales.map(e=>[e,Y(l,e)])),this.reportLocales(e,h),h.messages.length&&e.info(r(`indexed ${h.messages.length} messages across ${o.length} files.`));let y=[...h.failures];for(let[t,n]of y.slice(1))e.warn(r(`${t} translation failed: ${n.message}`));if(y.length)throw y[0][1];return _}runSync(e,t){let n=this.queue.then(()=>this.sync(e,t));return this.queue=n.then(()=>void 0,()=>void 0),n}};export{fe as C,re as D,te as E,ie as O,L as S,ne as T,q as _,X as a,be as b,rt as c,$e as d,ze as f,Oe as g,Me as h,at as i,N as k,Ge as l,Le as m,mt as n,nt as o,Pe as p,Z as r,ot as s,gt as t,Ye as u,H as v,pe as w,me as x,V as y};