@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,324 @@
1
+ import {
2
+ clearContext,
3
+ compileTranslations,
4
+ setContext
5
+ } from "./chunk-AYY2YIBQ.js";
6
+
7
+ // src/extraction/hash.ts
8
+ function hashString(str) {
9
+ let hash = 0;
10
+ for (let i = 0; i < str.length; i++) {
11
+ const char = str.charCodeAt(i);
12
+ hash = (hash << 5) - hash + char;
13
+ hash = hash & hash;
14
+ }
15
+ return Math.abs(hash).toString(36).substring(0, 8);
16
+ }
17
+ function computeChunkHash(translations, keys) {
18
+ const relevantTranslations = {};
19
+ for (const key of keys.sort()) {
20
+ if (translations[key]) {
21
+ relevantTranslations[key] = translations[key];
22
+ }
23
+ }
24
+ return hashString(JSON.stringify(relevantTranslations));
25
+ }
26
+ function computeAllChunkHashes(translations, manifest) {
27
+ const hashes = {};
28
+ for (const [chunkId, keys] of Object.entries(manifest)) {
29
+ hashes[chunkId] = computeChunkHash(translations, keys);
30
+ }
31
+ return hashes;
32
+ }
33
+
34
+ // src/server/service.ts
35
+ var instance = null;
36
+ function createI18nService(config) {
37
+ if (instance) {
38
+ throw new Error("i18n service already created. Call createI18nService() only once.");
39
+ }
40
+ instance = new I18nServiceImpl(config);
41
+ return instance;
42
+ }
43
+ function getI18nService() {
44
+ if (!instance) {
45
+ throw new Error(
46
+ "i18n service not initialized. Call createI18nService() before first request (e.g., in your boot file)."
47
+ );
48
+ }
49
+ return instance;
50
+ }
51
+ function hasI18nService() {
52
+ return instance !== null;
53
+ }
54
+ var I18nServiceImpl = class {
55
+ config;
56
+ // raw translation cache per locale
57
+ rawCache = /* @__PURE__ */ new Map();
58
+ // compiled translation cache per locale
59
+ compiledCache = /* @__PURE__ */ new Map();
60
+ // hash cache per locale (for per-chunk loading)
61
+ hashCache = /* @__PURE__ */ new Map();
62
+ // chunk manifest from build
63
+ chunkManifest;
64
+ // track in-progress fetches to avoid duplicate requests
65
+ fetchInProgress = /* @__PURE__ */ new Map();
66
+ constructor(config) {
67
+ this.config = Object.freeze({ ...config });
68
+ }
69
+ invalidate(locales) {
70
+ const targets = this.resolveLocales(locales);
71
+ for (const locale of targets) {
72
+ this.rawCache.delete(locale);
73
+ this.compiledCache.delete(locale);
74
+ this.hashCache.delete(locale);
75
+ this.fetchInProgress.delete(locale);
76
+ }
77
+ }
78
+ async refresh(locales) {
79
+ const targets = this.resolveLocales(locales);
80
+ const fetches = targets.map(async (locale) => {
81
+ const raw = await this.fetchTranslations(locale);
82
+ return { locale, raw };
83
+ });
84
+ const results = await Promise.all(fetches);
85
+ for (const { locale, raw } of results) {
86
+ this.rawCache.set(locale, raw);
87
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
88
+ if (this.chunkManifest) {
89
+ this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
90
+ }
91
+ }
92
+ }
93
+ async prefetch(locales) {
94
+ const targets = this.resolveLocales(locales);
95
+ await Promise.all(
96
+ targets.map(async (locale) => {
97
+ if (this.rawCache.has(locale)) return;
98
+ const raw = await this.fetchTranslations(locale);
99
+ this.rawCache.set(locale, raw);
100
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
101
+ if (this.chunkManifest) {
102
+ this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
103
+ }
104
+ })
105
+ );
106
+ }
107
+ async getTranslations(locale) {
108
+ const cached = this.compiledCache.get(locale);
109
+ if (cached) return cached;
110
+ const raw = await this.ensureRawTranslations(locale);
111
+ const compiled = compileTranslations(locale, raw);
112
+ this.compiledCache.set(locale, compiled);
113
+ return compiled;
114
+ }
115
+ async getRawTranslations(locale) {
116
+ return this.ensureRawTranslations(locale);
117
+ }
118
+ getHashes(locale) {
119
+ return this.hashCache.get(locale);
120
+ }
121
+ setChunkManifest(manifest) {
122
+ this.chunkManifest = manifest;
123
+ if (manifest) {
124
+ for (const [locale, raw] of this.rawCache) {
125
+ this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
126
+ }
127
+ }
128
+ }
129
+ getChunkManifest() {
130
+ return this.chunkManifest;
131
+ }
132
+ /**
133
+ * Ensure raw translations are cached, fetching if needed
134
+ */
135
+ async ensureRawTranslations(locale) {
136
+ const cached = this.rawCache.get(locale);
137
+ if (cached) return cached;
138
+ const raw = await this.fetchTranslations(locale);
139
+ this.rawCache.set(locale, raw);
140
+ if (this.chunkManifest) {
141
+ this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
142
+ }
143
+ return raw;
144
+ }
145
+ /**
146
+ * Fetch translations, deduplicating concurrent requests
147
+ */
148
+ async fetchTranslations(locale) {
149
+ const inProgress = this.fetchInProgress.get(locale);
150
+ if (inProgress) return inProgress;
151
+ const fetchPromise = this.config.fetch(locale, []).finally(() => {
152
+ this.fetchInProgress.delete(locale);
153
+ });
154
+ this.fetchInProgress.set(locale, fetchPromise);
155
+ return fetchPromise;
156
+ }
157
+ /**
158
+ * Resolve locale argument to array of locales
159
+ */
160
+ resolveLocales(locales) {
161
+ if (!locales) return this.config.locales;
162
+ if (typeof locales === "string") return [locales];
163
+ return locales;
164
+ }
165
+ };
166
+
167
+ // src/server/middleware.ts
168
+ var I18N_ENDPOINT_PREFIX = "/_i18n/";
169
+ function defaultDetectLocale(request, locales, defaultLocale) {
170
+ const url = new URL(request.url);
171
+ const localeParam = url.searchParams.get("locale");
172
+ if (localeParam && locales.includes(localeParam)) {
173
+ return localeParam;
174
+ }
175
+ const acceptLanguage = request.headers.get("accept-language");
176
+ if (acceptLanguage) {
177
+ const preferred = acceptLanguage.split(",").map((part) => {
178
+ const [lang, q = "q=1"] = part.trim().split(";");
179
+ return {
180
+ lang: lang.split("-")[0].toLowerCase(),
181
+ q: parseFloat(q.replace("q=", ""))
182
+ };
183
+ }).sort((a, b) => b.q - a.q);
184
+ for (const { lang } of preferred) {
185
+ if (locales.includes(lang)) {
186
+ return lang;
187
+ }
188
+ }
189
+ }
190
+ return defaultLocale;
191
+ }
192
+ function generateI18nHashScript(locale, hashes) {
193
+ const state = { locale, hashes, translations: {} };
194
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
195
+ }
196
+ function generateI18nFullScript(locale, raw) {
197
+ const state = { locale, hashes: {}, translations: raw };
198
+ return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
199
+ }
200
+ async function injectI18nScript(response, script) {
201
+ const contentType = response.headers.get("content-type");
202
+ if (!contentType?.includes("text/html")) {
203
+ return response;
204
+ }
205
+ const html = await response.text();
206
+ let injectedHtml;
207
+ if (html.includes("</head>")) {
208
+ injectedHtml = html.replace("</head>", `${script}</head>`);
209
+ } else if (html.includes("<body")) {
210
+ injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
211
+ } else {
212
+ injectedHtml = script + html;
213
+ }
214
+ return new Response(injectedHtml, {
215
+ status: response.status,
216
+ statusText: response.statusText,
217
+ headers: response.headers
218
+ });
219
+ }
220
+ function parseI18nEndpointPath(pathname) {
221
+ if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
222
+ return null;
223
+ }
224
+ const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
225
+ const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
226
+ if (!match) {
227
+ return null;
228
+ }
229
+ return { locale: match[1], chunkName: match[2], hash: match[3] };
230
+ }
231
+ function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
232
+ const keys = chunkManifest[chunkName];
233
+ if (!keys) {
234
+ return new Response(`/* chunk not found: ${chunkName} */`, {
235
+ status: 404,
236
+ headers: { "Content-Type": "application/javascript" }
237
+ });
238
+ }
239
+ const actualHash = computeChunkHash(translations, keys);
240
+ if (requestedHash !== actualHash) {
241
+ console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
242
+ }
243
+ const chunkTranslations = {};
244
+ for (const key of keys) {
245
+ if (translations[key]) {
246
+ chunkTranslations[key] = translations[key];
247
+ }
248
+ }
249
+ const js = `/* @astroscope/i18n chunk: ${chunkName} */
250
+ (function() {
251
+ var i = window.__i18n__;
252
+ if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
253
+ })();
254
+ `;
255
+ return new Response(js, {
256
+ status: 200,
257
+ headers: {
258
+ "Content-Type": "application/javascript",
259
+ // immutable cache - hash in URL ensures cache busting
260
+ "Cache-Control": "public, max-age=31536000, immutable"
261
+ }
262
+ });
263
+ }
264
+ function createI18nMiddleware(options) {
265
+ const { locales, defaultLocale, fallback, detectLocale, chunkManifest } = options;
266
+ const service = getI18nService();
267
+ if (chunkManifest) {
268
+ service.setChunkManifest(chunkManifest);
269
+ }
270
+ return async (ctx, next) => {
271
+ const pathname = new URL(ctx.request.url).pathname;
272
+ const serviceChunkManifest = service.getChunkManifest();
273
+ if (serviceChunkManifest) {
274
+ const endpointParams = parseI18nEndpointPath(pathname);
275
+ if (endpointParams) {
276
+ const { locale: urlLocale, chunkName, hash } = endpointParams;
277
+ const endpointRaw = await service.getRawTranslations(urlLocale);
278
+ return handleI18nEndpoint(chunkName, hash, endpointRaw, serviceChunkManifest);
279
+ }
280
+ }
281
+ const locale = detectLocale ? detectLocale(ctx.request) : ctx.currentLocale ?? defaultDetectLocale(ctx.request, locales, defaultLocale);
282
+ const translations = await service.getTranslations(locale);
283
+ const raw = await service.getRawTranslations(locale);
284
+ const context = {
285
+ locale,
286
+ translations,
287
+ fallback,
288
+ meta: {}
289
+ };
290
+ setContext(context);
291
+ try {
292
+ const response = await next();
293
+ let script;
294
+ const hasChunkManifest = serviceChunkManifest && Object.keys(serviceChunkManifest).length > 0;
295
+ if (hasChunkManifest) {
296
+ const hashes = service.getHashes(locale) ?? {};
297
+ script = generateI18nHashScript(locale, hashes);
298
+ } else {
299
+ script = generateI18nFullScript(locale, raw);
300
+ }
301
+ const injectedResponse = await injectI18nScript(response, script);
302
+ return injectedResponse;
303
+ } finally {
304
+ clearContext();
305
+ }
306
+ };
307
+ }
308
+ function clearTranslationCache(locale) {
309
+ getI18nService().invalidate(locale);
310
+ }
311
+ async function getCachedTranslations(locale) {
312
+ return getI18nService().getRawTranslations(locale);
313
+ }
314
+
315
+ export {
316
+ computeChunkHash,
317
+ computeAllChunkHashes,
318
+ createI18nService,
319
+ getI18nService,
320
+ hasI18nService,
321
+ createI18nMiddleware,
322
+ clearTranslationCache,
323
+ getCachedTranslations
324
+ };
@@ -0,0 +1,24 @@
1
+ import {
2
+ buildI18nChunkUrl,
3
+ componentUrlToChunkName
4
+ } from "./chunk-LMTEO22Y.js";
5
+
6
+ // src/client/directives/utils.ts
7
+ async function loadI18nForChunk(el) {
8
+ const componentUrl = el.getAttribute("component-url");
9
+ if (!componentUrl) return;
10
+ const chunkName = componentUrlToChunkName(componentUrl);
11
+ const i18n = window.__i18n__;
12
+ const hash = i18n.hashes[chunkName];
13
+ if (hash) {
14
+ const url = buildI18nChunkUrl(i18n.locale, chunkName, hash);
15
+ await import(
16
+ /* @vite-ignore */
17
+ url
18
+ );
19
+ }
20
+ }
21
+
22
+ export {
23
+ loadI18nForChunk
24
+ };
@@ -0,0 +1,128 @@
1
+ import {
2
+ compileTranslations
3
+ } from "./chunk-KNDYKTHE.js";
4
+
5
+ // src/server/i18n.ts
6
+ import fs from "fs";
7
+
8
+ // src/extraction/hash.ts
9
+ import { createHash } from "crypto";
10
+ function hashString(str) {
11
+ return createHash("sha256").update(str).digest("hex").substring(0, 8);
12
+ }
13
+ function computeChunkHash(translations, keys) {
14
+ const relevantTranslations = {};
15
+ for (const key of keys.sort()) {
16
+ if (translations[key]) {
17
+ relevantTranslations[key] = translations[key];
18
+ }
19
+ }
20
+ return hashString(JSON.stringify(relevantTranslations));
21
+ }
22
+ function computeAllChunkHashes(translations, manifest) {
23
+ const hashes = {};
24
+ for (const [chunkId, keys] of Object.entries(manifest)) {
25
+ hashes[chunkId] = computeChunkHash(translations, keys);
26
+ }
27
+ return hashes;
28
+ }
29
+
30
+ // src/server/i18n.ts
31
+ function loadExtractionManifest() {
32
+ const candidates = [
33
+ "./i18n-manifest.json",
34
+ // same directory
35
+ "../i18n-manifest.json"
36
+ // parent (when code is in chunks/)
37
+ ];
38
+ for (const candidate of candidates) {
39
+ try {
40
+ const manifestPath = new URL(candidate, import.meta.url);
41
+ const content = fs.readFileSync(manifestPath, "utf-8");
42
+ return JSON.parse(content);
43
+ } catch {
44
+ }
45
+ }
46
+ return void 0;
47
+ }
48
+ var I18nSingleton = class {
49
+ config = null;
50
+ rawCache = /* @__PURE__ */ new Map();
51
+ compiledCache = /* @__PURE__ */ new Map();
52
+ extractionManifest = void 0;
53
+ // undefined = not loaded yet
54
+ hashCache = /* @__PURE__ */ new Map();
55
+ configure(config) {
56
+ this.config = config;
57
+ }
58
+ getConfig() {
59
+ return this.config;
60
+ }
61
+ getDefaultLocale() {
62
+ return this.config?.defaultLocale ?? this.config?.locales[0];
63
+ }
64
+ getFallbackBehavior() {
65
+ return this.config?.fallback ?? "fallback";
66
+ }
67
+ setTranslations(locale, raw) {
68
+ this.rawCache.set(locale, raw);
69
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
70
+ this.hashCache.delete(locale);
71
+ const chunks = this.getChunkManifest();
72
+ if (chunks) {
73
+ this.hashCache.set(locale, computeAllChunkHashes(raw, chunks));
74
+ }
75
+ }
76
+ getTranslations(locale) {
77
+ return this.rawCache.get(locale) ?? {};
78
+ }
79
+ getCompiledTranslations(locale) {
80
+ return this.compiledCache.get(locale) ?? {};
81
+ }
82
+ getChunkManifest() {
83
+ return this.getExtractionManifest()?.chunks ?? {};
84
+ }
85
+ /**
86
+ * Get extracted translation keys with metadata.
87
+ * Use this to populate your CMS with keys extracted from the codebase.
88
+ */
89
+ getExtractedKeys() {
90
+ return this.getExtractionManifest()?.keys ?? null;
91
+ }
92
+ /**
93
+ * Get the full extraction manifest (keys + chunks).
94
+ * Returns null in dev mode (manifest doesn't exist).
95
+ */
96
+ getExtractionManifest() {
97
+ if (this.extractionManifest === void 0) {
98
+ this.extractionManifest = loadExtractionManifest() ?? null;
99
+ }
100
+ return this.extractionManifest;
101
+ }
102
+ getHashes(locale) {
103
+ return this.hashCache.get(locale) ?? {};
104
+ }
105
+ /**
106
+ * Clear translations for specified locale(s).
107
+ * @param locales - Locale(s) to clear, or all if not specified
108
+ */
109
+ clear(locales) {
110
+ const targets = this.resolveLocales(locales);
111
+ for (const locale of targets) {
112
+ this.rawCache.delete(locale);
113
+ this.compiledCache.delete(locale);
114
+ this.hashCache.delete(locale);
115
+ }
116
+ }
117
+ resolveLocales(locales) {
118
+ if (!locales) return this.config?.locales ?? [];
119
+ if (typeof locales === "string") return [locales];
120
+ return locales;
121
+ }
122
+ };
123
+ var i18n = new I18nSingleton();
124
+
125
+ export {
126
+ computeChunkHash,
127
+ i18n
128
+ };
@@ -0,0 +1,14 @@
1
+ // src/server/context.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ var als = new AsyncLocalStorage();
4
+ function runWithContext(context, fn) {
5
+ return als.run(context, fn);
6
+ }
7
+ function getContext() {
8
+ return als.getStore() ?? null;
9
+ }
10
+
11
+ export {
12
+ runWithContext,
13
+ getContext
14
+ };
@@ -0,0 +1,193 @@
1
+ import {
2
+ chunkIdToName
3
+ } from "./chunk-4A5BKHFN.js";
4
+
5
+ // src/extraction/manifest.ts
6
+ import path from "path";
7
+ var I18N_MANIFEST_GLOBAL_KEY = "__astroscope_i18n_manifest__";
8
+ function getGlobalState() {
9
+ const g = globalThis;
10
+ if (!g[I18N_MANIFEST_GLOBAL_KEY]) {
11
+ g[I18N_MANIFEST_GLOBAL_KEY] = {
12
+ extractedKeys: [],
13
+ chunkManifest: {},
14
+ projectRoot: ""
15
+ };
16
+ }
17
+ return g[I18N_MANIFEST_GLOBAL_KEY];
18
+ }
19
+ function getManifest() {
20
+ const state = getGlobalState();
21
+ const keys = state.extractedKeys.map((key) => ({
22
+ ...key,
23
+ // make file paths relative to project root for better readability
24
+ // and avoiding leaking absolute paths from dev or ci environments
25
+ file: state.projectRoot ? path.relative(state.projectRoot, key.file) : key.file
26
+ }));
27
+ return { keys, chunks: state.chunkManifest };
28
+ }
29
+
30
+ // src/extraction/vite-plugin.ts
31
+ import fs from "fs";
32
+ import path2 from "path";
33
+ import MagicString from "magic-string";
34
+ var VIRTUAL_MODULE_ID = "virtual:@astroscope/i18n/manifest";
35
+ var isVirtualModuleId = (id) => id === VIRTUAL_MODULE_ID || id.startsWith(`${VIRTUAL_MODULE_ID}?`);
36
+ var RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
37
+ var isResolvedVirtualModuleId = (id) => id === RESOLVED_VIRTUAL_MODULE_ID || id.startsWith(`\0${VIRTUAL_MODULE_ID}?`);
38
+ var MANIFEST_FILE_NAME = "i18n-manifest.json";
39
+ var INCLUDE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".astro"];
40
+ function i18nVitePlugin(options) {
41
+ const { logger } = options;
42
+ const extractedKeys = [];
43
+ const fileToKeys = /* @__PURE__ */ new Map();
44
+ const filesWithI18n = /* @__PURE__ */ new Set();
45
+ let isBuild = false;
46
+ let isSSR = false;
47
+ return {
48
+ name: "@astroscope/i18n/extract",
49
+ enforce: "pre",
50
+ configResolved(config) {
51
+ const state = getGlobalState();
52
+ state.projectRoot = config.root;
53
+ state.extractedKeys = extractedKeys;
54
+ isBuild = config.command === "build";
55
+ isSSR = !!config.build.ssr;
56
+ },
57
+ resolveId(id) {
58
+ if (isVirtualModuleId(id)) {
59
+ return `\0${id}`;
60
+ }
61
+ },
62
+ load(id) {
63
+ if (isResolvedVirtualModuleId(id)) {
64
+ if (isBuild) {
65
+ return `
66
+ import { readFileSync } from 'node:fs';
67
+ import { fileURLToPath } from 'node:url';
68
+ import { dirname, join } from 'node:path';
69
+
70
+ const __dirname = dirname(fileURLToPath(import.meta.url));
71
+ const manifestJson = JSON.parse(readFileSync(join(__dirname, '${MANIFEST_FILE_NAME}'), 'utf-8'));
72
+
73
+ export const manifest = manifestJson;
74
+ export function getManifest() { return manifestJson; }
75
+ `;
76
+ }
77
+ return `
78
+ import { getManifest as _getManifest } from '@astroscope/i18n/extraction';
79
+ export const manifest = { keys: [], chunks: {} };
80
+ export function getManifest() { return _getManifest(); }
81
+ `;
82
+ }
83
+ },
84
+ async transform(code, filename) {
85
+ if (!INCLUDE_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
86
+ return null;
87
+ }
88
+ if (filename.includes("node_modules")) {
89
+ return null;
90
+ }
91
+ if (!code.includes("@astroscope/i18n/t")) {
92
+ return null;
93
+ }
94
+ filesWithI18n.add(filename);
95
+ const fileKeys = [];
96
+ const [{ transformAsync }, { i18nExtractPlugin }] = await Promise.all([
97
+ import("@babel/core"),
98
+ import("./babel-plugin-K2K4ZPM5.js")
99
+ ]);
100
+ const result = await transformAsync(code, {
101
+ filename,
102
+ sourceMaps: true,
103
+ babelrc: false,
104
+ configFile: false,
105
+ parserOpts: {
106
+ plugins: [
107
+ ...filename.endsWith(".ts") || filename.endsWith(".tsx") ? ["typescript"] : [],
108
+ ...filename.endsWith(".jsx") || filename.endsWith(".tsx") ? ["jsx"] : []
109
+ ]
110
+ },
111
+ plugins: [
112
+ [
113
+ i18nExtractPlugin,
114
+ {
115
+ stripFallbacks: isBuild,
116
+ // only strip in production
117
+ onKeyExtracted: (key) => fileKeys.push(key),
118
+ logger
119
+ }
120
+ ]
121
+ ]
122
+ });
123
+ if (fileKeys.length > 0) {
124
+ extractedKeys.push(...fileKeys);
125
+ fileToKeys.set(
126
+ filename,
127
+ fileKeys.map((k) => k.key)
128
+ );
129
+ }
130
+ if (isBuild && result?.code) {
131
+ return { code: result.code, map: result.map };
132
+ }
133
+ return null;
134
+ },
135
+ generateBundle(_, bundle) {
136
+ const state = getGlobalState();
137
+ state.chunkManifest = {};
138
+ for (const [fileName, chunk] of Object.entries(bundle)) {
139
+ if (chunk.type === "chunk" && chunk.moduleIds) {
140
+ const keys = /* @__PURE__ */ new Set();
141
+ let hasI18nModule = false;
142
+ for (const moduleId of chunk.moduleIds) {
143
+ const moduleKeys = fileToKeys.get(moduleId);
144
+ moduleKeys?.forEach((k) => keys.add(k));
145
+ if (filesWithI18n.has(moduleId)) {
146
+ hasI18nModule = true;
147
+ }
148
+ }
149
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
150
+ if (keys.size) {
151
+ state.chunkManifest[chunkName] = Array.from(keys);
152
+ }
153
+ if (hasI18nModule) {
154
+ const loaderCode = `
155
+ /* @astroscope/i18n loader */
156
+ if (typeof window !== 'undefined' && window.__i18n__) {
157
+ const __i18n__ = window.__i18n__;
158
+ const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
159
+ if (__i18n_hash__) {
160
+ await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
161
+ }
162
+ }
163
+ /* end @astroscope/i18n loader */
164
+ `;
165
+ const s = new MagicString(chunk.code);
166
+ s.prepend(loaderCode);
167
+ chunk.code = s.toString();
168
+ if (chunk.map) {
169
+ chunk.map = s.generateMap({ hires: true });
170
+ }
171
+ }
172
+ }
173
+ }
174
+ logger.info(`manifest: ${Object.keys(state.chunkManifest).length} chunks, ${extractedKeys.length} keys`);
175
+ },
176
+ writeBundle(outputOptions) {
177
+ if (!isSSR && outputOptions.dir) {
178
+ const chunksDir = path2.resolve(outputOptions.dir, "..", "server", "chunks");
179
+ const manifestPath = path2.join(chunksDir, MANIFEST_FILE_NAME);
180
+ if (fs.existsSync(chunksDir)) {
181
+ fs.writeFileSync(manifestPath, JSON.stringify(getManifest()));
182
+ } else {
183
+ logger.error(`server chunks directory not found, cannot write manifest to ${manifestPath}`);
184
+ }
185
+ }
186
+ }
187
+ };
188
+ }
189
+
190
+ export {
191
+ getManifest,
192
+ i18nVitePlugin
193
+ };
@@ -0,0 +1,23 @@
1
+ import {
2
+ buildI18nChunkUrl,
3
+ chunkIdToName
4
+ } from "./chunk-HHRMR3TM.js";
5
+
6
+ // src/client/import-with-i18n.ts
7
+ async function importWithI18n(importFn, chunkId) {
8
+ const i18n = window.__i18n__;
9
+ const chunkName = chunkId ? chunkIdToName(chunkId) : void 0;
10
+ const hash = chunkName ? i18n.hashes[chunkName] : void 0;
11
+ const [module] = await Promise.all([
12
+ importFn(),
13
+ hash && chunkName ? import(
14
+ /* @vite-ignore */
15
+ buildI18nChunkUrl(i18n.locale, chunkName, hash)
16
+ ) : Promise.resolve()
17
+ ]);
18
+ return module;
19
+ }
20
+
21
+ export {
22
+ importWithI18n
23
+ };