i18n-json-react 0.0.0-stage → 0.1.1

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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +401 -2
  3. package/bundlers/shared.cjs +91 -0
  4. package/dist/cjs/api-types.d.ts +17 -0
  5. package/dist/cjs/api-types.d.ts.map +1 -0
  6. package/dist/cjs/api-types.js +3 -0
  7. package/dist/cjs/api-types.js.map +1 -0
  8. package/dist/cjs/core.d.ts +10 -0
  9. package/dist/cjs/core.d.ts.map +1 -0
  10. package/dist/cjs/core.js +31 -0
  11. package/dist/cjs/core.js.map +1 -0
  12. package/dist/cjs/default-store.d.ts +7 -0
  13. package/dist/cjs/default-store.d.ts.map +1 -0
  14. package/dist/cjs/default-store.js +96 -0
  15. package/dist/cjs/default-store.js.map +1 -0
  16. package/dist/cjs/dictionaries.d.ts +7 -0
  17. package/dist/cjs/dictionaries.d.ts.map +1 -0
  18. package/dist/cjs/dictionaries.js +31 -0
  19. package/dist/cjs/dictionaries.js.map +1 -0
  20. package/dist/cjs/index.d.ts +24 -0
  21. package/dist/cjs/index.d.ts.map +1 -0
  22. package/dist/cjs/index.js +38 -0
  23. package/dist/cjs/index.js.map +1 -0
  24. package/dist/cjs/interpolation.d.ts +6 -0
  25. package/dist/cjs/interpolation.d.ts.map +1 -0
  26. package/dist/cjs/interpolation.js +26 -0
  27. package/dist/cjs/interpolation.js.map +1 -0
  28. package/dist/cjs/languages.d.ts +4 -0
  29. package/dist/cjs/languages.d.ts.map +1 -0
  30. package/dist/cjs/languages.js +61 -0
  31. package/dist/cjs/languages.js.map +1 -0
  32. package/dist/cjs/package.json +1 -0
  33. package/dist/cjs/react.d.ts +15 -0
  34. package/dist/cjs/react.d.ts.map +1 -0
  35. package/dist/cjs/react.js +54 -0
  36. package/dist/cjs/react.js.map +1 -0
  37. package/dist/cjs/resource.d.ts +8 -0
  38. package/dist/cjs/resource.d.ts.map +1 -0
  39. package/dist/cjs/resource.js +34 -0
  40. package/dist/cjs/resource.js.map +1 -0
  41. package/dist/cjs/store-types.d.ts +10 -0
  42. package/dist/cjs/store-types.d.ts.map +1 -0
  43. package/dist/cjs/store-types.js +17 -0
  44. package/dist/cjs/store-types.js.map +1 -0
  45. package/dist/cjs/store.d.ts +24 -0
  46. package/dist/cjs/store.d.ts.map +1 -0
  47. package/dist/cjs/store.js +139 -0
  48. package/dist/cjs/store.js.map +1 -0
  49. package/dist/cjs/typed-react.d.ts +5 -0
  50. package/dist/cjs/typed-react.d.ts.map +1 -0
  51. package/dist/cjs/typed-react.js +23 -0
  52. package/dist/cjs/typed-react.js.map +1 -0
  53. package/dist/cjs/types.d.ts +91 -0
  54. package/dist/cjs/types.d.ts.map +1 -0
  55. package/dist/cjs/types.js +3 -0
  56. package/dist/cjs/types.js.map +1 -0
  57. package/dist/esm/api-types.d.ts +17 -0
  58. package/dist/esm/api-types.d.ts.map +1 -0
  59. package/dist/esm/api-types.js +2 -0
  60. package/dist/esm/api-types.js.map +1 -0
  61. package/dist/esm/core.d.ts +10 -0
  62. package/dist/esm/core.d.ts.map +1 -0
  63. package/dist/esm/core.js +25 -0
  64. package/dist/esm/core.js.map +1 -0
  65. package/dist/esm/default-store.d.ts +7 -0
  66. package/dist/esm/default-store.d.ts.map +1 -0
  67. package/dist/esm/default-store.js +93 -0
  68. package/dist/esm/default-store.js.map +1 -0
  69. package/dist/esm/dictionaries.d.ts +7 -0
  70. package/dist/esm/dictionaries.d.ts.map +1 -0
  71. package/dist/esm/dictionaries.js +26 -0
  72. package/dist/esm/dictionaries.js.map +1 -0
  73. package/dist/esm/index.d.ts +24 -0
  74. package/dist/esm/index.d.ts.map +1 -0
  75. package/dist/esm/index.js +31 -0
  76. package/dist/esm/index.js.map +1 -0
  77. package/dist/esm/interpolation.d.ts +6 -0
  78. package/dist/esm/interpolation.d.ts.map +1 -0
  79. package/dist/esm/interpolation.js +22 -0
  80. package/dist/esm/interpolation.js.map +1 -0
  81. package/dist/esm/languages.d.ts +4 -0
  82. package/dist/esm/languages.d.ts.map +1 -0
  83. package/dist/esm/languages.js +57 -0
  84. package/dist/esm/languages.js.map +1 -0
  85. package/dist/esm/package.json +1 -0
  86. package/dist/esm/react.d.ts +15 -0
  87. package/dist/esm/react.d.ts.map +1 -0
  88. package/dist/esm/react.js +51 -0
  89. package/dist/esm/react.js.map +1 -0
  90. package/dist/esm/resource.d.ts +8 -0
  91. package/dist/esm/resource.d.ts.map +1 -0
  92. package/dist/esm/resource.js +31 -0
  93. package/dist/esm/resource.js.map +1 -0
  94. package/dist/esm/store-types.d.ts +10 -0
  95. package/dist/esm/store-types.d.ts.map +1 -0
  96. package/dist/esm/store-types.js +14 -0
  97. package/dist/esm/store-types.js.map +1 -0
  98. package/dist/esm/store.d.ts +24 -0
  99. package/dist/esm/store.d.ts.map +1 -0
  100. package/dist/esm/store.js +136 -0
  101. package/dist/esm/store.js.map +1 -0
  102. package/dist/esm/typed-react.d.ts +5 -0
  103. package/dist/esm/typed-react.d.ts.map +1 -0
  104. package/dist/esm/typed-react.js +20 -0
  105. package/dist/esm/typed-react.js.map +1 -0
  106. package/dist/esm/types.d.ts +91 -0
  107. package/dist/esm/types.d.ts.map +1 -0
  108. package/dist/esm/types.js +2 -0
  109. package/dist/esm/types.js.map +1 -0
  110. package/dist/types/registry.d.cts +10 -0
  111. package/native/README.md +179 -0
  112. package/native/android/README.md +14 -0
  113. package/native/android/cli.cjs +2 -0
  114. package/native/android/expo.cjs +1 -0
  115. package/native/android/expo.d.cts +1 -0
  116. package/native/android/index.cjs +3 -0
  117. package/native/android/index.d.cts +5 -0
  118. package/native/android/metro.cjs +3 -0
  119. package/native/android/metro.d.cts +7 -0
  120. package/native/android/prepare.cjs +3 -0
  121. package/native/cli.cjs +43 -0
  122. package/native/expo.cjs +17 -0
  123. package/native/expo.d.cts +7 -0
  124. package/native/index.cjs +18 -0
  125. package/native/index.d.cts +14 -0
  126. package/native/ios/README.md +58 -0
  127. package/native/ios/cli.cjs +2 -0
  128. package/native/ios/expo.cjs +1 -0
  129. package/native/ios/expo.d.cts +1 -0
  130. package/native/ios/index.cjs +3 -0
  131. package/native/ios/index.d.cts +5 -0
  132. package/native/ios/metro.cjs +3 -0
  133. package/native/ios/metro.d.cts +7 -0
  134. package/native/ios/prepare.cjs +3 -0
  135. package/native/metro.cjs +45 -0
  136. package/native/metro.d.cts +34 -0
  137. package/native/prepare.cjs +120 -0
  138. package/package.json +165 -4
  139. package/src/api-types.ts +42 -0
  140. package/src/core.ts +29 -0
  141. package/src/default-store.ts +106 -0
  142. package/src/dictionaries.ts +31 -0
  143. package/src/index.ts +46 -0
  144. package/src/interpolation.ts +31 -0
  145. package/src/languages.ts +62 -0
  146. package/src/react.ts +83 -0
  147. package/src/resource.ts +40 -0
  148. package/src/store-types.ts +36 -0
  149. package/src/store.ts +150 -0
  150. package/src/typed-react.ts +33 -0
  151. package/src/types.ts +113 -0
  152. package/types/registry.d.cts +10 -0
  153. package/vite/index.cjs +145 -0
  154. package/vite/index.d.cts +15 -0
  155. package/webpack/index.cjs +46 -0
  156. package/webpack/index.d.cts +22 -0
  157. package/webpack/loader.cjs +21 -0
@@ -0,0 +1,179 @@
1
+ # Android and iOS / React Native
2
+
3
+ Android and iOS use the same feature-local `i18n.json` and `*.i18n.json` files, React helpers, and type registration as the PWA. Keep translated source beside shared features; only platform startup and bundler setup differ.
4
+
5
+ The integration targets Metro and provides an Expo SDK 54+ asset reader. It also exposes a reader callback for other React Native setups. It contains no custom Kotlin/Swift module or build plugin.
6
+
7
+ ## How loading works
8
+
9
+ During Metro configuration, `withI18nMetro` collects the feature JSON and generates:
10
+
11
+ ```text
12
+ .i18n-json-react/
13
+ assets/EN.i18npack
14
+ assets/UK.i18npack
15
+ references/<feature-id>.js
16
+ manifest.cjs
17
+ manifest.d.cts
18
+ ```
19
+
20
+ Each feature import resolves to a tiny `{ __id }` module. Language text lives in separate data assets, outside the main JavaScript/Hermes bundle. The manifest contains lazy, static `require` calls so Metro includes the files in the Android/iOS asset graph without reading their text into JavaScript on startup.
21
+
22
+ The runtime reads and parses only the fallback and selected locale. Switching to another language reads that locale on demand. The existing I18N resource cache deduplicates concurrent loads and retains previously loaded locales; retry and Suspense behavior are unchanged.
23
+
24
+ All generated languages are packaged by default, providing offline availability. They still contribute to application size. The `languages` build option can restrict the app binary to a smaller set. To keep additional locales outside the app binary entirely, host the generated language files and use a network loader with an application-owned offline cache instead.
25
+
26
+ This uses Metro's normal asset pipeline. Expo's automatic production code splitting is documented for web; its native production route imports remain synchronous. Separating translation data from JavaScript avoids relying on native code splitting. See [Expo Metro assets and bundle splitting](https://docs.expo.dev/versions/latest/config/metro/) and [Expo async routes caveats](https://docs.expo.dev/router/web/async-routes/).
27
+
28
+ ## Expo setup
29
+
30
+ Install the optional native dependencies in the Expo app, using Expo to choose SDK-compatible versions:
31
+
32
+ ```sh
33
+ npx expo install expo-asset expo-file-system
34
+ ```
35
+
36
+ Compose your existing Metro configuration:
37
+
38
+ ```js
39
+ // native/metro.config.js
40
+ const path = require('node:path');
41
+ const { getDefaultConfig } = require('expo/metro-config');
42
+ const { withI18nMetro } = require('i18n-json-react/native/metro');
43
+
44
+ const config = getDefaultConfig(__dirname);
45
+ config.watchFolders = [path.resolve(__dirname, '..')];
46
+
47
+ module.exports = withI18nMetro(config, {
48
+ root: '..',
49
+ dirs: ['src', 'native'],
50
+ exclude: ['native/android/**', 'native/ios/**', 'native/dist/**', 'native/.expo/**'],
51
+ });
52
+ ```
53
+
54
+ Metro accepts the returned promise. The helper preserves your existing transformer, asset plugins, resolver settings, and custom resolver, then adds the generated asset extension and feature-import resolution. Keep your existing monorepo `nodeModulesPaths`, SVG transformer, or other custom configuration before this call.
55
+
56
+ `projectRoot` is the Expo app folder (`native/` here); `root: '..'` sets the shared workspace as the source and ID root. Generated files default to `native/.i18n-json-react/`. Add that directory to `.gitignore`.
57
+
58
+ In the shared native startup module:
59
+
60
+ ```ts
61
+ // native/i18n.ts
62
+ import I18N from 'i18n-json-react';
63
+ import { createExpoDictionaryLoader } from 'i18n-json-react/native/expo';
64
+ import assets from './.i18n-json-react/manifest.cjs';
65
+
66
+ I18N.configure({
67
+ supportedLanguages: ['EN', 'UK'],
68
+ fallbackLanguage: 'UK',
69
+ storage: false,
70
+ loadDictionary: createExpoDictionaryLoader(assets),
71
+ });
72
+ ```
73
+
74
+ Load this setup before rendering translated content. You can await `I18N.loadLanguage()` before showing the app, or put translated UI and `LoaderForI18N` inside a `Suspense` boundary with an error boundary for I/O failures. The generated manifest's declarations preserve its exact locale names for the loader type.
75
+
76
+ The same Metro configuration and startup code work for both `android` and `ios`. Platform entry points under `/native/android` and `/native/ios` are also available; they delegate to this shared implementation. Existing Android imports and CLI commands continue to work.
77
+
78
+ The Expo adapter calls `Asset.fromModule` only for a requested locale, resolves a local asset with `downloadAsync` when necessary, then uses `File.text()` to read it. In an Android or iOS release build this resolves the bundled resource locally; in development Expo may obtain the requested asset from Metro. It does not load every language via `Asset.loadAsync`. See [Expo Asset](https://docs.expo.dev/versions/latest/sdk/asset/) and [Expo FileSystem](https://docs.expo.dev/versions/latest/sdk/filesystem/).
79
+
80
+ ### Device language and saved choices
81
+
82
+ React Native does not provide browser `localStorage` or reliable `navigator.languages`. Use `storage: false`. For device locale detection, install `expo-localization` and pass its tags explicitly:
83
+
84
+ ```ts
85
+ import { getLocales } from 'expo-localization';
86
+
87
+ // In the same configure call:
88
+ getBrowserLanguages: () => getLocales().map(locale => locale.languageTag),
89
+ ```
90
+
91
+ To persist choices with AsyncStorage, read the saved string asynchronously during startup, normalize it with `I18N.resolveLanguage`, then call `I18N.setCurrentLang` before rendering/loading. Persist subsequent language changes from a subscription. AsyncStorage cannot be passed as the synchronous `storage` adapter.
92
+
93
+ ```ts
94
+ const saved = await AsyncStorage.getItem('ui-language');
95
+ const language = saved ? I18N.resolveLanguage(saved) : undefined;
96
+ if (language) I18N.setCurrentLang(language);
97
+
98
+ let previous = I18N.getCurrentLang();
99
+ I18N.subscribe(() => {
100
+ const current = I18N.getCurrentLang();
101
+ if (current === previous) return;
102
+ previous = current;
103
+ void AsyncStorage.setItem('ui-language', current).catch(console.error);
104
+ });
105
+ await I18N.loadLanguage();
106
+ ```
107
+
108
+ `EN` / `UK`, regional identifiers, custom interpolation, and `CustomTypeOptions` all work exactly as in the PWA. Case must match the JSON locale keys.
109
+
110
+ ## Shared PWA / Android / iOS source
111
+
112
+ For Health Ledger's layout, the intended setup is:
113
+
114
+ | Location | Responsibility |
115
+ | ---------------------------- | ----------------------------------------------------------------------------------------- |
116
+ | `src/features/.../i18n.json` | Shared feature translations |
117
+ | `src/features/.../i18n.ts` | Shared hooks importing `createUseTypo` from the package |
118
+ | `pwa/i18n.ts` | Browser configuration with `createFetchDictionaryLoader` |
119
+ | `native/i18n.ts` | Native configuration with `createExpoDictionaryLoader` |
120
+ | Root `vite.config.ts` | `i18nJsonPlugin({ root: '..', dirs: ['src', 'pwa'] })` when Vite's project root is `pwa/` |
121
+ | `native/metro.config.js` | `withI18nMetro(config, { root: '..', dirs: ['src', 'native'] })` |
122
+
123
+ Use the **same absolute ID root** (the workspace) for both bundlers. Both integrations use the same collection, validation, and file-ID algorithm. Shared feature code imports neither `pwa/` nor `native/` setup modules. Each platform's entry point initializes its own default I18N instance before rendering.
124
+
125
+ PWA files remain ordinary emitted JSON at `i18n/<locale>.json`; Android and iOS use bundled data assets. No translation source files need to be duplicated or moved. If the PWA must work offline, include its emitted language files in the application's service-worker caching strategy too.
126
+
127
+ For iOS release builds, the usual React Native/Expo Xcode bundle phase includes the statically required `.i18npack` files as app resources. Keep that asset-copying phase enabled, and run it again when shared translations change. A custom asset-selection or OTA update configuration must include the generated packs as well. The [iOS guide](ios/README.md) covers platform setup and release checks.
128
+
129
+ This package change does not migrate Health Ledger or modify its platform configuration. Its existing native shared-source Gradle inputs can continue to trigger rebundling when `src/` changes. Other bare Gradle projects should ensure shared source directories are inputs to the JavaScript bundle task.
130
+
131
+ ## Preparation, development, and CI
132
+
133
+ `withI18nMetro` regenerates the packs every time Metro configuration loads, including production bundling. The first version intentionally performs preparation at startup rather than maintaining a second file watcher alongside Metro.
134
+
135
+ **Restart Metro after editing, adding, or removing translation JSON.** A regular app reload alone does not rerun preparation. If a changed or uncollected source is resolved during a session, the helper reports an actionable restart/collection error instead of bundling all its languages inline. Other source-code Fast Refresh behavior is unchanged; this restriction is specific to translation preparation.
136
+
137
+ For a fresh checkout, prepare the generated manifest before running a standalone native type check:
138
+
139
+ ```sh
140
+ # Run from the native/ application directory.
141
+ npx i18n-json-react-native --root .. --dir src --dir native \
142
+ --exclude 'native/android/**' --exclude 'native/ios/**' \
143
+ --exclude 'native/dist/**' --exclude 'native/.expo/**'
144
+ ```
145
+
146
+ Alternatively call `prepareNativeI18n` from a build script. The CLI supports `--project-root`, `--root`, `--out`, repeated `--dir` / `--exclude`, and repeated `--language` options. Use the same options as Metro.
147
+
148
+ ### Build options
149
+
150
+ | Option | Default / meaning |
151
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------- |
152
+ | `root` | Metro project root; absolute or relative to `projectRoot`; shared ID/source root |
153
+ | `dirs` | `['.']`; directories/globs relative to `root` |
154
+ | `exclude` | File/directory globs relative to `root` |
155
+ | `languages` | All locales found in the collected files; an optional nonempty subset for the build |
156
+ | `outputDir` | `.i18n-json-react`; dedicated generated folder, relative to Metro project root or absolute |
157
+ | `projectRoot` | For `prepareNativeI18n` / CLI only; defaults to the current directory; inferred from the provided Metro config by `withI18nMetro` |
158
+
159
+ Include the runtime fallback in `languages` when filtering. The runtime loader rejects a locale absent from the manifest. The generated directory is marked as package-owned; preparation refuses to overwrite a nonempty unmarked directory and only removes recognized stale generated files.
160
+
161
+ ## Other React Native asset readers
162
+
163
+ The generic adapter has no Expo dependency:
164
+
165
+ ```ts
166
+ import { createNativeDictionaryLoader } from 'i18n-json-react/native';
167
+
168
+ const loadDictionary = createNativeDictionaryLoader(assets, {
169
+ readAssetText: async moduleId => nativeAssetReader.readUtf8(moduleId),
170
+ });
171
+ ```
172
+
173
+ Your reader must resolve a Metro asset module ID to UTF-8 text on the native platform, handling bundled resources and development-server assets as appropriate. Only the Expo adapter entry points entry imports Expo modules. The package root, `/core`, and web build plugins do not import them.
174
+
175
+ ## Verification
176
+
177
+ Tests generate shared-workspace assets and build actual minified Android and iOS Metro bundles. They check that language text is absent from JavaScript, assets remain discoverable for packaging, provider calls are lazy, and only selected/fallback files are read. The loader, Expo adapter contract, caching/retry behavior, CLI, safe regeneration, and TypeScript exports are covered.
178
+
179
+ To also execute the generated production bundle in an available Hermes CLI, set `I18N_JSON_REACT_HERMES=/absolute/path/to/hermes` when running tests. This was checked against the Hermes binary installed with React Native 0.81.5. An installed Android/iOS app test is still required when integrating into an application; these package tests do not claim to run native modules on a device.
@@ -0,0 +1,14 @@
1
+ # Android / React Native
2
+
3
+ Android and iOS now use the [shared native integration](../README.md). One Metro configuration and native startup module work for both platforms, using the same feature-local JSON files as the PWA.
4
+
5
+ Existing Android imports and commands remain supported:
6
+
7
+ - `i18n-json-react/native/android/metro`: `withI18nMetro`, `prepareAndroidI18n`.
8
+ - `i18n-json-react/native/android/expo`: `createExpoDictionaryLoader`.
9
+ - `i18n-json-react/native/android`: `createAndroidDictionaryLoader`, `AndroidLanguageAssets`, `AndroidDictionaryLoaderOptions`.
10
+ - `i18n-json-react-android`: preparation CLI.
11
+
12
+ For new shared setup code, use `/native/metro`, `/native/expo`, and `i18n-json-react-native`. The platform-specific entry points delegate to that implementation.
13
+
14
+ Language text remains outside JavaScript in separate offline data assets. Only fallback and selected locale assets are read initially; a build language filter can reduce APK size. Restart Metro after translation JSON changes. See the shared guide for the complete setup, native storage and locale options, Health Ledger source layout, and release verification limits.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../cli.cjs').runCLI('i18n-json-react-android');
@@ -0,0 +1 @@
1
+ module.exports = require('../expo.cjs');
@@ -0,0 +1 @@
1
+ export { createExpoDictionaryLoader } from '../expo.cjs';
@@ -0,0 +1,3 @@
1
+ const { createNativeDictionaryLoader } = require('../index.cjs');
2
+
3
+ module.exports = { createAndroidDictionaryLoader: createNativeDictionaryLoader };
@@ -0,0 +1,5 @@
1
+ export {
2
+ createNativeDictionaryLoader as createAndroidDictionaryLoader,
3
+ type NativeLanguageAssets as AndroidLanguageAssets,
4
+ type NativeDictionaryLoaderOptions as AndroidDictionaryLoaderOptions,
5
+ } from '../index.cjs';
@@ -0,0 +1,3 @@
1
+ const { withI18nMetro, prepareNativeI18n } = require('../metro.cjs');
2
+
3
+ module.exports = { withI18nMetro, prepareAndroidI18n: prepareNativeI18n };
@@ -0,0 +1,7 @@
1
+ export {
2
+ withI18nMetro,
3
+ prepareNativeI18n as prepareAndroidI18n,
4
+ type NativeI18nOptions as AndroidI18nOptions,
5
+ type NativeI18nPreparationOptions as AndroidI18nPreparationOptions,
6
+ type PreparedNativeI18n as PreparedAndroidI18n,
7
+ } from '../metro.cjs';
@@ -0,0 +1,3 @@
1
+ const { prepareNativeI18n, ASSET_EXTENSION } = require('../prepare.cjs');
2
+
3
+ module.exports = { prepareAndroidI18n: prepareNativeI18n, ASSET_EXTENSION };
package/native/cli.cjs ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ const { prepareNativeI18n } = require('./prepare.cjs');
3
+
4
+ function runCLI(command = 'i18n-json-react-native') {
5
+ main(command).catch(error => {
6
+ console.error(error);
7
+ process.exitCode = 1;
8
+ });
9
+ }
10
+
11
+ async function main(command) {
12
+ const options = {};
13
+ const values = new Map([
14
+ ['--project-root', 'projectRoot'],
15
+ ['--root', 'root'],
16
+ ['--out', 'outputDir'],
17
+ ['--dir', 'dirs'],
18
+ ['--exclude', 'exclude'],
19
+ ['--language', 'languages'],
20
+ ]);
21
+ const args = process.argv.slice(2);
22
+ for (let index = 0; index < args.length; index += 1) {
23
+ const flag = args[index];
24
+ if (flag === '--help') {
25
+ process.stdout.write(
26
+ `${command} [--project-root DIR] [--root DIR] [--out DIR] [--dir DIR] [--exclude GLOB] [--language CODE]\nRepeat --dir, --exclude and --language as needed.\n`,
27
+ );
28
+ return;
29
+ }
30
+ const key = values.get(flag);
31
+ const value = args[++index];
32
+ if (!key || !value || value.startsWith('--')) throw new Error(`Invalid option: ${flag}`);
33
+ if (['dirs', 'exclude', 'languages'].includes(key)) (options[key] ??= []).push(value);
34
+ else options[key] = value;
35
+ }
36
+ const result = await prepareNativeI18n(options);
37
+ process.stdout.write(
38
+ `Prepared ${result.references.size} feature dictionaries for ${result.languages.join(', ')} in ${result.outputDir}\n`,
39
+ );
40
+ }
41
+
42
+ module.exports = { runCLI };
43
+ if (require.main === module) runCLI();
@@ -0,0 +1,17 @@
1
+ const { Asset } = require('expo-asset');
2
+ const { File } = require('expo-file-system');
3
+ const { createNativeDictionaryLoader } = require('./index.cjs');
4
+
5
+ /** Expo SDK 54+ adapter for bundled Android and iOS data assets, including offline app resources. */
6
+ function createExpoDictionaryLoader(assets) {
7
+ return createNativeDictionaryLoader(assets, {
8
+ async readAssetText(moduleId) {
9
+ const asset = Asset.fromModule(moduleId);
10
+ if (!asset.localUri) await asset.downloadAsync();
11
+ if (!asset.localUri) throw new Error(`Could not resolve dictionary asset ${moduleId} to a local file`);
12
+ return new File(asset.localUri).text();
13
+ },
14
+ });
15
+ }
16
+
17
+ module.exports = { createExpoDictionaryLoader };
@@ -0,0 +1,7 @@
1
+ import type { LanguageDictionary } from '../dist/cjs/core.js';
2
+ import type { NativeLanguageAssets } from './index.cjs';
3
+
4
+ /** Requires expo-asset >=12 and expo-file-system >=19; does not import those modules in web entrypoints. */
5
+ export declare function createExpoDictionaryLoader<const L extends string>(
6
+ assets: NativeLanguageAssets<L>,
7
+ ): (language: L) => Promise<LanguageDictionary>;
@@ -0,0 +1,18 @@
1
+ const { validateLanguageDictionary } = require('../dist/cjs/dictionaries.js');
2
+
3
+ /** Reads only a requested language's data asset. The existing I18N store handles caching and retries. */
4
+ function createNativeDictionaryLoader(assets, options) {
5
+ if (typeof options?.readAssetText !== 'function') throw new TypeError('readAssetText must be provided');
6
+ return async language => {
7
+ const provider = Object.prototype.hasOwnProperty.call(assets, language) ? assets[language] : undefined;
8
+ if (typeof provider !== 'function') throw new Error(`No bundled dictionary asset for language: ${language}`);
9
+ const moduleId = provider();
10
+ if (!Number.isInteger(moduleId) || moduleId <= 0)
11
+ throw new TypeError(`Invalid native asset module for language: ${language}`);
12
+ const dictionary = JSON.parse(await options.readAssetText(moduleId));
13
+ validateLanguageDictionary(dictionary);
14
+ return dictionary;
15
+ };
16
+ }
17
+
18
+ module.exports = { createNativeDictionaryLoader };
@@ -0,0 +1,14 @@
1
+ import type { LanguageDictionary } from '../dist/cjs/core.js';
2
+
3
+ /** Generated manifest: static native asset requires, deferred until the locale is requested. */
4
+ export type NativeLanguageAssets<L extends string = string> = Readonly<Record<L, () => number>>;
5
+
6
+ export interface NativeDictionaryLoaderOptions {
7
+ /** Read UTF-8 asset text using the application's native file/asset integration. */
8
+ readAssetText(moduleId: number): Promise<string>;
9
+ }
10
+
11
+ export declare function createNativeDictionaryLoader<const L extends string>(
12
+ assets: NativeLanguageAssets<L>,
13
+ options: NativeDictionaryLoaderOptions,
14
+ ): (language: L) => Promise<LanguageDictionary>;
@@ -0,0 +1,58 @@
1
+ # iOS / React Native
2
+
3
+ iOS uses the [shared native integration](../README.md). The same Metro configuration, generated manifest, `I18N.configure` call, and feature-local JSON files serve Android and iOS. Translations stay in separate `.i18npack` resources; only the fallback and selected locale are read and parsed initially.
4
+
5
+ The recommended entry points for an app targeting both platforms are:
6
+
7
+ ```js
8
+ // native/metro.config.js
9
+ const { getDefaultConfig } = require('expo/metro-config');
10
+ const { withI18nMetro } = require('i18n-json-react/native/metro');
11
+
12
+ module.exports = withI18nMetro(getDefaultConfig(__dirname), {
13
+ root: '..',
14
+ dirs: ['src', 'native'],
15
+ exclude: ['native/android/**', 'native/ios/**', 'native/dist/**', 'native/.expo/**'],
16
+ });
17
+ ```
18
+
19
+ Keep any existing monorepo resolver/transformer settings before wrapping the configuration. `root` must match the PWA's ID root. See the shared guide for full startup, device locale, AsyncStorage, and type-checking examples.
20
+
21
+ ```ts
22
+ // native/i18n.ts — used by both Android and iOS
23
+ import I18N from 'i18n-json-react';
24
+ import { createExpoDictionaryLoader } from 'i18n-json-react/native/expo';
25
+ import assets from './.i18n-json-react/manifest.cjs';
26
+
27
+ I18N.configure({
28
+ supportedLanguages: ['EN', 'UK'],
29
+ fallbackLanguage: 'UK',
30
+ storage: false,
31
+ loadDictionary: createExpoDictionaryLoader(assets),
32
+ });
33
+ ```
34
+
35
+ Install `expo-asset` and `expo-file-system` using `npx expo install`, then rebuild the native application if those modules are new. In a bare React Native project using Expo modules, follow Expo's normal native installation/autolinking steps, including CocoaPods. There is no package-specific Pod, Swift module, or `Info.plist` change.
36
+
37
+ The Expo reader accepts local iOS app-bundle URLs through `Asset.localUri`, or resolves an asset using `downloadAsync` before reading it with `File.text()`. Production resources are copied by the normal Xcode React Native/Expo bundle phase; development assets may be served by Metro. This follows the standard [React Native non-image asset pipeline](https://reactnative.dev/docs/0.81/images#static-non-image-resources) and [Expo asset loading](https://docs.expo.dev/develop/user-interface/assets/).
38
+
39
+ All packaged languages remain available offline and contribute to the application size. Use Metro's `languages` option to restrict the packaged set. Keep generated packs in any custom asset-copying, asset-selection, or OTA update configuration. The data packs are app resources, so they do not require one `.lproj` folder per locale.
40
+
41
+ ## Platform-specific entry points
42
+
43
+ For an iOS-only integration, equivalent entry points are available:
44
+
45
+ - `i18n-json-react/native/ios/metro`: `withI18nMetro`, `prepareIOSI18n`.
46
+ - `i18n-json-react/native/ios/expo`: `createExpoDictionaryLoader`.
47
+ - `i18n-json-react/native/ios`: `createIOSDictionaryLoader`, `IOSLanguageAssets`, `IOSDictionaryLoaderOptions` for an injected native asset reader.
48
+ - `i18n-json-react-ios`: preparation CLI, with the same options as `i18n-json-react-native`.
49
+
50
+ Existing Android Metro configurations now extract feature JSON on iOS as well, so they can be kept while adopting the shared entry points. Web requests through Metro remain unchanged; PWA extraction continues to use Vite.
51
+
52
+ ## Development and release verification
53
+
54
+ Restart Metro after editing, adding, or removing translation JSON. Standalone native type checks can generate the manifest first with `i18n-json-react-native --root .. --dir src --dir native` from the native app directory; use the same exclusions and language filter as Metro.
55
+
56
+ Package tests build minified iOS and Android Metro bundles and verify matching feature IDs, separate asset graphs, lazy reads, and fallback behavior. Both bundles can also run in Hermes via `I18N_JSON_REACT_HERMES`.
57
+
58
+ When integrating into an application, verify an installed iOS Release build with Metro stopped and networking disabled: the selected and fallback locales must render, and switching to another packaged locale must work. Xcode signing, an IPA build, and device/simulator execution are application-level checks and are not performed by this package's tests.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../cli.cjs').runCLI('i18n-json-react-ios');
@@ -0,0 +1 @@
1
+ module.exports = require('../expo.cjs');
@@ -0,0 +1 @@
1
+ export { createExpoDictionaryLoader } from '../expo.cjs';
@@ -0,0 +1,3 @@
1
+ const { createNativeDictionaryLoader } = require('../index.cjs');
2
+
3
+ module.exports = { createIOSDictionaryLoader: createNativeDictionaryLoader };
@@ -0,0 +1,5 @@
1
+ export {
2
+ createNativeDictionaryLoader as createIOSDictionaryLoader,
3
+ type NativeLanguageAssets as IOSLanguageAssets,
4
+ type NativeDictionaryLoaderOptions as IOSDictionaryLoaderOptions,
5
+ } from '../index.cjs';
@@ -0,0 +1,3 @@
1
+ const { withI18nMetro, prepareNativeI18n } = require('../metro.cjs');
2
+
3
+ module.exports = { withI18nMetro, prepareIOSI18n: prepareNativeI18n };
@@ -0,0 +1,7 @@
1
+ export {
2
+ withI18nMetro,
3
+ prepareNativeI18n as prepareIOSI18n,
4
+ type NativeI18nOptions as IOSI18nOptions,
5
+ type NativeI18nPreparationOptions as IOSI18nPreparationOptions,
6
+ type PreparedNativeI18n as PreparedIOSI18n,
7
+ } from '../metro.cjs';
@@ -0,0 +1,3 @@
1
+ const { prepareNativeI18n, ASSET_EXTENSION } = require('../prepare.cjs');
2
+
3
+ module.exports = { prepareIOSI18n: prepareNativeI18n, ASSET_EXTENSION };
@@ -0,0 +1,45 @@
1
+ const { readFileSync, realpathSync } = require('node:fs');
2
+ const { createHash } = require('node:crypto');
3
+ const { prepareNativeI18n, ASSET_EXTENSION } = require('./prepare.cjs');
4
+
5
+ const FEATURE_FILE = /(?:^|[/\\])(?:i18n|[^/\\]+\.i18n)\.json$/;
6
+
7
+ /** Composes an existing Metro configuration, preserving its resolver, transformer and asset pipeline. */
8
+ async function withI18nMetro(baseConfig, options = {}) {
9
+ const config = await baseConfig;
10
+ const prepared = await prepareNativeI18n({ ...options, projectRoot: config.projectRoot });
11
+ const previous = config.resolver?.resolveRequest;
12
+ return {
13
+ ...config,
14
+ watchFolders: [...new Set([...(config.watchFolders ?? []), ...prepared.watchFolders])],
15
+ resolver: {
16
+ ...config.resolver,
17
+ assetExts: [...new Set([...(config.resolver?.assetExts ?? []), ASSET_EXTENSION])],
18
+ sourceExts: (config.resolver?.sourceExts ?? []).filter(extension => extension !== ASSET_EXTENSION),
19
+ resolveRequest(context, moduleName, platform) {
20
+ const result = previous
21
+ ? previous(context, moduleName, platform)
22
+ : context.resolveRequest(context, moduleName, platform);
23
+ if (
24
+ (platform !== 'android' && platform !== 'ios') ||
25
+ result.type !== 'sourceFile' ||
26
+ !FEATURE_FILE.test(result.filePath)
27
+ )
28
+ return result;
29
+ const file = realpathSync(result.filePath);
30
+ const reference = prepared.references.get(file);
31
+ if (!reference)
32
+ throw new Error(
33
+ `i18n file was not collected: ${file}. Adjust dirs/exclude so it is collected, then restart Metro.`,
34
+ );
35
+ const fingerprint = createHash('sha256').update(readFileSync(file, 'utf8')).digest('hex');
36
+ if (prepared.fingerprints.get(file) !== fingerprint) {
37
+ throw new Error(`i18n file changed after preparation: ${file}. Restart Metro to regenerate language assets.`);
38
+ }
39
+ return { type: 'sourceFile', filePath: reference };
40
+ },
41
+ },
42
+ };
43
+ }
44
+
45
+ module.exports = { withI18nMetro, prepareNativeI18n };
@@ -0,0 +1,34 @@
1
+ import type { ConfigT } from 'metro-config';
2
+
3
+ export interface NativeI18nOptions {
4
+ /** Source/ID root, absolute or relative to the Metro projectRoot. Use the same root in Vite. */
5
+ root?: string;
6
+ /** Directories relative to root. Defaults to ['.']; list platform-specific source directories explicitly. */
7
+ dirs?: readonly string[];
8
+ exclude?: readonly string[];
9
+ /** Optional language subset to package. Include the runtime fallback language. Defaults to all JSON locales. */
10
+ languages?: readonly string[];
11
+ /** Dedicated generated folder, absolute or relative to projectRoot. Defaults to '.i18n-json-react'. */
12
+ outputDir?: string;
13
+ }
14
+
15
+ export interface NativeI18nPreparationOptions extends NativeI18nOptions {
16
+ /** Metro application's directory. Defaults to process.cwd(). */
17
+ projectRoot?: string;
18
+ }
19
+
20
+ export interface PreparedNativeI18n {
21
+ root: string;
22
+ outputDir: string;
23
+ manifestPath: string;
24
+ languages: string[];
25
+ references: Map<string, string>;
26
+ fingerprints: Map<string, string>;
27
+ watchFolders: string[];
28
+ }
29
+
30
+ export declare function prepareNativeI18n(options?: NativeI18nPreparationOptions): Promise<PreparedNativeI18n>;
31
+ export declare function withI18nMetro(
32
+ config: ConfigT | Promise<ConfigT>,
33
+ options?: NativeI18nOptions,
34
+ ): Promise<ConfigT>;
@@ -0,0 +1,120 @@
1
+ const { mkdir, readFile, readdir, rename, unlink, writeFile } = require('node:fs/promises');
2
+ const { randomUUID } = require('node:crypto');
3
+ const path = require('node:path');
4
+ const { collectDictionaries, computeId, resolveRoot } = require('../bundlers/shared.cjs');
5
+
6
+ const ASSET_EXTENSION = 'i18npack';
7
+ const MARKER = '.generated-by-i18n-json-react';
8
+
9
+ /** Produces data assets and tiny reference modules, without moving feature-local source JSON. */
10
+ async function prepareNativeI18n(options = {}) {
11
+ const projectRoot = resolveRoot(process.cwd(), options.projectRoot);
12
+ const root = resolveRoot(projectRoot, options.root);
13
+ const outputDir = path.resolve(projectRoot, options.outputDir ?? '.i18n-json-react');
14
+ if (outputDir === root || outputDir === projectRoot)
15
+ throw new Error('outputDir must be a dedicated generated directory');
16
+ const relativeOutput = path.relative(root, outputDir).split(path.sep).join('/');
17
+ const directories = new Set([root, outputDir]);
18
+ const { files, perLanguage, fingerprints } = await collectDictionaries(
19
+ root,
20
+ {
21
+ dirs: options.dirs ?? ['.'],
22
+ exclude: [...(options.exclude ?? []), ...(!relativeOutput.startsWith('..') ? [`${relativeOutput}/**`] : [])],
23
+ },
24
+ directory => directories.add(directory),
25
+ );
26
+ const languages = options.languages ?? [...perLanguage.keys()].sort();
27
+ if (options.languages && (!languages.length || new Set(languages).size !== languages.length)) {
28
+ throw new Error('languages must be a nonempty list without duplicates');
29
+ }
30
+ for (const language of languages) {
31
+ if (!perLanguage.has(language)) throw new Error(`No translations found for language: ${language}`);
32
+ }
33
+
34
+ await prepareOutput(outputDir);
35
+ const assetDir = path.join(outputDir, 'assets');
36
+ const referenceDir = path.join(outputDir, 'references');
37
+ await mkdir(assetDir, { recursive: true });
38
+ await mkdir(referenceDir, { recursive: true });
39
+ const assets = [];
40
+ for (const language of languages) {
41
+ const file = `${language}.${ASSET_EXTENSION}`;
42
+ await writeChanged(path.join(assetDir, file), JSON.stringify(perLanguage.get(language)));
43
+ assets.push(file);
44
+ }
45
+ const references = new Map();
46
+ for (const file of files) {
47
+ const id = computeId(file, root);
48
+ const target = path.join(referenceDir, `${id}.js`);
49
+ await writeChanged(target, `module.exports = ${JSON.stringify({ __id: id })};\n`);
50
+ references.set(file, target);
51
+ }
52
+ await removeStale(assetDir, new Set(assets), /^[A-Za-z0-9_-]+\.i18npack$/);
53
+ await removeStale(
54
+ referenceDir,
55
+ new Set([...references.values()].map(file => path.basename(file))),
56
+ /^[a-f0-9]{16}\.js$/,
57
+ );
58
+ const providers = languages.map(
59
+ language =>
60
+ ` ${JSON.stringify(language)}: () => require(${JSON.stringify(`./assets/${language}.${ASSET_EXTENSION}`)})`,
61
+ );
62
+ const manifestPath = path.join(outputDir, 'manifest.cjs');
63
+ await writeChanged(
64
+ manifestPath,
65
+ `// Generated. Each language asset is required only when selected.\nmodule.exports = Object.freeze({\n${providers.join(',\n')}\n});\n`,
66
+ );
67
+ const fields = languages.map(language => ` readonly ${JSON.stringify(language)}: () => number;`);
68
+ await writeChanged(
69
+ path.join(outputDir, 'manifest.d.cts'),
70
+ `declare const assets: {\n${fields.join('\n')}\n};\nexport = assets;\n`,
71
+ );
72
+ return {
73
+ root,
74
+ outputDir,
75
+ manifestPath,
76
+ languages: [...languages],
77
+ references,
78
+ fingerprints,
79
+ watchFolders: [...directories],
80
+ };
81
+ }
82
+
83
+ async function prepareOutput(outputDir) {
84
+ await mkdir(outputDir, { recursive: true });
85
+ const contents = await readdir(outputDir);
86
+ if (contents.length && !contents.includes(MARKER)) {
87
+ throw new Error(`Refusing to overwrite a non-generated directory: ${outputDir}`);
88
+ }
89
+ await writeChanged(path.join(outputDir, MARKER), 'Generated by i18n-json-react.\n');
90
+ }
91
+
92
+ async function writeChanged(file, content) {
93
+ let previous;
94
+ try {
95
+ previous = await readFile(file, 'utf8');
96
+ } catch (error) {
97
+ if (error.code !== 'ENOENT') throw error;
98
+ }
99
+ if (previous === content) return;
100
+ const temporary = `${file}.${randomUUID()}.tmp`;
101
+ try {
102
+ await writeFile(temporary, content);
103
+ await rename(temporary, file);
104
+ } catch (error) {
105
+ try {
106
+ await unlink(temporary);
107
+ } catch (cleanupError) {
108
+ if (cleanupError.code !== 'ENOENT') console.error(cleanupError);
109
+ }
110
+ throw error;
111
+ }
112
+ }
113
+
114
+ async function removeStale(directory, keep, pattern) {
115
+ for (const file of await readdir(directory)) {
116
+ if (pattern.test(file) && !keep.has(file)) await unlink(path.join(directory, file));
117
+ }
118
+ }
119
+
120
+ module.exports = { prepareNativeI18n, ASSET_EXTENSION };