@astroscope/i18n 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +262 -0
  2. package/dist/babel-plugin-FUTQRKLT.js +121 -0
  3. package/dist/babel-plugin-K2K4ZPM5.js +118 -0
  4. package/dist/chunk-22ZZFFC2.js +159 -0
  5. package/dist/chunk-2PSXD3JJ.js +144 -0
  6. package/dist/chunk-3VI62RLT.js +176 -0
  7. package/dist/chunk-4A5BKHFN.js +16 -0
  8. package/dist/chunk-4DAQPWXI.js +36 -0
  9. package/dist/chunk-4OGX6AF5.js +10 -0
  10. package/dist/chunk-4PHYKXO3.js +227 -0
  11. package/dist/chunk-4UBFISFY.js +376 -0
  12. package/dist/chunk-5DERF6DV.js +266 -0
  13. package/dist/chunk-5KGNHFTC.js +344 -0
  14. package/dist/chunk-5PP4D2VK.js +23 -0
  15. package/dist/chunk-6BW3PN23.js +14 -0
  16. package/dist/chunk-6ESQ4JQI.js +263 -0
  17. package/dist/chunk-A7MPXMOP.js +202 -0
  18. package/dist/chunk-AWZ2SQDW.js +149 -0
  19. package/dist/chunk-AYY2YIBQ.js +52 -0
  20. package/dist/chunk-BMNEJFTD.js +56 -0
  21. package/dist/chunk-BSXQGEUK.js +16 -0
  22. package/dist/chunk-BSYTJFGF.js +21 -0
  23. package/dist/chunk-BVPXEGTT.js +12 -0
  24. package/dist/chunk-C4DJYWF6.js +193 -0
  25. package/dist/chunk-C5EJYE2P.js +245 -0
  26. package/dist/chunk-CLNOQHMS.js +254 -0
  27. package/dist/chunk-E5MCIRSU.js +144 -0
  28. package/dist/chunk-E7ZJS7WX.js +162 -0
  29. package/dist/chunk-EMM6LRO2.js +8 -0
  30. package/dist/chunk-ESFGCYYH.js +24 -0
  31. package/dist/chunk-FAKBSLNW.js +24 -0
  32. package/dist/chunk-FHBVI3TL.js +372 -0
  33. package/dist/chunk-FI5KZ5IO.js +17 -0
  34. package/dist/chunk-H5R6YMOL.js +233 -0
  35. package/dist/chunk-H62K3FGA.js +236 -0
  36. package/dist/chunk-HDG2R6XT.js +211 -0
  37. package/dist/chunk-HGXU5QAK.js +344 -0
  38. package/dist/chunk-HHRMR3TM.js +17 -0
  39. package/dist/chunk-HS4HVBAD.js +127 -0
  40. package/dist/chunk-IPJWKKHJ.js +324 -0
  41. package/dist/chunk-ITTL4V7J.js +24 -0
  42. package/dist/chunk-IWUBCMOK.js +128 -0
  43. package/dist/chunk-JJBBY2GR.js +14 -0
  44. package/dist/chunk-JJEDOJBR.js +193 -0
  45. package/dist/chunk-JTUKXNIJ.js +23 -0
  46. package/dist/chunk-K7YULG4A.js +14 -0
  47. package/dist/chunk-KNDYKTHE.js +31 -0
  48. package/dist/chunk-KNONI6DP.js +89 -0
  49. package/dist/chunk-LMTEO22Y.js +17 -0
  50. package/dist/chunk-LRLZEX4D.js +147 -0
  51. package/dist/chunk-MFKPLUAN.js +241 -0
  52. package/dist/chunk-MIWXQOO3.js +316 -0
  53. package/dist/chunk-MJRTAWPR.js +261 -0
  54. package/dist/chunk-MZEPQCXX.js +249 -0
  55. package/dist/chunk-NHHTSFA7.js +237 -0
  56. package/dist/chunk-NTTXM7AG.js +23 -0
  57. package/dist/chunk-NZFAVJXR.js +192 -0
  58. package/dist/chunk-OFNFSDW3.js +13 -0
  59. package/dist/chunk-PG3XDNGF.js +227 -0
  60. package/dist/chunk-PVEVTPNK.js +139 -0
  61. package/dist/chunk-QAO4BXS4.js +244 -0
  62. package/dist/chunk-QCTULQQK.js +34 -0
  63. package/dist/chunk-QFAAGCP5.js +177 -0
  64. package/dist/chunk-QKND2KCA.js +163 -0
  65. package/dist/chunk-QZEGY6RJ.js +151 -0
  66. package/dist/chunk-RAE2L6FT.js +193 -0
  67. package/dist/chunk-S3ABJBU3.js +255 -0
  68. package/dist/chunk-SVDVCPCV.js +236 -0
  69. package/dist/chunk-T35ZUWTL.js +153 -0
  70. package/dist/chunk-T6WV5DW6.js +156 -0
  71. package/dist/chunk-TGUXVDA3.js +82 -0
  72. package/dist/chunk-TYMO7K3A.js +173 -0
  73. package/dist/chunk-V4RBFLQL.js +23 -0
  74. package/dist/chunk-V4XWJXXZ.js +23 -0
  75. package/dist/chunk-VQCY3OKK.js +258 -0
  76. package/dist/chunk-WLGOJPDJ.js +15 -0
  77. package/dist/chunk-WUEPDJIL.js +259 -0
  78. package/dist/chunk-X3L7WZLY.js +254 -0
  79. package/dist/chunk-XDD62ZM3.js +255 -0
  80. package/dist/chunk-XFXXEDRD.js +36 -0
  81. package/dist/chunk-XKYOR5UK.js +8 -0
  82. package/dist/chunk-Y26535SI.js +239 -0
  83. package/dist/chunk-Y3PQX5TX.js +152 -0
  84. package/dist/chunk-Y4BE2V6F.js +347 -0
  85. package/dist/chunk-Z4IZYDIA.js +24 -0
  86. package/dist/chunk-Z52G4CYY.js +14 -0
  87. package/dist/chunk-ZGLUYWVM.js +128 -0
  88. package/dist/client/directives/idle.d.ts +9 -0
  89. package/dist/client/directives/idle.js +15 -0
  90. package/dist/client/directives/load.d.ts +9 -0
  91. package/dist/client/directives/load.js +15 -0
  92. package/dist/client/directives/media.d.ts +9 -0
  93. package/dist/client/directives/media.js +15 -0
  94. package/dist/client/directives/only.d.ts +9 -0
  95. package/dist/client/directives/only.js +15 -0
  96. package/dist/client/directives/utils.d.ts +10 -0
  97. package/dist/client/directives/utils.js +7 -0
  98. package/dist/client/directives/visible.d.ts +9 -0
  99. package/dist/client/directives/visible.js +15 -0
  100. package/dist/client/import-with-i18n.d.ts +16 -0
  101. package/dist/client/import-with-i18n.js +8 -0
  102. package/dist/client/t.d.ts +20 -0
  103. package/dist/client/t.js +37 -0
  104. package/dist/client-directives/idle.d.ts +9 -0
  105. package/dist/client-directives/idle.js +15 -0
  106. package/dist/client-directives/load.d.ts +9 -0
  107. package/dist/client-directives/load.js +15 -0
  108. package/dist/client-directives/media.d.ts +9 -0
  109. package/dist/client-directives/media.js +15 -0
  110. package/dist/client-directives/only.d.ts +9 -0
  111. package/dist/client-directives/only.js +15 -0
  112. package/dist/client-directives/utils.d.ts +9 -0
  113. package/dist/client-directives/utils.js +7 -0
  114. package/dist/client-directives/visible.d.ts +9 -0
  115. package/dist/client-directives/visible.js +15 -0
  116. package/dist/extraction/index.d.ts +34 -0
  117. package/dist/extraction/index.js +9 -0
  118. package/dist/i18n-3cZHoHwP.d.ts +86 -0
  119. package/dist/i18n-BGfrSNM8.d.ts +56 -0
  120. package/dist/i18n-BHU81LMA.d.ts +55 -0
  121. package/dist/i18n-BagoeH4_.d.ts +62 -0
  122. package/dist/i18n-BeL84090.d.ts +77 -0
  123. package/dist/i18n-BeRWDfHi.d.ts +55 -0
  124. package/dist/i18n-Bfs2PVcf.d.ts +79 -0
  125. package/dist/i18n-BrL7p3aN.d.ts +99 -0
  126. package/dist/i18n-CNQNCFU0.d.ts +55 -0
  127. package/dist/i18n-CX_uU8V2.d.ts +80 -0
  128. package/dist/i18n-Cr1QZCwe.d.ts +64 -0
  129. package/dist/i18n-CzTRxGeX.d.ts +80 -0
  130. package/dist/i18n-DUOFiC7g.d.ts +77 -0
  131. package/dist/i18n-DcF47BHS.d.ts +77 -0
  132. package/dist/i18n-DifWvtaO.d.ts +60 -0
  133. package/dist/i18n-DumSqX1t.d.ts +55 -0
  134. package/dist/i18n-fWTJw12h.d.ts +80 -0
  135. package/dist/import-with-i18n.d.ts +23 -0
  136. package/dist/import-with-i18n.js +7 -0
  137. package/dist/index.d.ts +68 -0
  138. package/dist/index.js +151 -0
  139. package/dist/init.d.ts +2 -0
  140. package/dist/init.js +8 -0
  141. package/dist/internal.d.ts +11 -0
  142. package/dist/internal.js +9 -0
  143. package/dist/middleware-entrypoint-C0Drh9E_.d.ts +29 -0
  144. package/dist/middleware-entrypoint-mEl66IUy.d.ts +29 -0
  145. package/dist/middleware-entrypoint.d.ts +5 -0
  146. package/dist/middleware-entrypoint.js +30 -0
  147. package/dist/server/middleware-entrypoint.d.ts +2 -0
  148. package/dist/server/middleware-entrypoint.js +28 -0
  149. package/dist/server/t.d.ts +17 -0
  150. package/dist/server/t.js +59 -0
  151. package/dist/t-BY_C9lZ1.d.ts +30 -0
  152. package/dist/t-CG3yDiEa.d.ts +30 -0
  153. package/dist/t-CHsBfrPr.d.ts +30 -0
  154. package/dist/t-DQpXaDhP.d.ts +30 -0
  155. package/dist/t.client.d.ts +11 -0
  156. package/dist/t.client.js +35 -0
  157. package/dist/t.server.d.ts +22 -0
  158. package/dist/t.server.js +12 -0
  159. package/dist/types-8uKCwFda.d.ts +24 -0
  160. package/dist/types-BC6K-pID.d.ts +110 -0
  161. package/dist/types-BUV7BZML.d.ts +55 -0
  162. package/dist/types-BWGB322F.d.ts +46 -0
  163. package/dist/types-B_-RxW4A.d.ts +7 -0
  164. package/dist/types-BaaSiz9n.d.ts +7 -0
  165. package/dist/types-Bgl2V5xo.d.ts +102 -0
  166. package/dist/types-BwhB6IT4.d.ts +111 -0
  167. package/dist/types-Bzp6KxsI.d.ts +50 -0
  168. package/dist/types-C6rOJFY2.d.ts +24 -0
  169. package/dist/types-C7lD-Woj.d.ts +50 -0
  170. package/dist/types-CLWZeQhD.d.ts +54 -0
  171. package/dist/types-COXt613w.d.ts +19 -0
  172. package/dist/types-CUlkbl9-.d.ts +50 -0
  173. package/dist/types-CVv7GGPj.d.ts +46 -0
  174. package/dist/types-CiIDN2sW.d.ts +64 -0
  175. package/dist/types-Cr86qjYl.d.ts +58 -0
  176. package/dist/types-CxnObiEO.d.ts +7 -0
  177. package/dist/types-D44mFUjA.d.ts +97 -0
  178. package/dist/types-D85m9UTC.d.ts +137 -0
  179. package/dist/types-DWhsmSPP.d.ts +102 -0
  180. package/dist/types-DdprXGJ1.d.ts +46 -0
  181. package/dist/types-DhVJ2ZIo.d.ts +43 -0
  182. package/dist/types-DnbOuM1L.d.ts +7 -0
  183. package/dist/types-DsNK_9sI.d.ts +24 -0
  184. package/dist/types-DvWBr9Xp.d.ts +17 -0
  185. package/dist/types-DwkIalh6.d.ts +24 -0
  186. package/dist/types-OYRgjtE_.d.ts +110 -0
  187. package/dist/types-SV8S05GX.d.ts +7 -0
  188. package/dist/types-TYn9WnxY.d.ts +46 -0
  189. package/dist/types-aXCBbdhq.d.ts +55 -0
  190. package/dist/types-gn4aNKGx.d.ts +54 -0
  191. package/dist/types-nippsMkm.d.ts +54 -0
  192. package/package.json +105 -0
  193. package/src/components/I18nScript.astro +37 -0
  194. package/src/components/index.ts +2 -0
@@ -0,0 +1,233 @@
1
+ import {
2
+ runWithContext
3
+ } from "./chunk-JJBBY2GR.js";
4
+ import {
5
+ compileTranslations
6
+ } from "./chunk-KNDYKTHE.js";
7
+
8
+ // src/extraction/hash.ts
9
+ function hashString(str) {
10
+ let hash = 0;
11
+ for (let i = 0; i < str.length; i++) {
12
+ const char = str.charCodeAt(i);
13
+ hash = (hash << 5) - hash + char;
14
+ hash = hash & hash;
15
+ }
16
+ return Math.abs(hash).toString(36).substring(0, 8);
17
+ }
18
+ function computeChunkHash(translations, keys) {
19
+ const relevantTranslations = {};
20
+ for (const key of keys.sort()) {
21
+ if (translations[key]) {
22
+ relevantTranslations[key] = translations[key];
23
+ }
24
+ }
25
+ return hashString(JSON.stringify(relevantTranslations));
26
+ }
27
+ function computeAllChunkHashes(translations, manifest) {
28
+ const hashes = {};
29
+ for (const [chunkId, keys] of Object.entries(manifest)) {
30
+ hashes[chunkId] = computeChunkHash(translations, keys);
31
+ }
32
+ return hashes;
33
+ }
34
+
35
+ // src/server/i18n.ts
36
+ var I18nSingleton = class {
37
+ config = null;
38
+ rawCache = /* @__PURE__ */ new Map();
39
+ compiledCache = /* @__PURE__ */ new Map();
40
+ chunkManifest = null;
41
+ hashCache = /* @__PURE__ */ new Map();
42
+ configure(config) {
43
+ this.config = config;
44
+ }
45
+ getConfig() {
46
+ return this.config;
47
+ }
48
+ setTranslations(locale, raw) {
49
+ this.rawCache.set(locale, raw);
50
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
51
+ this.hashCache.delete(locale);
52
+ if (this.chunkManifest) {
53
+ this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
54
+ }
55
+ }
56
+ getTranslations(locale) {
57
+ return this.rawCache.get(locale);
58
+ }
59
+ getCompiledTranslations(locale) {
60
+ return this.compiledCache.get(locale);
61
+ }
62
+ setChunkManifest(manifest) {
63
+ this.chunkManifest = manifest;
64
+ for (const [locale, raw] of this.rawCache) {
65
+ this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
66
+ }
67
+ }
68
+ getChunkManifest() {
69
+ return this.chunkManifest;
70
+ }
71
+ getHashes(locale) {
72
+ return this.hashCache.get(locale);
73
+ }
74
+ /**
75
+ * Clear translations for specified locale(s).
76
+ * @param locales - Locale(s) to clear, or all if not specified
77
+ */
78
+ clear(locales) {
79
+ const targets = this.resolveLocales(locales);
80
+ for (const locale of targets) {
81
+ this.rawCache.delete(locale);
82
+ this.compiledCache.delete(locale);
83
+ this.hashCache.delete(locale);
84
+ }
85
+ }
86
+ resolveLocales(locales) {
87
+ if (!locales) return this.config?.locales ?? [];
88
+ if (typeof locales === "string") return [locales];
89
+ return locales;
90
+ }
91
+ };
92
+ var i18n = new I18nSingleton();
93
+
94
+ // src/server/middleware.ts
95
+ var I18N_ENDPOINT_PREFIX = "/_i18n/";
96
+ function detectLocale(request) {
97
+ const config = i18n.getConfig();
98
+ if (!config) return void 0;
99
+ const { locales } = config;
100
+ const acceptLanguage = request.headers.get("accept-language");
101
+ if (!acceptLanguage) return void 0;
102
+ const preferred = acceptLanguage.split(",").map((part) => {
103
+ const [lang, q = "q=1"] = part.trim().split(";");
104
+ return {
105
+ lang: lang.split("-")[0].toLowerCase(),
106
+ q: parseFloat(q.replace("q=", ""))
107
+ };
108
+ }).sort((a, b) => b.q - a.q);
109
+ for (const { lang } of preferred) {
110
+ if (locales.includes(lang)) {
111
+ return lang;
112
+ }
113
+ }
114
+ return void 0;
115
+ }
116
+ function generateI18nHashScript(locale, hashes) {
117
+ const state = { locale, hashes, translations: {} };
118
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
119
+ }
120
+ function generateI18nFullScript(locale, raw) {
121
+ const state = { locale, hashes: {}, translations: raw };
122
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
123
+ }
124
+ async function injectI18nScript(response, script) {
125
+ const contentType = response.headers.get("content-type");
126
+ if (!contentType?.includes("text/html")) {
127
+ return response;
128
+ }
129
+ const html = await response.text();
130
+ let injectedHtml;
131
+ if (html.includes("</head>")) {
132
+ injectedHtml = html.replace("</head>", `${script}</head>`);
133
+ } else if (html.includes("<body")) {
134
+ injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
135
+ } else {
136
+ injectedHtml = script + html;
137
+ }
138
+ return new Response(injectedHtml, {
139
+ status: response.status,
140
+ statusText: response.statusText,
141
+ headers: response.headers
142
+ });
143
+ }
144
+ function parseI18nEndpointPath(pathname) {
145
+ if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
146
+ return null;
147
+ }
148
+ const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
149
+ const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
150
+ if (!match) {
151
+ return null;
152
+ }
153
+ return { locale: match[1], chunkName: match[2], hash: match[3] };
154
+ }
155
+ function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
156
+ const keys = chunkManifest[chunkName];
157
+ if (!keys) {
158
+ return new Response(`/* chunk not found: ${chunkName} */`, {
159
+ status: 404,
160
+ headers: { "Content-Type": "application/javascript" }
161
+ });
162
+ }
163
+ const actualHash = computeChunkHash(translations, keys);
164
+ if (requestedHash !== actualHash) {
165
+ console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
166
+ }
167
+ const chunkTranslations = {};
168
+ for (const key of keys) {
169
+ if (translations[key]) {
170
+ chunkTranslations[key] = translations[key];
171
+ }
172
+ }
173
+ const js = `/* @astroscope/i18n chunk: ${chunkName} */
174
+ (function() {
175
+ var i = window.__i18n__;
176
+ if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
177
+ })();
178
+ `;
179
+ return new Response(js, {
180
+ status: 200,
181
+ headers: {
182
+ "Content-Type": "application/javascript",
183
+ "Cache-Control": "public, max-age=31536000, immutable"
184
+ }
185
+ });
186
+ }
187
+ function createI18nMiddleware(options) {
188
+ return async (ctx, next) => {
189
+ const config = i18n.getConfig();
190
+ if (!config) {
191
+ throw new Error("i18n not configured. Call i18n.configure() before using i18nMiddleware.");
192
+ }
193
+ const pathname = new URL(ctx.request.url).pathname;
194
+ const chunkManifest = i18n.getChunkManifest();
195
+ if (chunkManifest) {
196
+ const endpointParams = parseI18nEndpointPath(pathname);
197
+ if (endpointParams) {
198
+ const { locale: urlLocale, chunkName, hash } = endpointParams;
199
+ const endpointRaw = i18n.getTranslations(urlLocale) ?? {};
200
+ return handleI18nEndpoint(chunkName, hash, endpointRaw, chunkManifest);
201
+ }
202
+ }
203
+ const locale = options.locale(ctx);
204
+ const compiled = i18n.getCompiledTranslations(locale) ?? {};
205
+ const raw = i18n.getTranslations(locale) ?? {};
206
+ const context = {
207
+ locale,
208
+ translations: compiled,
209
+ fallback: config.fallback,
210
+ meta: {}
211
+ };
212
+ return runWithContext(context, async () => {
213
+ const response = await next();
214
+ let script;
215
+ const hasChunkManifest = chunkManifest && Object.keys(chunkManifest).length > 0;
216
+ if (hasChunkManifest) {
217
+ const hashes = i18n.getHashes(locale) ?? {};
218
+ script = generateI18nHashScript(locale, hashes);
219
+ } else {
220
+ script = generateI18nFullScript(locale, raw);
221
+ }
222
+ return injectI18nScript(response, script);
223
+ });
224
+ };
225
+ }
226
+
227
+ export {
228
+ computeChunkHash,
229
+ computeAllChunkHashes,
230
+ i18n,
231
+ detectLocale,
232
+ createI18nMiddleware
233
+ };
@@ -0,0 +1,236 @@
1
+ import {
2
+ runWithContext
3
+ } from "./chunk-JJBBY2GR.js";
4
+ import {
5
+ compileTranslations
6
+ } from "./chunk-KNDYKTHE.js";
7
+
8
+ // src/extraction/hash.ts
9
+ function hashString(str) {
10
+ let hash = 0;
11
+ for (let i = 0; i < str.length; i++) {
12
+ const char = str.charCodeAt(i);
13
+ hash = (hash << 5) - hash + char;
14
+ hash = hash & hash;
15
+ }
16
+ return Math.abs(hash).toString(36).substring(0, 8);
17
+ }
18
+ function computeChunkHash(translations, keys) {
19
+ const relevantTranslations = {};
20
+ for (const key of keys.sort()) {
21
+ if (translations[key]) {
22
+ relevantTranslations[key] = translations[key];
23
+ }
24
+ }
25
+ return hashString(JSON.stringify(relevantTranslations));
26
+ }
27
+ function computeAllChunkHashes(translations, manifest) {
28
+ const hashes = {};
29
+ for (const [chunkId, keys] of Object.entries(manifest)) {
30
+ hashes[chunkId] = computeChunkHash(translations, keys);
31
+ }
32
+ return hashes;
33
+ }
34
+
35
+ // src/server/i18n.ts
36
+ var I18nSingleton = class {
37
+ config = null;
38
+ rawCache = /* @__PURE__ */ new Map();
39
+ compiledCache = /* @__PURE__ */ new Map();
40
+ chunkManifest = null;
41
+ hashCache = /* @__PURE__ */ new Map();
42
+ configure(config) {
43
+ this.config = config;
44
+ }
45
+ getConfig() {
46
+ return this.config;
47
+ }
48
+ getDefaultLocale() {
49
+ return this.config?.defaultLocale ?? this.config?.locales[0];
50
+ }
51
+ setTranslations(locale, raw) {
52
+ this.rawCache.set(locale, raw);
53
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
54
+ this.hashCache.delete(locale);
55
+ if (this.chunkManifest) {
56
+ this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
57
+ }
58
+ }
59
+ getTranslations(locale) {
60
+ return this.rawCache.get(locale);
61
+ }
62
+ getCompiledTranslations(locale) {
63
+ return this.compiledCache.get(locale);
64
+ }
65
+ setChunkManifest(manifest) {
66
+ this.chunkManifest = manifest;
67
+ for (const [locale, raw] of this.rawCache) {
68
+ this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
69
+ }
70
+ }
71
+ getChunkManifest() {
72
+ return this.chunkManifest;
73
+ }
74
+ getHashes(locale) {
75
+ return this.hashCache.get(locale);
76
+ }
77
+ /**
78
+ * Clear translations for specified locale(s).
79
+ * @param locales - Locale(s) to clear, or all if not specified
80
+ */
81
+ clear(locales) {
82
+ const targets = this.resolveLocales(locales);
83
+ for (const locale of targets) {
84
+ this.rawCache.delete(locale);
85
+ this.compiledCache.delete(locale);
86
+ this.hashCache.delete(locale);
87
+ }
88
+ }
89
+ resolveLocales(locales) {
90
+ if (!locales) return this.config?.locales ?? [];
91
+ if (typeof locales === "string") return [locales];
92
+ return locales;
93
+ }
94
+ };
95
+ var i18n = new I18nSingleton();
96
+
97
+ // src/server/middleware.ts
98
+ var I18N_ENDPOINT_PREFIX = "/_i18n/";
99
+ function detectLocale(request) {
100
+ const config = i18n.getConfig();
101
+ if (!config) return void 0;
102
+ const { locales } = config;
103
+ const acceptLanguage = request.headers.get("accept-language");
104
+ if (!acceptLanguage) return void 0;
105
+ const preferred = acceptLanguage.split(",").map((part) => {
106
+ const [lang, q = "q=1"] = part.trim().split(";");
107
+ return {
108
+ lang: lang.split("-")[0].toLowerCase(),
109
+ q: parseFloat(q.replace("q=", ""))
110
+ };
111
+ }).sort((a, b) => b.q - a.q);
112
+ for (const { lang } of preferred) {
113
+ if (locales.includes(lang)) {
114
+ return lang;
115
+ }
116
+ }
117
+ return void 0;
118
+ }
119
+ function generateI18nHashScript(locale, hashes) {
120
+ const state = { locale, hashes, translations: {} };
121
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
122
+ }
123
+ function generateI18nFullScript(locale, raw) {
124
+ const state = { locale, hashes: {}, translations: raw };
125
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
126
+ }
127
+ async function injectI18nScript(response, script) {
128
+ const contentType = response.headers.get("content-type");
129
+ if (!contentType?.includes("text/html")) {
130
+ return response;
131
+ }
132
+ const html = await response.text();
133
+ let injectedHtml;
134
+ if (html.includes("</head>")) {
135
+ injectedHtml = html.replace("</head>", `${script}</head>`);
136
+ } else if (html.includes("<body")) {
137
+ injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
138
+ } else {
139
+ injectedHtml = script + html;
140
+ }
141
+ return new Response(injectedHtml, {
142
+ status: response.status,
143
+ statusText: response.statusText,
144
+ headers: response.headers
145
+ });
146
+ }
147
+ function parseI18nEndpointPath(pathname) {
148
+ if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
149
+ return null;
150
+ }
151
+ const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
152
+ const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
153
+ if (!match) {
154
+ return null;
155
+ }
156
+ return { locale: match[1], chunkName: match[2], hash: match[3] };
157
+ }
158
+ function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
159
+ const keys = chunkManifest[chunkName];
160
+ if (!keys) {
161
+ return new Response(`/* chunk not found: ${chunkName} */`, {
162
+ status: 404,
163
+ headers: { "Content-Type": "application/javascript" }
164
+ });
165
+ }
166
+ const actualHash = computeChunkHash(translations, keys);
167
+ if (requestedHash !== actualHash) {
168
+ console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
169
+ }
170
+ const chunkTranslations = {};
171
+ for (const key of keys) {
172
+ if (translations[key]) {
173
+ chunkTranslations[key] = translations[key];
174
+ }
175
+ }
176
+ const js = `/* @astroscope/i18n chunk: ${chunkName} */
177
+ (function() {
178
+ var i = window.__i18n__;
179
+ if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
180
+ })();
181
+ `;
182
+ return new Response(js, {
183
+ status: 200,
184
+ headers: {
185
+ "Content-Type": "application/javascript",
186
+ "Cache-Control": "public, max-age=31536000, immutable"
187
+ }
188
+ });
189
+ }
190
+ function createI18nMiddleware(options) {
191
+ return async (ctx, next) => {
192
+ const config = i18n.getConfig();
193
+ if (!config) {
194
+ throw new Error("i18n not configured. Call i18n.configure() before using i18nMiddleware.");
195
+ }
196
+ const pathname = new URL(ctx.request.url).pathname;
197
+ const chunkManifest = i18n.getChunkManifest();
198
+ if (chunkManifest) {
199
+ const endpointParams = parseI18nEndpointPath(pathname);
200
+ if (endpointParams) {
201
+ const { locale: urlLocale, chunkName, hash } = endpointParams;
202
+ const endpointRaw = i18n.getTranslations(urlLocale) ?? {};
203
+ return handleI18nEndpoint(chunkName, hash, endpointRaw, chunkManifest);
204
+ }
205
+ }
206
+ const locale = options.locale(ctx);
207
+ const compiled = i18n.getCompiledTranslations(locale) ?? {};
208
+ const raw = i18n.getTranslations(locale) ?? {};
209
+ const context = {
210
+ locale,
211
+ translations: compiled,
212
+ fallback: config.fallback ?? "fallback",
213
+ meta: {}
214
+ };
215
+ return runWithContext(context, async () => {
216
+ const response = await next();
217
+ let script;
218
+ const hasChunkManifest = chunkManifest && Object.keys(chunkManifest).length > 0;
219
+ if (hasChunkManifest) {
220
+ const hashes = i18n.getHashes(locale) ?? {};
221
+ script = generateI18nHashScript(locale, hashes);
222
+ } else {
223
+ script = generateI18nFullScript(locale, raw);
224
+ }
225
+ return injectI18nScript(response, script);
226
+ });
227
+ };
228
+ }
229
+
230
+ export {
231
+ computeChunkHash,
232
+ computeAllChunkHashes,
233
+ i18n,
234
+ detectLocale,
235
+ createI18nMiddleware
236
+ };
@@ -0,0 +1,211 @@
1
+ import {
2
+ chunkIdToName
3
+ } from "./chunk-4A5BKHFN.js";
4
+
5
+ // src/extraction/vite-plugin.ts
6
+ import path from "path";
7
+ var VIRTUAL_MODULE_ID = "virtual:@astroscope/i18n/manifest";
8
+ var RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
9
+ var globalExtractedKeys = [];
10
+ var globalChunkManifest = {};
11
+ var globalProjectRoot = "";
12
+ function getManifest() {
13
+ const keysWithRelativePaths = globalExtractedKeys.map((key) => ({
14
+ ...key,
15
+ file: globalProjectRoot ? path.relative(globalProjectRoot, key.file) : key.file
16
+ }));
17
+ return {
18
+ keys: keysWithRelativePaths,
19
+ chunks: globalChunkManifest
20
+ };
21
+ }
22
+ function extractBalancedBraces(code, startIndex) {
23
+ if (code[startIndex] !== "{") return null;
24
+ let depth = 0;
25
+ let i = startIndex;
26
+ while (i < code.length) {
27
+ if (code[i] === "{") depth++;
28
+ else if (code[i] === "}") {
29
+ depth--;
30
+ if (depth === 0) return code.slice(startIndex, i + 1);
31
+ }
32
+ i++;
33
+ }
34
+ return null;
35
+ }
36
+ function extractTranslationCalls(code, filename) {
37
+ const keys = [];
38
+ const regex = /\bt\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*/g;
39
+ let match;
40
+ while ((match = regex.exec(code)) !== null) {
41
+ const key = match[1];
42
+ const afterKey = code.slice(match.index + match[0].length);
43
+ const upToMatch = code.slice(0, match.index);
44
+ const lineNumber = (upToMatch.match(/\n/g) || []).length + 1;
45
+ try {
46
+ const stringMatch = afterKey.match(/^['"`]([^'"`]*)['"`]/);
47
+ if (stringMatch) {
48
+ keys.push({
49
+ key,
50
+ meta: { fallback: stringMatch[1] },
51
+ file: filename,
52
+ line: lineNumber
53
+ });
54
+ } else if (afterKey.startsWith("{")) {
55
+ const metaStr = extractBalancedBraces(afterKey, 0);
56
+ if (metaStr) {
57
+ const fallbackMatch = metaStr.match(/fallback\s*:\s*['"`]([^'"`]+)['"`]/);
58
+ const descMatch = metaStr.match(/description\s*:\s*['"`]([^'"`]+)['"`]/);
59
+ const fallback = fallbackMatch ? fallbackMatch[1] : "";
60
+ const description = descMatch ? descMatch[1] : void 0;
61
+ const varsBlockMatch = metaStr.match(/variables\s*:\s*\{/);
62
+ let variables;
63
+ if (varsBlockMatch) {
64
+ const varsStart = metaStr.indexOf("{", varsBlockMatch.index + varsBlockMatch[0].length - 1);
65
+ const varsStr = extractBalancedBraces(metaStr, varsStart);
66
+ if (varsStr) {
67
+ variables = parseVariables(varsStr);
68
+ }
69
+ }
70
+ keys.push({
71
+ key,
72
+ meta: { fallback, description, variables },
73
+ file: filename,
74
+ line: lineNumber
75
+ });
76
+ }
77
+ }
78
+ } catch {
79
+ }
80
+ }
81
+ return keys;
82
+ }
83
+ function parseVariables(str) {
84
+ const result = {};
85
+ const varNameRegex = /(\w+)\s*:\s*\{/g;
86
+ let nameMatch;
87
+ while ((nameMatch = varNameRegex.exec(str)) !== null) {
88
+ const varName = nameMatch[1];
89
+ const varStart = str.indexOf("{", nameMatch.index + nameMatch[0].length - 1);
90
+ const varObj = extractBalancedBraces(str, varStart);
91
+ if (varObj) {
92
+ const fallbackMatch = varObj.match(/fallback\s*:\s*['"`]([^'"`]*)['"`]/);
93
+ const descMatch = varObj.match(/description\s*:\s*['"`]([^'"`]*)['"`]/);
94
+ result[varName] = {
95
+ fallback: fallbackMatch ? fallbackMatch[1] : void 0,
96
+ description: descMatch ? descMatch[1] : void 0
97
+ };
98
+ }
99
+ }
100
+ return Object.keys(result).length > 0 ? result : void 0;
101
+ }
102
+ function hasI18nImport(code) {
103
+ return /@astroscope\/i18n\/t/.test(code);
104
+ }
105
+ function i18nVitePlugin(options) {
106
+ const { include = [".ts", ".tsx", ".js", ".jsx", ".astro"], logger } = options;
107
+ const extractedKeys = [];
108
+ const fileToKeys = /* @__PURE__ */ new Map();
109
+ const filesWithI18n = /* @__PURE__ */ new Set();
110
+ let chunkManifest = {};
111
+ let projectRoot = "";
112
+ return {
113
+ name: "@astroscope/i18n/extract",
114
+ enforce: "pre",
115
+ configResolved(config) {
116
+ projectRoot = config.root;
117
+ globalProjectRoot = config.root;
118
+ },
119
+ resolveId(id) {
120
+ if (id === VIRTUAL_MODULE_ID) {
121
+ return RESOLVED_VIRTUAL_MODULE_ID;
122
+ }
123
+ if (id.startsWith(`${VIRTUAL_MODULE_ID}?`)) {
124
+ return `\0${id}`;
125
+ }
126
+ },
127
+ load(id) {
128
+ if (id === RESOLVED_VIRTUAL_MODULE_ID || id.startsWith(`\0${VIRTUAL_MODULE_ID}?`)) {
129
+ const keysWithRelativePaths = extractedKeys.map((key) => ({
130
+ ...key,
131
+ file: projectRoot ? path.relative(projectRoot, key.file) : key.file
132
+ }));
133
+ const manifest = {
134
+ keys: keysWithRelativePaths,
135
+ chunks: chunkManifest
136
+ };
137
+ return `
138
+ export const manifest = ${JSON.stringify(manifest)};
139
+ export function getManifest() { return ${JSON.stringify(manifest)}; }
140
+ `;
141
+ }
142
+ },
143
+ transform(code, id) {
144
+ if (!include.some((ext) => id.endsWith(ext))) {
145
+ return null;
146
+ }
147
+ if (id.includes("node_modules")) {
148
+ return null;
149
+ }
150
+ if (hasI18nImport(code)) {
151
+ filesWithI18n.add(id);
152
+ }
153
+ const keys = extractTranslationCalls(code, id);
154
+ if (keys.length > 0) {
155
+ extractedKeys.push(...keys);
156
+ globalExtractedKeys = extractedKeys;
157
+ fileToKeys.set(
158
+ id,
159
+ keys.map((k) => k.key)
160
+ );
161
+ }
162
+ return null;
163
+ },
164
+ generateBundle(_, bundle) {
165
+ chunkManifest = {};
166
+ for (const [fileName, chunk] of Object.entries(bundle)) {
167
+ if (chunk.type === "chunk" && chunk.moduleIds) {
168
+ const keys = /* @__PURE__ */ new Set();
169
+ let hasI18nModule = false;
170
+ for (const moduleId of chunk.moduleIds) {
171
+ const moduleKeys = fileToKeys.get(moduleId);
172
+ if (moduleKeys) {
173
+ moduleKeys.forEach((k) => keys.add(k));
174
+ }
175
+ if (filesWithI18n.has(moduleId)) {
176
+ hasI18nModule = true;
177
+ }
178
+ }
179
+ if (keys.size > 0) {
180
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
181
+ chunkManifest[chunkName] = Array.from(keys);
182
+ }
183
+ if (hasI18nModule && chunk.type === "chunk") {
184
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
185
+ const loaderCode = `
186
+ /* @astroscope/i18n loader */
187
+ if (typeof window !== 'undefined' && window.__i18n__) {
188
+ const __i18n__ = window.__i18n__;
189
+ const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
190
+ if (__i18n_hash__) {
191
+ await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
192
+ }
193
+ }
194
+ /* end @astroscope/i18n loader */
195
+ `;
196
+ chunk.code = loaderCode + chunk.code;
197
+ }
198
+ }
199
+ }
200
+ globalChunkManifest = chunkManifest;
201
+ const chunkCount = Object.keys(chunkManifest).length;
202
+ const keyCount = extractedKeys.length;
203
+ logger?.info(`manifest: ${chunkCount} chunks, ${keyCount} keys`);
204
+ }
205
+ };
206
+ }
207
+
208
+ export {
209
+ getManifest,
210
+ i18nVitePlugin
211
+ };