@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,316 @@
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
+
309
+ export {
310
+ computeChunkHash,
311
+ computeAllChunkHashes,
312
+ createI18nService,
313
+ getI18nService,
314
+ hasI18nService,
315
+ createI18nMiddleware
316
+ };
@@ -0,0 +1,261 @@
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 MANIFEST_FILE_NAME = "i18n-manifest.json";
10
+ var globalExtractedKeys = [];
11
+ var globalChunkManifest = {};
12
+ var globalProjectRoot = "";
13
+ function getManifest() {
14
+ const keysWithRelativePaths = globalExtractedKeys.map((key) => ({
15
+ ...key,
16
+ file: globalProjectRoot ? path.relative(globalProjectRoot, key.file) : key.file
17
+ }));
18
+ return {
19
+ keys: keysWithRelativePaths,
20
+ chunks: globalChunkManifest
21
+ };
22
+ }
23
+ function extractBalancedBraces(code, startIndex) {
24
+ if (code[startIndex] !== "{") return null;
25
+ let depth = 0;
26
+ let i = startIndex;
27
+ while (i < code.length) {
28
+ if (code[i] === "{") depth++;
29
+ else if (code[i] === "}") {
30
+ depth--;
31
+ if (depth === 0) return code.slice(startIndex, i + 1);
32
+ }
33
+ i++;
34
+ }
35
+ return null;
36
+ }
37
+ function extractTranslationCalls(code, filename) {
38
+ const keys = [];
39
+ const regex = /\bt\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*/g;
40
+ let match;
41
+ while ((match = regex.exec(code)) !== null) {
42
+ const key = match[1];
43
+ const afterKey = code.slice(match.index + match[0].length);
44
+ const upToMatch = code.slice(0, match.index);
45
+ const lineNumber = (upToMatch.match(/\n/g) || []).length + 1;
46
+ try {
47
+ const stringMatch = afterKey.match(/^['"`]([^'"`]*)['"`]/);
48
+ if (stringMatch) {
49
+ keys.push({
50
+ key,
51
+ meta: { fallback: stringMatch[1] },
52
+ file: filename,
53
+ line: lineNumber
54
+ });
55
+ } else if (afterKey.startsWith("{")) {
56
+ const metaStr = extractBalancedBraces(afterKey, 0);
57
+ if (metaStr) {
58
+ const fallbackMatch = metaStr.match(/fallback\s*:\s*['"`]([^'"`]+)['"`]/);
59
+ const descMatch = metaStr.match(/description\s*:\s*['"`]([^'"`]+)['"`]/);
60
+ const fallback = fallbackMatch ? fallbackMatch[1] : "";
61
+ const description = descMatch ? descMatch[1] : void 0;
62
+ const varsBlockMatch = metaStr.match(/variables\s*:\s*\{/);
63
+ let variables;
64
+ if (varsBlockMatch) {
65
+ const varsStart = metaStr.indexOf("{", varsBlockMatch.index + varsBlockMatch[0].length - 1);
66
+ const varsStr = extractBalancedBraces(metaStr, varsStart);
67
+ if (varsStr) {
68
+ variables = parseVariables(varsStr);
69
+ }
70
+ }
71
+ keys.push({
72
+ key,
73
+ meta: { fallback, description, variables },
74
+ file: filename,
75
+ line: lineNumber
76
+ });
77
+ }
78
+ }
79
+ } catch {
80
+ }
81
+ }
82
+ return keys;
83
+ }
84
+ function parseVariables(str) {
85
+ const result = {};
86
+ const varNameRegex = /(\w+)\s*:\s*\{/g;
87
+ let nameMatch;
88
+ while ((nameMatch = varNameRegex.exec(str)) !== null) {
89
+ const varName = nameMatch[1];
90
+ const varStart = str.indexOf("{", nameMatch.index + nameMatch[0].length - 1);
91
+ const varObj = extractBalancedBraces(str, varStart);
92
+ if (varObj) {
93
+ const fallbackMatch = varObj.match(/fallback\s*:\s*['"`]([^'"`]*)['"`]/);
94
+ const descMatch = varObj.match(/description\s*:\s*['"`]([^'"`]*)['"`]/);
95
+ result[varName] = {
96
+ fallback: fallbackMatch ? fallbackMatch[1] : void 0,
97
+ description: descMatch ? descMatch[1] : void 0
98
+ };
99
+ }
100
+ }
101
+ return Object.keys(result).length > 0 ? result : void 0;
102
+ }
103
+ function hasI18nImport(code) {
104
+ return /@astroscope\/i18n\/t/.test(code);
105
+ }
106
+ function i18nVitePlugin(options) {
107
+ const { include = [".ts", ".tsx", ".js", ".jsx", ".astro"], logger } = options;
108
+ const extractedKeys = [];
109
+ const fileToKeys = /* @__PURE__ */ new Map();
110
+ const filesWithI18n = /* @__PURE__ */ new Set();
111
+ let chunkManifest = {};
112
+ let projectRoot = "";
113
+ let isBuild = false;
114
+ let isSSR = false;
115
+ return {
116
+ name: "@astroscope/i18n/extract",
117
+ enforce: "pre",
118
+ configResolved(config) {
119
+ projectRoot = config.root;
120
+ globalProjectRoot = config.root;
121
+ isBuild = config.command === "build";
122
+ isSSR = !!config.build.ssr;
123
+ },
124
+ resolveId(id) {
125
+ if (id === VIRTUAL_MODULE_ID) {
126
+ return RESOLVED_VIRTUAL_MODULE_ID;
127
+ }
128
+ if (id.startsWith(`${VIRTUAL_MODULE_ID}?`)) {
129
+ return `\0${id}`;
130
+ }
131
+ },
132
+ load(id) {
133
+ if (id === RESOLVED_VIRTUAL_MODULE_ID || id.startsWith(`\0${VIRTUAL_MODULE_ID}?`)) {
134
+ if (isBuild) {
135
+ return `
136
+ import { readFileSync, existsSync } from 'node:fs';
137
+ import { fileURLToPath } from 'node:url';
138
+ import { dirname, join } from 'node:path';
139
+
140
+ const __dirname = dirname(fileURLToPath(import.meta.url));
141
+ const manifestName = '${MANIFEST_FILE_NAME}';
142
+
143
+ // manifest is emitted to server directory (not publicly accessible)
144
+ const searchPaths = [
145
+ join(__dirname, manifestName), // same dir (server/)
146
+ join(__dirname, '..', manifestName), // parent dir (from chunks/)
147
+ ];
148
+
149
+ let manifestPath = searchPaths.find(p => existsSync(p));
150
+ if (!manifestPath) {
151
+ console.warn('[i18n] manifest not found, using empty manifest');
152
+ manifestPath = null;
153
+ }
154
+
155
+ const manifestJson = manifestPath
156
+ ? JSON.parse(readFileSync(manifestPath, 'utf-8'))
157
+ : { keys: [], chunks: {} };
158
+
159
+ export const manifest = manifestJson;
160
+ export function getManifest() { return manifestJson; }
161
+ `;
162
+ }
163
+ const keysWithRelativePaths = extractedKeys.map((key) => ({
164
+ ...key,
165
+ file: projectRoot ? path.relative(projectRoot, key.file) : key.file
166
+ }));
167
+ const manifest = {
168
+ keys: keysWithRelativePaths,
169
+ chunks: chunkManifest
170
+ };
171
+ return `
172
+ export const manifest = ${JSON.stringify(manifest)};
173
+ export function getManifest() { return ${JSON.stringify(manifest)}; }
174
+ `;
175
+ }
176
+ },
177
+ transform(code, id) {
178
+ if (!include.some((ext) => id.endsWith(ext))) {
179
+ return null;
180
+ }
181
+ if (id.includes("node_modules")) {
182
+ return null;
183
+ }
184
+ if (hasI18nImport(code)) {
185
+ filesWithI18n.add(id);
186
+ }
187
+ const keys = extractTranslationCalls(code, id);
188
+ if (keys.length > 0) {
189
+ extractedKeys.push(...keys);
190
+ globalExtractedKeys = extractedKeys;
191
+ fileToKeys.set(
192
+ id,
193
+ keys.map((k) => k.key)
194
+ );
195
+ }
196
+ return null;
197
+ },
198
+ generateBundle(_, bundle) {
199
+ chunkManifest = {};
200
+ for (const [fileName, chunk] of Object.entries(bundle)) {
201
+ if (chunk.type === "chunk" && chunk.moduleIds) {
202
+ const keys = /* @__PURE__ */ new Set();
203
+ let hasI18nModule = false;
204
+ for (const moduleId of chunk.moduleIds) {
205
+ const moduleKeys = fileToKeys.get(moduleId);
206
+ if (moduleKeys) {
207
+ moduleKeys.forEach((k) => keys.add(k));
208
+ }
209
+ if (filesWithI18n.has(moduleId)) {
210
+ hasI18nModule = true;
211
+ }
212
+ }
213
+ if (keys.size > 0) {
214
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
215
+ chunkManifest[chunkName] = Array.from(keys);
216
+ }
217
+ if (hasI18nModule && chunk.type === "chunk") {
218
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
219
+ const loaderCode = `
220
+ /* @astroscope/i18n loader */
221
+ if (typeof window !== 'undefined' && window.__i18n__) {
222
+ const __i18n__ = window.__i18n__;
223
+ const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
224
+ if (__i18n_hash__) {
225
+ await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
226
+ }
227
+ }
228
+ /* end @astroscope/i18n loader */
229
+ `;
230
+ chunk.code = loaderCode + chunk.code;
231
+ }
232
+ }
233
+ }
234
+ globalChunkManifest = chunkManifest;
235
+ if (!isSSR) {
236
+ const keysWithRelativePaths = extractedKeys.map((key) => ({
237
+ ...key,
238
+ file: projectRoot ? path.relative(projectRoot, key.file) : key.file
239
+ }));
240
+ const manifest = {
241
+ keys: keysWithRelativePaths,
242
+ chunks: chunkManifest
243
+ };
244
+ this.emitFile({
245
+ type: "asset",
246
+ // emit to ../server/ directory (relative to client output)
247
+ fileName: `../server/${MANIFEST_FILE_NAME}`,
248
+ source: JSON.stringify(manifest)
249
+ });
250
+ }
251
+ const chunkCount = Object.keys(chunkManifest).length;
252
+ const keyCount = extractedKeys.length;
253
+ logger?.info(`manifest: ${chunkCount} chunks, ${keyCount} keys`);
254
+ }
255
+ };
256
+ }
257
+
258
+ export {
259
+ getManifest,
260
+ i18nVitePlugin
261
+ };