@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,202 @@
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
+ },
124
+ load(id) {
125
+ if (id === RESOLVED_VIRTUAL_MODULE_ID) {
126
+ return `
127
+ import { getManifest } from '@astroscope/i18n/extraction';
128
+ export { getManifest };
129
+ // for static import compatibility, also export current snapshot
130
+ export const manifest = getManifest();
131
+ `;
132
+ }
133
+ },
134
+ transform(code, id) {
135
+ if (!include.some((ext) => id.endsWith(ext))) {
136
+ return null;
137
+ }
138
+ if (id.includes("node_modules")) {
139
+ return null;
140
+ }
141
+ if (hasI18nImport(code)) {
142
+ filesWithI18n.add(id);
143
+ }
144
+ const keys = extractTranslationCalls(code, id);
145
+ if (keys.length > 0) {
146
+ extractedKeys.push(...keys);
147
+ globalExtractedKeys = extractedKeys;
148
+ fileToKeys.set(
149
+ id,
150
+ keys.map((k) => k.key)
151
+ );
152
+ }
153
+ return null;
154
+ },
155
+ generateBundle(_, bundle) {
156
+ chunkManifest = {};
157
+ for (const [fileName, chunk] of Object.entries(bundle)) {
158
+ if (chunk.type === "chunk" && chunk.moduleIds) {
159
+ const keys = /* @__PURE__ */ new Set();
160
+ let hasI18nModule = false;
161
+ for (const moduleId of chunk.moduleIds) {
162
+ const moduleKeys = fileToKeys.get(moduleId);
163
+ if (moduleKeys) {
164
+ moduleKeys.forEach((k) => keys.add(k));
165
+ }
166
+ if (filesWithI18n.has(moduleId)) {
167
+ hasI18nModule = true;
168
+ }
169
+ }
170
+ if (keys.size > 0) {
171
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
172
+ chunkManifest[chunkName] = Array.from(keys);
173
+ }
174
+ if (hasI18nModule && chunk.type === "chunk") {
175
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
176
+ const loaderCode = `
177
+ /* @astroscope/i18n loader */
178
+ if (typeof window !== 'undefined' && window.__i18n__) {
179
+ const __i18n__ = window.__i18n__;
180
+ const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
181
+ if (__i18n_hash__) {
182
+ await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
183
+ }
184
+ }
185
+ /* end @astroscope/i18n loader */
186
+ `;
187
+ chunk.code = loaderCode + chunk.code;
188
+ }
189
+ }
190
+ }
191
+ globalChunkManifest = chunkManifest;
192
+ const chunkCount = Object.keys(chunkManifest).length;
193
+ const keyCount = extractedKeys.length;
194
+ logger?.info(`manifest: ${chunkCount} chunks, ${keyCount} keys`);
195
+ }
196
+ };
197
+ }
198
+
199
+ export {
200
+ getManifest,
201
+ i18nVitePlugin
202
+ };
@@ -0,0 +1,149 @@
1
+ import {
2
+ compileTranslations
3
+ } from "./chunk-KNDYKTHE.js";
4
+
5
+ // src/extraction/hash.ts
6
+ import { createHash } from "crypto";
7
+ function hashString(str) {
8
+ return createHash("sha256").update(str).digest("hex").substring(0, 8);
9
+ }
10
+ function computeChunkHash(translations, keys) {
11
+ const relevantTranslations = {};
12
+ for (const key of keys.sort()) {
13
+ if (translations[key]) {
14
+ relevantTranslations[key] = translations[key];
15
+ }
16
+ }
17
+ return hashString(JSON.stringify(relevantTranslations));
18
+ }
19
+ function computeAllChunkHashes(translations, manifest) {
20
+ const hashes = {};
21
+ for (const [chunkId, keys] of Object.entries(manifest)) {
22
+ hashes[chunkId] = computeChunkHash(translations, keys);
23
+ }
24
+ return hashes;
25
+ }
26
+
27
+ // src/server/i18n.ts
28
+ var I18nSingleton = class {
29
+ // normalized user config with defaults applied
30
+ config = null;
31
+ // locale -> raw translation strings (before ICU compilation)
32
+ rawCache = /* @__PURE__ */ new Map();
33
+ // locale -> compiled ICU MessageFormat functions
34
+ compiledCache = /* @__PURE__ */ new Map();
35
+ // locale -> chunk name -> content hash (for cache busting)
36
+ hashCache = /* @__PURE__ */ new Map();
37
+ // extraction manifest (injected by middleware entrypoint from virtual module)
38
+ manifest = { keys: [], chunks: {} };
39
+ configure(config) {
40
+ if (!config.locales?.length) {
41
+ throw new Error("i18n.configure(): locales array is required and must not be empty");
42
+ }
43
+ for (const locale of config.locales) {
44
+ if (!locale) {
45
+ throw new Error("i18n.configure(): locale cannot be empty");
46
+ }
47
+ if (locale !== locale.trim()) {
48
+ throw new Error(`i18n.configure(): locale "${locale}" has leading or trailing whitespace`);
49
+ }
50
+ }
51
+ if (new Set(config.locales).size !== config.locales.length) {
52
+ throw new Error("i18n.configure(): locales array contains duplicates");
53
+ }
54
+ if (config.defaultLocale !== void 0) {
55
+ if (!config.defaultLocale) {
56
+ throw new Error("i18n.configure(): defaultLocale cannot be empty");
57
+ }
58
+ if (config.defaultLocale !== config.defaultLocale.trim()) {
59
+ throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" has leading or trailing whitespace`);
60
+ }
61
+ if (!config.locales.includes(config.defaultLocale)) {
62
+ throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" is not in locales array`);
63
+ }
64
+ }
65
+ this.config = {
66
+ locales: config.locales,
67
+ defaultLocale: config.defaultLocale ?? config.locales[0],
68
+ fallback: config.fallback ?? "fallback"
69
+ };
70
+ }
71
+ isConfigured() {
72
+ return this.config !== null;
73
+ }
74
+ getConfig() {
75
+ if (!this.config) {
76
+ throw new Error("i18n not configured. Call i18n.configure() first.");
77
+ }
78
+ return this.config;
79
+ }
80
+ setTranslations(locale, raw) {
81
+ this.rawCache.set(locale, raw);
82
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
83
+ this.hashCache.delete(locale);
84
+ const chunks = this.getChunkManifest();
85
+ if (Object.keys(chunks).length > 0) {
86
+ this.hashCache.set(locale, computeAllChunkHashes(raw, chunks));
87
+ }
88
+ }
89
+ getTranslations(locale) {
90
+ return this.rawCache.get(locale) ?? {};
91
+ }
92
+ getCompiledTranslations(locale) {
93
+ return this.compiledCache.get(locale) ?? {};
94
+ }
95
+ getChunkManifest() {
96
+ return this.getExtractionManifest().chunks;
97
+ }
98
+ /**
99
+ * Get extracted translation keys with metadata.
100
+ * Use this to populate your translation provider with keys extracted from the codebase.
101
+ */
102
+ getExtractedKeys() {
103
+ return this.getExtractionManifest().keys;
104
+ }
105
+ /**
106
+ * Get the full extraction manifest (keys + chunks).
107
+ * In dev mode, keys are available live but chunks are empty.
108
+ * In build mode, both keys and chunk mappings are populated.
109
+ */
110
+ getExtractionManifest() {
111
+ return this.manifest;
112
+ }
113
+ /**
114
+ * Set the extraction manifest (called by middleware entrypoint).
115
+ * @internal
116
+ */
117
+ setManifest(manifest) {
118
+ this.manifest = manifest;
119
+ }
120
+ getHashes(locale) {
121
+ return this.hashCache.get(locale) ?? {};
122
+ }
123
+ /**
124
+ * Clear translations for specified locale(s).
125
+ * @param locales - Locale(s) to clear, or all if not specified
126
+ */
127
+ clear(locales) {
128
+ const targets = this.resolveLocales(locales);
129
+ for (const locale of targets) {
130
+ this.rawCache.delete(locale);
131
+ this.compiledCache.delete(locale);
132
+ this.hashCache.delete(locale);
133
+ }
134
+ }
135
+ resolveLocales(locales) {
136
+ if (!locales) {
137
+ return this.config?.locales ?? [];
138
+ }
139
+ if (typeof locales === "string") {
140
+ return [locales];
141
+ }
142
+ return locales;
143
+ }
144
+ };
145
+ var i18n = new I18nSingleton();
146
+
147
+ export {
148
+ i18n
149
+ };
@@ -0,0 +1,52 @@
1
+ // src/server/messageformat.ts
2
+ import MessageFormat from "@messageformat/core";
3
+ var mfCache = /* @__PURE__ */ new Map();
4
+ function getMessageFormat(locale) {
5
+ let mf = mfCache.get(locale);
6
+ if (!mf) {
7
+ mf = new MessageFormat(locale);
8
+ mfCache.set(locale, mf);
9
+ }
10
+ return mf;
11
+ }
12
+ function compileMessage(locale, message) {
13
+ const mf = getMessageFormat(locale);
14
+ try {
15
+ return mf.compile(message);
16
+ } catch {
17
+ return (values) => {
18
+ if (!values) return message;
19
+ return Object.entries(values).reduce(
20
+ (result, [key, value]) => result.replace(new RegExp(`\\{${key}\\}`, "g"), String(value)),
21
+ message
22
+ );
23
+ };
24
+ }
25
+ }
26
+ function compileTranslations(locale, raw) {
27
+ const compiled = {};
28
+ for (const [key, message] of Object.entries(raw)) {
29
+ compiled[key] = compileMessage(locale, message);
30
+ }
31
+ return compiled;
32
+ }
33
+
34
+ // src/server/context.ts
35
+ var currentContext = null;
36
+ function setContext(context) {
37
+ currentContext = context;
38
+ }
39
+ function getContext() {
40
+ return currentContext;
41
+ }
42
+ function clearContext() {
43
+ currentContext = null;
44
+ }
45
+
46
+ export {
47
+ compileMessage,
48
+ compileTranslations,
49
+ setContext,
50
+ getContext,
51
+ clearContext
52
+ };
@@ -0,0 +1,56 @@
1
+ import {
2
+ clearContext,
3
+ compileTranslations,
4
+ setContext
5
+ } from "./chunk-KNONI6DP.js";
6
+
7
+ // src/middleware.ts
8
+ function defaultDetectLocale(request, locales, defaultLocale) {
9
+ const acceptLanguage = request.headers.get("accept-language");
10
+ if (!acceptLanguage) {
11
+ return defaultLocale;
12
+ }
13
+ const preferred = acceptLanguage.split(",").map((part) => {
14
+ const [lang, q = "q=1"] = part.trim().split(";");
15
+ return {
16
+ lang: lang.split("-")[0].toLowerCase(),
17
+ q: parseFloat(q.replace("q=", ""))
18
+ };
19
+ }).sort((a, b) => b.q - a.q);
20
+ for (const { lang } of preferred) {
21
+ if (locales.includes(lang)) {
22
+ return lang;
23
+ }
24
+ }
25
+ return defaultLocale;
26
+ }
27
+ var translationCache = /* @__PURE__ */ new Map();
28
+ function createI18nMiddleware(options) {
29
+ const { locales, defaultLocale, fallback, cms, detectLocale } = options;
30
+ return async (ctx, next) => {
31
+ const locale = detectLocale ? detectLocale(ctx.request) : ctx.currentLocale ?? defaultDetectLocale(ctx.request, locales, defaultLocale);
32
+ let raw = translationCache.get(locale);
33
+ if (!raw) {
34
+ raw = await cms.fetch(locale, []);
35
+ translationCache.set(locale, raw);
36
+ }
37
+ const translations = compileTranslations(locale, raw);
38
+ const context = {
39
+ locale,
40
+ translations,
41
+ fallback,
42
+ meta: {}
43
+ };
44
+ setContext(context);
45
+ try {
46
+ const response = await next();
47
+ return response;
48
+ } finally {
49
+ clearContext();
50
+ }
51
+ };
52
+ }
53
+
54
+ export {
55
+ createI18nMiddleware
56
+ };
@@ -0,0 +1,16 @@
1
+ // src/client-directives/utils.ts
2
+ async function loadI18nForChunk(el) {
3
+ const componentUrl = el.getAttribute("component-url");
4
+ if (!componentUrl) return;
5
+ const chunkId = componentUrl.replace(/^\//, "").replace(/\.js$/, "");
6
+ const hash = window.__i18n_hashes__?.[chunkId];
7
+ const locale = window.__i18n_locale__ || "en";
8
+ if (hash) {
9
+ const chunkName = chunkId.replace(/^_astro\//, "");
10
+ await import(`/_i18n/${locale}/${chunkName}.${hash}.js`);
11
+ }
12
+ }
13
+
14
+ export {
15
+ loadI18nForChunk
16
+ };
@@ -0,0 +1,21 @@
1
+ import {
2
+ buildI18nChunkUrl
3
+ } from "./chunk-OFNFSDW3.js";
4
+
5
+ // src/import-with-i18n.ts
6
+ async function importWithI18n(importFn, chunkId) {
7
+ const hash = chunkId ? window.__i18n_hashes__?.[chunkId] : void 0;
8
+ const locale = window.__i18n_locale__ || "en";
9
+ const [module] = await Promise.all([
10
+ importFn(),
11
+ hash && chunkId ? import(
12
+ /* @vite-ignore */
13
+ buildI18nChunkUrl(locale, chunkId, hash)
14
+ ) : Promise.resolve()
15
+ ]);
16
+ return module;
17
+ }
18
+
19
+ export {
20
+ importWithI18n
21
+ };
@@ -0,0 +1,12 @@
1
+ // src/client/import-with-i18n.ts
2
+ async function importx(importFn) {
3
+ return importFn();
4
+ }
5
+ function lazyx(importFn) {
6
+ return importFn;
7
+ }
8
+
9
+ export {
10
+ importx,
11
+ lazyx
12
+ };
@@ -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 serverDir = path2.resolve(outputOptions.dir, "..", "server");
179
+ const manifestPath = path2.join(serverDir, MANIFEST_FILE_NAME);
180
+ if (fs.existsSync(serverDir)) {
181
+ fs.writeFileSync(manifestPath, JSON.stringify(getManifest()));
182
+ } else {
183
+ logger.error(`server directory not found, cannot write manifest to ${manifestPath}`);
184
+ }
185
+ }
186
+ }
187
+ };
188
+ }
189
+
190
+ export {
191
+ getManifest,
192
+ i18nVitePlugin
193
+ };