lexisync-react 0.1.2 → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sander Post / LexiSync
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,12 +1,16 @@
1
1
  # lexisync-react
2
2
 
3
- React bindings for [LexiSync](https://lexisync.app) — Locize-style workflow:
3
+ React bindings for [LexiSync](https://github.com/sanderpost/lexisync) — open-source, self-hosted translation management.
4
4
 
5
- 1. Create org + API keys in the dashboard
6
- 2. Load **working copy** (`version: "latest"`) with optional `saveMissing`
7
- 3. Translate in the dashboard
8
- 4. **Publish** a version (`production`, `1.0.0`, …)
9
- 5. Pin the app to that version (CDN) or keep `latest` in dev
5
+ > **1.0:** `apiUrl` is required — the URL of your own LexiSync instance. There is no hosted default.
6
+
7
+ Locize-style workflow:
8
+
9
+ 1. Run LexiSync ([Docker guide](https://github.com/sanderpost/lexisync/blob/main/docker/README.md)); create a project + API keys
10
+ 2. Load **working copy** (`version: "latest"`) with optional `saveMissing`
11
+ 3. Translate in the dashboard
12
+ 4. **Publish** a version (`production`, `1.0.0`, …)
13
+ 5. Pin the app to that version (CDN) or keep `latest` in dev
10
14
 
11
15
  ## Install
12
16
 
@@ -25,7 +29,9 @@ function Copy() {
25
29
  return (
26
30
  <>
27
31
  <h1>{t('title')}</h1>
28
- <button type="button" onClick={() => void changeLanguage('nl')}>NL</button>
32
+ <button type="button" onClick={() => void changeLanguage('nl')}>
33
+ NL
34
+ </button>
29
35
  <p>{status}</p>
30
36
  </>
31
37
  );
@@ -36,8 +42,8 @@ export function App() {
36
42
  <LexiSyncProvider
37
43
  projectId={import.meta.env.VITE_LEXISYNC_PROJECT_ID}
38
44
  apiKey={import.meta.env.VITE_LEXISYNC_API_KEY}
39
- apiUrl="https://lexisync.app" // optional default
40
- // cdnUrl="https://cdn.lexisync.app" // optional — auto for lexisync.app
45
+ apiUrl="https://lexisync.example.com" // required — your LexiSync instance
46
+ // cdnUrl="https://cdn.lexisync.example.com" // optional — default `${apiUrl}/cdn`
41
47
  version="latest" // or "production" after publish
42
48
  lng="en"
43
49
  ns="common"
@@ -52,7 +58,8 @@ export function App() {
52
58
  CDN URL shape after publish:
53
59
 
54
60
  ```
55
- https://cdn.lexisync.app/{projectId}/{version}/{lng}/{namespace}.json
61
+ {apiUrl}/cdn/{projectId}/{version}/{lng}/{namespace}
62
+ # or, with a dedicated CDN host: {cdnUrl}/{projectId}/{version}/{lng}/{namespace}.json
56
63
  ```
57
64
 
58
65
  ## Tests
package/dist/index.cjs CHANGED
@@ -30,36 +30,36 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- LexiSyncContext: () => LexiSyncContext,
34
- LexiSyncProvider: () => LexiSyncProvider,
35
33
  createLexiSyncI18n: () => createLexiSyncI18n,
36
- resolveConfig: () => resolveConfig,
37
- useLexiSync: () => useLexiSync,
38
- useT: () => useT
34
+ resolveConfig: () => resolveConfig
39
35
  });
40
36
  module.exports = __toCommonJS(index_exports);
41
37
 
42
38
  // src/createI18n.ts
43
39
  var import_i18next = __toESM(require("i18next"), 1);
44
40
  var import_lexisync = __toESM(require("lexisync"), 1);
45
- var DEFAULT_API_URL = "https://lexisync.app";
46
41
  function resolveConfig(config) {
47
42
  if (!config.projectId || !String(config.projectId).trim()) {
48
43
  throw new Error("LexiSync: projectId is required");
49
44
  }
45
+ if (!config.apiUrl || !String(config.apiUrl).trim()) {
46
+ throw new Error(
47
+ "LexiSync: apiUrl is required \u2014 the base URL of your self-hosted LexiSync instance"
48
+ );
49
+ }
50
50
  const version = config.version || "latest";
51
51
  const ns = config.ns ?? "common";
52
52
  const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || "common";
53
53
  return {
54
54
  ...config,
55
55
  projectId: config.projectId,
56
- apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ""),
56
+ apiUrl: String(config.apiUrl).trim().replace(/\/$/, ""),
57
57
  version,
58
58
  lng: config.lng || "en",
59
59
  fallbackLng: config.fallbackLng ?? "en",
60
60
  ns,
61
61
  defaultNS,
62
- saveMissing: Boolean(config.saveMissing && config.apiKey && version === "latest")
62
+ saveMissing: Boolean(config.saveMissing && config.apiKey)
63
63
  };
64
64
  }
65
65
  async function createLexiSyncI18n(config) {
@@ -87,118 +87,8 @@ async function createLexiSyncI18n(config) {
87
87
  });
88
88
  return instance;
89
89
  }
90
-
91
- // src/provider.tsx
92
- var import_react = require("react");
93
- var LexiSyncContext = (0, import_react.createContext)(null);
94
- function toError(e) {
95
- return e instanceof Error ? e : new Error(String(e));
96
- }
97
- var STUB_I18N = null;
98
- function LexiSyncProvider(props) {
99
- const { children, i18n: externalI18n, suspense = false, ...rawConfig } = props;
100
- const config = (0, import_react.useMemo)(
101
- () => resolveConfig(rawConfig),
102
- // eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
103
- [
104
- rawConfig.projectId,
105
- rawConfig.apiKey,
106
- rawConfig.apiUrl,
107
- rawConfig.cdnUrl,
108
- rawConfig.version,
109
- rawConfig.lng,
110
- rawConfig.fallbackLng,
111
- rawConfig.ns,
112
- rawConfig.defaultNS,
113
- rawConfig.saveMissing
114
- ]
115
- );
116
- const [instance, setInstance] = (0, import_react.useState)(() => externalI18n ?? null);
117
- const [status, setStatus] = (0, import_react.useState)(() => externalI18n ? "ready" : "loading");
118
- const [error, setError] = (0, import_react.useState)(null);
119
- const [tick, setTick] = (0, import_react.useState)(0);
120
- const bootstrap = (0, import_react.useCallback)(async () => {
121
- if (externalI18n) {
122
- setInstance(externalI18n);
123
- setStatus("ready");
124
- setError(null);
125
- return;
126
- }
127
- setStatus("loading");
128
- setError(null);
129
- try {
130
- const i18n = await createLexiSyncI18n(config);
131
- setInstance(i18n);
132
- setStatus("ready");
133
- } catch (e) {
134
- setError(toError(e));
135
- setStatus("error");
136
- }
137
- }, [config, externalI18n]);
138
- (0, import_react.useEffect)(() => {
139
- void bootstrap();
140
- }, [bootstrap]);
141
- const changeLanguage = (0, import_react.useCallback)(async (lng) => {
142
- setInstance((current) => {
143
- if (current) {
144
- void current.changeLanguage(lng).then(() => setTick((t2) => t2 + 1));
145
- }
146
- return current;
147
- });
148
- }, []);
149
- const reload = (0, import_react.useCallback)(async () => {
150
- if (externalI18n) {
151
- await externalI18n.reloadResources();
152
- setTick((t2) => t2 + 1);
153
- return;
154
- }
155
- await bootstrap();
156
- setTick((t2) => t2 + 1);
157
- }, [bootstrap, externalI18n]);
158
- const t = (0, import_react.useCallback)(
159
- (key, options) => {
160
- void tick;
161
- return instance ? String(instance.t(key, options)) : key;
162
- },
163
- [instance, tick]
164
- );
165
- const value = (0, import_react.useMemo)(
166
- () => ({
167
- config,
168
- status,
169
- error,
170
- i18n: instance ?? STUB_I18N,
171
- t,
172
- changeLanguage,
173
- reload
174
- }),
175
- [instance, status, error, config, t, changeLanguage, reload]
176
- );
177
- if (suspense && !instance && status !== "error") {
178
- return (0, import_react.createElement)(
179
- "div",
180
- { "data-lexisync-status": status, role: "status" },
181
- "Loading translations\u2026"
182
- );
183
- }
184
- return (0, import_react.createElement)(LexiSyncContext.Provider, { value }, children);
185
- }
186
- function useLexiSync() {
187
- const ctx = (0, import_react.useContext)(LexiSyncContext);
188
- if (!ctx) {
189
- throw new Error("useLexiSync must be used within <LexiSyncProvider>");
190
- }
191
- return ctx;
192
- }
193
- function useT() {
194
- return useLexiSync().t;
195
- }
196
90
  // Annotate the CommonJS export names for ESM import in node:
197
91
  0 && (module.exports = {
198
- LexiSyncContext,
199
- LexiSyncProvider,
200
92
  createLexiSyncI18n,
201
- resolveConfig,
202
- useLexiSync,
203
- useT
93
+ resolveConfig
204
94
  });
package/dist/index.d.cts CHANGED
@@ -1,62 +1,31 @@
1
- import * as i18next from 'i18next';
2
1
  import { i18n } from 'i18next';
3
- import * as react from 'react';
4
- import { ReactNode } from 'react';
5
2
 
6
3
  type LexiSyncConfig = {
7
4
  /** LexiSync project id from the dashboard */
8
5
  projectId: string;
9
6
  /** Secret key (sk_…) — required for saveMissing / write */
10
7
  apiKey?: string;
11
- /** Platform origin, default https://lexisync.app */
12
- apiUrl?: string;
13
- /** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
8
+ /** Base URL of your self-hosted LexiSync instance (required, no default) */
9
+ apiUrl: string;
10
+ /** Optional dedicated CDN origin; default `${apiUrl}/cdn` */
14
11
  cdnUrl?: string;
15
12
  /**
16
- * Catalog version:
13
+ * Catalog version (READ path):
17
14
  * - `latest` — working copy (dev, saveMissing)
18
15
  * - `production` / `1.0.0` / … — published CDN snapshot
16
+ *
17
+ * saveMissing always writes to the working copy regardless of this value.
19
18
  */
20
19
  version?: string;
21
20
  lng?: string;
22
21
  fallbackLng?: string | string[];
23
22
  ns?: string | string[];
24
23
  defaultNS?: string;
25
- /** Auto-push missing keys to working copy (needs apiKey, version latest) */
24
+ /** Auto-push missing keys to working copy (needs apiKey). */
26
25
  saveMissing?: boolean;
27
26
  };
28
- type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
29
- type LexiSyncContextValue = {
30
- config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
31
- status: LexiSyncStatus;
32
- error: Error | null;
33
- i18n: i18next.i18n;
34
- t: (key: string, options?: Record<string, unknown>) => string;
35
- changeLanguage: (lng: string) => Promise<void>;
36
- reload: () => Promise<void>;
37
- };
38
27
 
39
28
  declare function resolveConfig(config: LexiSyncConfig): Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>> & LexiSyncConfig;
40
29
  declare function createLexiSyncI18n(config: LexiSyncConfig): Promise<i18n>;
41
30
 
42
- declare const LexiSyncContext: react.Context<LexiSyncContextValue | null>;
43
- type LexiSyncProviderProps = LexiSyncConfig & {
44
- children: ReactNode;
45
- /** Optional pre-built i18n instance (tests / advanced). */
46
- i18n?: i18n;
47
- /**
48
- * When true (default), children render immediately while CDN/bootstrap loads.
49
- * `t()` returns the key until ready — pair with local fallbacks for zero flash.
50
- * Set false only if you want a hard loading gate.
51
- */
52
- suspense?: boolean;
53
- };
54
- declare function LexiSyncProvider(props: LexiSyncProviderProps): react.DetailedReactHTMLElement<{
55
- 'data-lexisync-status': "idle" | "loading" | "ready";
56
- role: "status";
57
- }, HTMLElement> | react.FunctionComponentElement<react.ProviderProps<LexiSyncContextValue | null>>;
58
- declare function useLexiSync(): LexiSyncContextValue;
59
- /** Shortcut: translation function bound to the provider instance. */
60
- declare function useT(): (key: string, options?: Record<string, unknown>) => string;
61
-
62
- export { type LexiSyncConfig, LexiSyncContext, type LexiSyncContextValue, LexiSyncProvider, type LexiSyncProviderProps, type LexiSyncStatus, createLexiSyncI18n, resolveConfig, useLexiSync, useT };
31
+ export { type LexiSyncConfig, createLexiSyncI18n, resolveConfig };
package/dist/index.d.ts CHANGED
@@ -1,62 +1,31 @@
1
- import * as i18next from 'i18next';
2
1
  import { i18n } from 'i18next';
3
- import * as react from 'react';
4
- import { ReactNode } from 'react';
5
2
 
6
3
  type LexiSyncConfig = {
7
4
  /** LexiSync project id from the dashboard */
8
5
  projectId: string;
9
6
  /** Secret key (sk_…) — required for saveMissing / write */
10
7
  apiKey?: string;
11
- /** Platform origin, default https://lexisync.app */
12
- apiUrl?: string;
13
- /** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
8
+ /** Base URL of your self-hosted LexiSync instance (required, no default) */
9
+ apiUrl: string;
10
+ /** Optional dedicated CDN origin; default `${apiUrl}/cdn` */
14
11
  cdnUrl?: string;
15
12
  /**
16
- * Catalog version:
13
+ * Catalog version (READ path):
17
14
  * - `latest` — working copy (dev, saveMissing)
18
15
  * - `production` / `1.0.0` / … — published CDN snapshot
16
+ *
17
+ * saveMissing always writes to the working copy regardless of this value.
19
18
  */
20
19
  version?: string;
21
20
  lng?: string;
22
21
  fallbackLng?: string | string[];
23
22
  ns?: string | string[];
24
23
  defaultNS?: string;
25
- /** Auto-push missing keys to working copy (needs apiKey, version latest) */
24
+ /** Auto-push missing keys to working copy (needs apiKey). */
26
25
  saveMissing?: boolean;
27
26
  };
28
- type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
29
- type LexiSyncContextValue = {
30
- config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
31
- status: LexiSyncStatus;
32
- error: Error | null;
33
- i18n: i18next.i18n;
34
- t: (key: string, options?: Record<string, unknown>) => string;
35
- changeLanguage: (lng: string) => Promise<void>;
36
- reload: () => Promise<void>;
37
- };
38
27
 
39
28
  declare function resolveConfig(config: LexiSyncConfig): Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>> & LexiSyncConfig;
40
29
  declare function createLexiSyncI18n(config: LexiSyncConfig): Promise<i18n>;
41
30
 
42
- declare const LexiSyncContext: react.Context<LexiSyncContextValue | null>;
43
- type LexiSyncProviderProps = LexiSyncConfig & {
44
- children: ReactNode;
45
- /** Optional pre-built i18n instance (tests / advanced). */
46
- i18n?: i18n;
47
- /**
48
- * When true (default), children render immediately while CDN/bootstrap loads.
49
- * `t()` returns the key until ready — pair with local fallbacks for zero flash.
50
- * Set false only if you want a hard loading gate.
51
- */
52
- suspense?: boolean;
53
- };
54
- declare function LexiSyncProvider(props: LexiSyncProviderProps): react.DetailedReactHTMLElement<{
55
- 'data-lexisync-status': "idle" | "loading" | "ready";
56
- role: "status";
57
- }, HTMLElement> | react.FunctionComponentElement<react.ProviderProps<LexiSyncContextValue | null>>;
58
- declare function useLexiSync(): LexiSyncContextValue;
59
- /** Shortcut: translation function bound to the provider instance. */
60
- declare function useT(): (key: string, options?: Record<string, unknown>) => string;
61
-
62
- export { type LexiSyncConfig, LexiSyncContext, type LexiSyncContextValue, LexiSyncProvider, type LexiSyncProviderProps, type LexiSyncStatus, createLexiSyncI18n, resolveConfig, useLexiSync, useT };
31
+ export { type LexiSyncConfig, createLexiSyncI18n, resolveConfig };
package/dist/index.js CHANGED
@@ -1,24 +1,28 @@
1
1
  // src/createI18n.ts
2
2
  import i18next from "i18next";
3
3
  import LexiSyncBackend from "lexisync";
4
- var DEFAULT_API_URL = "https://lexisync.app";
5
4
  function resolveConfig(config) {
6
5
  if (!config.projectId || !String(config.projectId).trim()) {
7
6
  throw new Error("LexiSync: projectId is required");
8
7
  }
8
+ if (!config.apiUrl || !String(config.apiUrl).trim()) {
9
+ throw new Error(
10
+ "LexiSync: apiUrl is required \u2014 the base URL of your self-hosted LexiSync instance"
11
+ );
12
+ }
9
13
  const version = config.version || "latest";
10
14
  const ns = config.ns ?? "common";
11
15
  const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || "common";
12
16
  return {
13
17
  ...config,
14
18
  projectId: config.projectId,
15
- apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ""),
19
+ apiUrl: String(config.apiUrl).trim().replace(/\/$/, ""),
16
20
  version,
17
21
  lng: config.lng || "en",
18
22
  fallbackLng: config.fallbackLng ?? "en",
19
23
  ns,
20
24
  defaultNS,
21
- saveMissing: Boolean(config.saveMissing && config.apiKey && version === "latest")
25
+ saveMissing: Boolean(config.saveMissing && config.apiKey)
22
26
  };
23
27
  }
24
28
  async function createLexiSyncI18n(config) {
@@ -46,125 +50,7 @@ async function createLexiSyncI18n(config) {
46
50
  });
47
51
  return instance;
48
52
  }
49
-
50
- // src/provider.tsx
51
- import {
52
- createContext,
53
- createElement,
54
- useCallback,
55
- useContext,
56
- useEffect,
57
- useMemo,
58
- useState
59
- } from "react";
60
- var LexiSyncContext = createContext(null);
61
- function toError(e) {
62
- return e instanceof Error ? e : new Error(String(e));
63
- }
64
- var STUB_I18N = null;
65
- function LexiSyncProvider(props) {
66
- const { children, i18n: externalI18n, suspense = false, ...rawConfig } = props;
67
- const config = useMemo(
68
- () => resolveConfig(rawConfig),
69
- // eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
70
- [
71
- rawConfig.projectId,
72
- rawConfig.apiKey,
73
- rawConfig.apiUrl,
74
- rawConfig.cdnUrl,
75
- rawConfig.version,
76
- rawConfig.lng,
77
- rawConfig.fallbackLng,
78
- rawConfig.ns,
79
- rawConfig.defaultNS,
80
- rawConfig.saveMissing
81
- ]
82
- );
83
- const [instance, setInstance] = useState(() => externalI18n ?? null);
84
- const [status, setStatus] = useState(() => externalI18n ? "ready" : "loading");
85
- const [error, setError] = useState(null);
86
- const [tick, setTick] = useState(0);
87
- const bootstrap = useCallback(async () => {
88
- if (externalI18n) {
89
- setInstance(externalI18n);
90
- setStatus("ready");
91
- setError(null);
92
- return;
93
- }
94
- setStatus("loading");
95
- setError(null);
96
- try {
97
- const i18n = await createLexiSyncI18n(config);
98
- setInstance(i18n);
99
- setStatus("ready");
100
- } catch (e) {
101
- setError(toError(e));
102
- setStatus("error");
103
- }
104
- }, [config, externalI18n]);
105
- useEffect(() => {
106
- void bootstrap();
107
- }, [bootstrap]);
108
- const changeLanguage = useCallback(async (lng) => {
109
- setInstance((current) => {
110
- if (current) {
111
- void current.changeLanguage(lng).then(() => setTick((t2) => t2 + 1));
112
- }
113
- return current;
114
- });
115
- }, []);
116
- const reload = useCallback(async () => {
117
- if (externalI18n) {
118
- await externalI18n.reloadResources();
119
- setTick((t2) => t2 + 1);
120
- return;
121
- }
122
- await bootstrap();
123
- setTick((t2) => t2 + 1);
124
- }, [bootstrap, externalI18n]);
125
- const t = useCallback(
126
- (key, options) => {
127
- void tick;
128
- return instance ? String(instance.t(key, options)) : key;
129
- },
130
- [instance, tick]
131
- );
132
- const value = useMemo(
133
- () => ({
134
- config,
135
- status,
136
- error,
137
- i18n: instance ?? STUB_I18N,
138
- t,
139
- changeLanguage,
140
- reload
141
- }),
142
- [instance, status, error, config, t, changeLanguage, reload]
143
- );
144
- if (suspense && !instance && status !== "error") {
145
- return createElement(
146
- "div",
147
- { "data-lexisync-status": status, role: "status" },
148
- "Loading translations\u2026"
149
- );
150
- }
151
- return createElement(LexiSyncContext.Provider, { value }, children);
152
- }
153
- function useLexiSync() {
154
- const ctx = useContext(LexiSyncContext);
155
- if (!ctx) {
156
- throw new Error("useLexiSync must be used within <LexiSyncProvider>");
157
- }
158
- return ctx;
159
- }
160
- function useT() {
161
- return useLexiSync().t;
162
- }
163
53
  export {
164
- LexiSyncContext,
165
- LexiSyncProvider,
166
54
  createLexiSyncI18n,
167
- resolveConfig,
168
- useLexiSync,
169
- useT
55
+ resolveConfig
170
56
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lexisync-react",
3
- "version": "0.1.2",
4
- "description": "React bindings for LexiSync — Provider, hooks, saveMissing, versioned CDN catalogs",
3
+ "version": "1.0.0",
4
+ "description": "React bindings for self-hosted LexiSync — Provider, hooks, saveMissing, versioned CDN catalogs",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -16,7 +16,9 @@
16
16
  },
17
17
  "files": [
18
18
  "dist",
19
- "src"
19
+ "src",
20
+ "README.md",
21
+ "LICENSE"
20
22
  ],
21
23
  "sideEffects": false,
22
24
  "scripts": {
@@ -31,20 +33,40 @@
31
33
  "react-i18next": ">=14.0.0"
32
34
  },
33
35
  "dependencies": {
34
- "lexisync": "*"
36
+ "lexisync": "^1.0.0"
35
37
  },
36
38
  "devDependencies": {
37
39
  "@testing-library/react": "^16.2.0",
38
40
  "@types/react": "^19.0.0",
39
41
  "@types/react-dom": "^19.0.0",
40
- "@vitest/coverage-v8": "^3.0.5",
41
- "i18next": "^24.2.2",
42
+ "@vitest/coverage-v8": "^5.0.0",
43
+ "i18next": "^26.7.2",
42
44
  "jsdom": "^26.0.0",
43
45
  "react": "^19.0.0",
44
46
  "react-dom": "^19.0.0",
45
47
  "react-i18next": "^15.4.1",
46
48
  "tsup": "^8.3.6",
47
49
  "typescript": "^5.7.2",
48
- "vitest": "^3.0.5"
49
- }
50
- }
50
+ "vitest": "^5.0.0"
51
+ },
52
+ "author": "Sander Post",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/sanderpost/lexisync",
56
+ "directory": "packages/lexisync-react"
57
+ },
58
+ "homepage": "https://github.com/sanderpost/lexisync/tree/main/packages/lexisync-react#readme",
59
+ "bugs": {
60
+ "url": "https://github.com/sanderpost/lexisync/issues"
61
+ },
62
+ "keywords": [
63
+ "lexisync",
64
+ "i18next",
65
+ "react",
66
+ "localization",
67
+ "translation",
68
+ "tms",
69
+ "i18n",
70
+ "provider"
71
+ ]
72
+ }
@@ -15,7 +15,11 @@ vi.mock('lexisync', () => {
15
15
  init(_s: unknown, opts: Record<string, unknown> = {}) {
16
16
  this.options = { ...this.options, ...opts };
17
17
  }
18
- read(lng: string, ns: string, cb: (err: Error | null, data: Record<string, string> | null) => void) {
18
+ read(
19
+ lng: string,
20
+ ns: string,
21
+ cb: (err: Error | null, data: Record<string, string> | null) => void,
22
+ ) {
19
23
  readMock(lng, ns);
20
24
  cb(null, { greeting: `hi-${lng}`, title: 'Title' });
21
25
  }
@@ -26,15 +30,22 @@ vi.mock('lexisync', () => {
26
30
  return { default: MockBackend, __esModule: true };
27
31
  });
28
32
 
33
+ const API = 'https://lexisync.example.com';
34
+
29
35
  describe('resolveConfig', () => {
30
36
  it('throws without projectId', () => {
31
- expect(() => resolveConfig({ projectId: '' })).toThrow(/projectId/);
32
- expect(() => resolveConfig({ projectId: ' ' })).toThrow(/projectId/);
37
+ expect(() => resolveConfig({ projectId: '', apiUrl: API })).toThrow(/projectId/);
38
+ expect(() => resolveConfig({ projectId: ' ', apiUrl: API })).toThrow(/projectId/);
39
+ });
40
+
41
+ it('throws without apiUrl (no hosted default)', () => {
42
+ expect(() => resolveConfig({ projectId: 'p1' } as never)).toThrow(/apiUrl is required/);
43
+ expect(() => resolveConfig({ projectId: 'p1', apiUrl: ' ' })).toThrow(/apiUrl is required/);
33
44
  });
34
45
 
35
46
  it('applies defaults', () => {
36
- const c = resolveConfig({ projectId: 'p1' });
37
- expect(c.apiUrl).toBe('https://lexisync.app');
47
+ const c = resolveConfig({ projectId: 'p1', apiUrl: API });
48
+ expect(c.apiUrl).toBe(API);
38
49
  expect(c.version).toBe('latest');
39
50
  expect(c.lng).toBe('en');
40
51
  expect(c.defaultNS).toBe('common');
@@ -47,28 +58,45 @@ describe('resolveConfig', () => {
47
58
  expect(c.apiUrl).toBe('https://x.test');
48
59
  });
49
60
 
50
- it('enables saveMissing only with apiKey + latest', () => {
61
+ it('enables saveMissing with apiKey regardless of version', () => {
62
+ // saveMissing always writes to the working copy (latest), independent of
63
+ // the READ version. So a production read can still register new keys.
51
64
  expect(
52
- resolveConfig({ projectId: 'p1', apiKey: 'sk', saveMissing: true, version: 'latest' }).saveMissing
65
+ resolveConfig({
66
+ projectId: 'p1',
67
+ apiUrl: API,
68
+ apiKey: 'sk',
69
+ saveMissing: true,
70
+ version: 'production',
71
+ }).saveMissing,
53
72
  ).toBe(true);
54
73
  expect(
55
- resolveConfig({ projectId: 'p1', apiKey: 'sk', saveMissing: true, version: 'production' }).saveMissing
74
+ resolveConfig({
75
+ projectId: 'p1',
76
+ apiUrl: API,
77
+ apiKey: 'sk',
78
+ saveMissing: true,
79
+ version: 'latest',
80
+ }).saveMissing,
81
+ ).toBe(true);
82
+ expect(
83
+ resolveConfig({ projectId: 'p1', apiUrl: API, saveMissing: true, version: 'latest' })
84
+ .saveMissing,
56
85
  ).toBe(false);
57
- expect(resolveConfig({ projectId: 'p1', saveMissing: true, version: 'latest' }).saveMissing).toBe(false);
58
86
  });
59
87
 
60
88
  it('defaultNS from ns array first element', () => {
61
- const c = resolveConfig({ projectId: 'p1', ns: ['auth', 'common'] });
89
+ const c = resolveConfig({ projectId: 'p1', apiUrl: API, ns: ['auth', 'common'] });
62
90
  expect(c.defaultNS).toBe('auth');
63
91
  });
64
92
 
65
93
  it('defaultNS falls back when ns array empty', () => {
66
- const c = resolveConfig({ projectId: 'p1', ns: [] });
94
+ const c = resolveConfig({ projectId: 'p1', apiUrl: API, ns: [] });
67
95
  expect(c.defaultNS).toBe('common');
68
96
  });
69
97
 
70
98
  it('respects explicit defaultNS', () => {
71
- const c = resolveConfig({ projectId: 'p1', ns: ['a'], defaultNS: 'custom' });
99
+ const c = resolveConfig({ projectId: 'p1', apiUrl: API, ns: ['a'], defaultNS: 'custom' });
72
100
  expect(c.defaultNS).toBe('custom');
73
101
  });
74
102
  });
@@ -93,6 +121,7 @@ describe('createLexiSyncI18n', () => {
93
121
  it('loads resources via backend (array ns)', async () => {
94
122
  const i18n = await createLexiSyncI18n({
95
123
  projectId: 'proj',
124
+ apiUrl: API,
96
125
  lng: 'en',
97
126
  ns: ['common', 'auth'],
98
127
  });
@@ -103,6 +132,7 @@ describe('createLexiSyncI18n', () => {
103
132
  it('wires saveMissing when enabled', async () => {
104
133
  const i18n = await createLexiSyncI18n({
105
134
  projectId: 'proj',
135
+ apiUrl: API,
106
136
  apiKey: 'sk_test',
107
137
  saveMissing: true,
108
138
  version: 'latest',
@@ -113,4 +143,4 @@ describe('createLexiSyncI18n', () => {
113
143
  await Promise.resolve();
114
144
  expect(i18n.isInitialized).toBe(true);
115
145
  });
116
- });
146
+ });
package/src/createI18n.ts CHANGED
@@ -2,28 +2,36 @@ import i18next, { type i18n as I18nInstance } from 'i18next';
2
2
  import LexiSyncBackend from 'lexisync';
3
3
  import type { LexiSyncConfig } from './types';
4
4
 
5
- const DEFAULT_API_URL = 'https://lexisync.app';
6
-
7
- export function resolveConfig(config: LexiSyncConfig): Required<
8
- Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>
5
+ export function resolveConfig(
6
+ config: LexiSyncConfig,
7
+ ): Required<
8
+ Pick<
9
+ LexiSyncConfig,
10
+ 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'
11
+ >
9
12
  > &
10
13
  LexiSyncConfig {
11
14
  if (!config.projectId || !String(config.projectId).trim()) {
12
15
  throw new Error('LexiSync: projectId is required');
13
16
  }
17
+ if (!config.apiUrl || !String(config.apiUrl).trim()) {
18
+ throw new Error(
19
+ 'LexiSync: apiUrl is required — the base URL of your self-hosted LexiSync instance',
20
+ );
21
+ }
14
22
  const version = config.version || 'latest';
15
23
  const ns = config.ns ?? 'common';
16
24
  const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || 'common';
17
25
  return {
18
26
  ...config,
19
27
  projectId: config.projectId,
20
- apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ''),
28
+ apiUrl: String(config.apiUrl).trim().replace(/\/$/, ''),
21
29
  version,
22
30
  lng: config.lng || 'en',
23
31
  fallbackLng: config.fallbackLng ?? 'en',
24
32
  ns,
25
33
  defaultNS,
26
- saveMissing: Boolean(config.saveMissing && config.apiKey && version === 'latest'),
34
+ saveMissing: Boolean(config.saveMissing && config.apiKey),
27
35
  };
28
36
  }
29
37
 
@@ -53,4 +61,4 @@ export async function createLexiSyncI18n(config: LexiSyncConfig): Promise<I18nIn
53
61
  });
54
62
 
55
63
  return instance;
56
- }
64
+ }
package/src/index.test.ts CHANGED
@@ -2,12 +2,15 @@ import { describe, it, expect } from 'vitest';
2
2
  import * as pkg from './index';
3
3
 
4
4
  describe('package exports', () => {
5
- it('exposes public API', () => {
6
- expect(typeof pkg.LexiSyncProvider).toBe('function');
7
- expect(typeof pkg.useLexiSync).toBe('function');
8
- expect(typeof pkg.useT).toBe('function');
5
+ it('exposes setup utility only', () => {
6
+ // LexiSyncProvider/useLexiSync/useT are gone — consumers should use
7
+ // react-i18next's I18nextProvider + useTranslation directly. createLexiSyncI18n
8
+ // is the only thing this package provides now.
9
9
  expect(typeof pkg.createLexiSyncI18n).toBe('function');
10
10
  expect(typeof pkg.resolveConfig).toBe('function');
11
- expect(pkg.LexiSyncContext).toBeTruthy();
11
+ // The removed exports must not be reachable.
12
+ expect((pkg as Record<string, unknown>).LexiSyncProvider).toBeUndefined();
13
+ expect((pkg as Record<string, unknown>).useLexiSync).toBeUndefined();
14
+ expect((pkg as Record<string, unknown>).useT).toBeUndefined();
12
15
  });
13
- });
16
+ });
package/src/index.ts CHANGED
@@ -1,4 +1,2 @@
1
- export type { LexiSyncConfig, LexiSyncContextValue, LexiSyncStatus } from './types';
1
+ export type { LexiSyncConfig } from './types';
2
2
  export { createLexiSyncI18n, resolveConfig } from './createI18n';
3
- export { LexiSyncProvider, useLexiSync, useT, LexiSyncContext } from './provider';
4
- export type { LexiSyncProviderProps } from './provider';
package/src/lexisync.d.ts CHANGED
@@ -11,9 +11,9 @@ declare module 'lexisync' {
11
11
  languages: string | string[],
12
12
  namespace: string,
13
13
  key: string,
14
- fallbackValue: string
14
+ fallbackValue: string,
15
15
  ): void;
16
16
  }
17
17
 
18
18
  export default LexiSyncBackend;
19
- }
19
+ }
package/src/test/setup.ts CHANGED
@@ -2,4 +2,4 @@ import { beforeEach, vi } from 'vitest';
2
2
 
3
3
  beforeEach(() => {
4
4
  vi.restoreAllMocks();
5
- });
5
+ });
package/src/types.ts CHANGED
@@ -3,32 +3,22 @@ export type LexiSyncConfig = {
3
3
  projectId: string;
4
4
  /** Secret key (sk_…) — required for saveMissing / write */
5
5
  apiKey?: string;
6
- /** Platform origin, default https://lexisync.app */
7
- apiUrl?: string;
8
- /** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
6
+ /** Base URL of your self-hosted LexiSync instance (required, no default) */
7
+ apiUrl: string;
8
+ /** Optional dedicated CDN origin; default `${apiUrl}/cdn` */
9
9
  cdnUrl?: string;
10
10
  /**
11
- * Catalog version:
11
+ * Catalog version (READ path):
12
12
  * - `latest` — working copy (dev, saveMissing)
13
13
  * - `production` / `1.0.0` / … — published CDN snapshot
14
+ *
15
+ * saveMissing always writes to the working copy regardless of this value.
14
16
  */
15
17
  version?: string;
16
18
  lng?: string;
17
19
  fallbackLng?: string | string[];
18
20
  ns?: string | string[];
19
21
  defaultNS?: string;
20
- /** Auto-push missing keys to working copy (needs apiKey, version latest) */
22
+ /** Auto-push missing keys to working copy (needs apiKey). */
21
23
  saveMissing?: boolean;
22
24
  };
23
-
24
- export type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
25
-
26
- export type LexiSyncContextValue = {
27
- config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
28
- status: LexiSyncStatus;
29
- error: Error | null;
30
- i18n: import('i18next').i18n;
31
- t: (key: string, options?: Record<string, unknown>) => string;
32
- changeLanguage: (lng: string) => Promise<void>;
33
- reload: () => Promise<void>;
34
- };
@@ -1,197 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen, waitFor, act } from '@testing-library/react';
3
- import { createElement } from 'react';
4
- import i18next from 'i18next';
5
- import { LexiSyncProvider, useLexiSync, useT } from './provider';
6
-
7
- vi.mock('./createI18n', async () => {
8
- const actual = await vi.importActual<typeof import('./createI18n')>('./createI18n');
9
- return {
10
- ...actual,
11
- createLexiSyncI18n: vi.fn(async (cfg: { projectId: string; lng?: string }) => {
12
- const instance = i18next.createInstance();
13
- await instance.init({
14
- lng: cfg.lng || 'en',
15
- resources: {
16
- en: { common: { hello: 'Hello', world: 'World' } },
17
- nl: { common: { hello: 'Hallo', world: 'Wereld' } },
18
- },
19
- ns: ['common'],
20
- defaultNS: 'common',
21
- });
22
- return instance;
23
- }),
24
- };
25
- });
26
-
27
- function Probe() {
28
- const { t, status, changeLanguage, reload, config } = useLexiSync();
29
- return createElement(
30
- 'div',
31
- null,
32
- createElement('span', { 'data-testid': 'status' }, status),
33
- createElement('span', { 'data-testid': 'hello' }, t('hello')),
34
- createElement('span', { 'data-testid': 'version' }, config.version),
35
- createElement(
36
- 'button',
37
- {
38
- type: 'button',
39
- onClick: () => {
40
- void changeLanguage('nl');
41
- },
42
- },
43
- 'nl'
44
- ),
45
- createElement(
46
- 'button',
47
- {
48
- type: 'button',
49
- onClick: () => {
50
- void reload();
51
- },
52
- },
53
- 'reload'
54
- )
55
- );
56
- }
57
-
58
- function TOnly() {
59
- const t = useT();
60
- return createElement('span', { 'data-testid': 't-only' }, t('world'));
61
- }
62
-
63
- describe('LexiSyncProvider', () => {
64
- beforeEach(() => {
65
- vi.clearAllMocks();
66
- });
67
-
68
- it('throws useLexiSync outside provider', () => {
69
- expect(() => render(createElement(Probe))).toThrow(/useLexiSync must be used within/);
70
- });
71
-
72
- it('renders children immediately while loading, then ready', async () => {
73
- render(createElement(LexiSyncProvider, { projectId: 'p1', version: 'latest' }, createElement(Probe)));
74
- // No blank "Loading translations…" gate — shell is visible with status=loading
75
- expect(screen.getByTestId('status').textContent).toBe('loading');
76
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
77
- expect(screen.getByTestId('hello').textContent).toBe('Hello');
78
- expect(screen.getByTestId('version').textContent).toBe('latest');
79
- });
80
-
81
- it('suspense=true keeps legacy loading gate', () => {
82
- render(
83
- createElement(
84
- LexiSyncProvider,
85
- { projectId: 'p1', suspense: true },
86
- createElement(Probe)
87
- )
88
- );
89
- expect(screen.getByRole('status').textContent).toMatch(/Loading translations/i);
90
- });
91
-
92
- it('useT returns translations', async () => {
93
- render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(TOnly)));
94
- await waitFor(() => expect(screen.getByTestId('t-only').textContent).toBe('World'));
95
- });
96
-
97
- it('changeLanguage updates strings', async () => {
98
- render(createElement(LexiSyncProvider, { projectId: 'p1', lng: 'en' }, createElement(Probe)));
99
- await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('Hello'));
100
- await act(async () => {
101
- screen.getByText('nl').click();
102
- });
103
- await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('Hallo'));
104
- });
105
-
106
- it('reload works', async () => {
107
- render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(Probe)));
108
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
109
- await act(async () => {
110
- screen.getByText('reload').click();
111
- });
112
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
113
- });
114
-
115
- it('accepts external i18n instance', async () => {
116
- const external = i18next.createInstance();
117
- await external.init({
118
- lng: 'en',
119
- resources: { en: { common: { hello: 'External' } } },
120
- ns: ['common'],
121
- defaultNS: 'common',
122
- });
123
- render(createElement(LexiSyncProvider, { projectId: 'p1', i18n: external }, createElement(Probe)));
124
- await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('External'));
125
- });
126
-
127
- it('reload with external i18n calls reloadResources', async () => {
128
- const external = i18next.createInstance();
129
- await external.init({
130
- lng: 'en',
131
- resources: { en: { common: { hello: 'Ext' } } },
132
- ns: ['common'],
133
- defaultNS: 'common',
134
- });
135
- const spy = vi.spyOn(external, 'reloadResources').mockResolvedValue(external as never);
136
- render(createElement(LexiSyncProvider, { projectId: 'p1', i18n: external }, createElement(Probe)));
137
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
138
- await act(async () => {
139
- screen.getByText('reload').click();
140
- });
141
- expect(spy).toHaveBeenCalled();
142
- });
143
-
144
- it('surfaces error status when create fails with Error', async () => {
145
- const { createLexiSyncI18n } = await import('./createI18n');
146
- vi.mocked(createLexiSyncI18n).mockRejectedValueOnce(new Error('boom'));
147
-
148
- function ErrProbe() {
149
- const { status, error, t, changeLanguage } = useLexiSync();
150
- return createElement(
151
- 'div',
152
- null,
153
- createElement('span', { 'data-testid': 'status' }, status),
154
- createElement('span', { 'data-testid': 'err' }, error?.message || ''),
155
- createElement('span', { 'data-testid': 't' }, t('x')),
156
- createElement(
157
- 'button',
158
- {
159
- type: 'button',
160
- onClick: () => {
161
- void changeLanguage('de');
162
- },
163
- },
164
- 'de'
165
- )
166
- );
167
- }
168
-
169
- render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(ErrProbe)));
170
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('error'));
171
- expect(screen.getByTestId('err').textContent).toBe('boom');
172
- expect(screen.getByTestId('t').textContent).toBe('x');
173
- await act(async () => {
174
- screen.getByText('de').click();
175
- });
176
- expect(screen.getByTestId('status').textContent).toBe('error');
177
- });
178
-
179
- it('surfaces error when create fails with non-Error', async () => {
180
- const { createLexiSyncI18n } = await import('./createI18n');
181
- vi.mocked(createLexiSyncI18n).mockRejectedValueOnce('string-fail');
182
-
183
- function ErrProbe() {
184
- const { status, error } = useLexiSync();
185
- return createElement(
186
- 'div',
187
- null,
188
- createElement('span', { 'data-testid': 'status' }, status),
189
- createElement('span', { 'data-testid': 'err' }, error?.message || '')
190
- );
191
- }
192
-
193
- render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(ErrProbe)));
194
- await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('error'));
195
- expect(screen.getByTestId('err').textContent).toBe('string-fail');
196
- });
197
- });
package/src/provider.tsx DELETED
@@ -1,148 +0,0 @@
1
- import {
2
- createContext,
3
- createElement,
4
- useCallback,
5
- useContext,
6
- useEffect,
7
- useMemo,
8
- useState,
9
- type ReactNode,
10
- } from 'react';
11
- import type { i18n as I18nInstance } from 'i18next';
12
- import { createLexiSyncI18n, resolveConfig } from './createI18n';
13
- import type { LexiSyncConfig, LexiSyncContextValue, LexiSyncStatus } from './types';
14
-
15
- const LexiSyncContext = createContext<LexiSyncContextValue | null>(null);
16
-
17
- export type LexiSyncProviderProps = LexiSyncConfig & {
18
- children: ReactNode;
19
- /** Optional pre-built i18n instance (tests / advanced). */
20
- i18n?: I18nInstance;
21
- /**
22
- * When true (default), children render immediately while CDN/bootstrap loads.
23
- * `t()` returns the key until ready — pair with local fallbacks for zero flash.
24
- * Set false only if you want a hard loading gate.
25
- */
26
- suspense?: boolean;
27
- };
28
-
29
- function toError(e: unknown): Error {
30
- return e instanceof Error ? e : new Error(String(e));
31
- }
32
-
33
- /** Minimal stand-in so consumers never crash before i18n boots. */
34
- const STUB_I18N = null as unknown as I18nInstance;
35
-
36
- export function LexiSyncProvider(props: LexiSyncProviderProps) {
37
- const { children, i18n: externalI18n, suspense = false, ...rawConfig } = props;
38
- const config = useMemo(
39
- () => resolveConfig(rawConfig),
40
- // eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
41
- [
42
- rawConfig.projectId,
43
- rawConfig.apiKey,
44
- rawConfig.apiUrl,
45
- rawConfig.cdnUrl,
46
- rawConfig.version,
47
- rawConfig.lng,
48
- rawConfig.fallbackLng,
49
- rawConfig.ns,
50
- rawConfig.defaultNS,
51
- rawConfig.saveMissing,
52
- ]
53
- );
54
-
55
- const [instance, setInstance] = useState<I18nInstance | null>(() => externalI18n ?? null);
56
- const [status, setStatus] = useState<LexiSyncStatus>(() => (externalI18n ? 'ready' : 'loading'));
57
- const [error, setError] = useState<Error | null>(null);
58
- const [tick, setTick] = useState(0);
59
-
60
- const bootstrap = useCallback(async () => {
61
- if (externalI18n) {
62
- setInstance(externalI18n);
63
- setStatus('ready');
64
- setError(null);
65
- return;
66
- }
67
- setStatus('loading');
68
- setError(null);
69
- try {
70
- const i18n = await createLexiSyncI18n(config);
71
- setInstance(i18n);
72
- setStatus('ready');
73
- } catch (e) {
74
- setError(toError(e));
75
- setStatus('error');
76
- }
77
- }, [config, externalI18n]);
78
-
79
- useEffect(() => {
80
- void bootstrap();
81
- }, [bootstrap]);
82
-
83
- const changeLanguage = useCallback(async (lng: string) => {
84
- setInstance((current) => {
85
- if (current) {
86
- void current.changeLanguage(lng).then(() => setTick((t) => t + 1));
87
- }
88
- return current;
89
- });
90
- }, []);
91
-
92
- const reload = useCallback(async () => {
93
- if (externalI18n) {
94
- await externalI18n.reloadResources();
95
- setTick((t) => t + 1);
96
- return;
97
- }
98
- await bootstrap();
99
- setTick((t) => t + 1);
100
- }, [bootstrap, externalI18n]);
101
-
102
- const t = useCallback(
103
- (key: string, options?: Record<string, unknown>) => {
104
- void tick;
105
- return instance ? String(instance.t(key, options)) : key;
106
- },
107
- [instance, tick]
108
- );
109
-
110
- const value = useMemo<LexiSyncContextValue>(
111
- () => ({
112
- config,
113
- status,
114
- error,
115
- i18n: instance ?? STUB_I18N,
116
- t,
117
- changeLanguage,
118
- reload,
119
- }),
120
- [instance, status, error, config, t, changeLanguage, reload]
121
- );
122
-
123
- // Optional hard gate (legacy). Default: always paint children.
124
- if (suspense && !instance && status !== 'error') {
125
- return createElement(
126
- 'div',
127
- { 'data-lexisync-status': status, role: 'status' },
128
- 'Loading translations…'
129
- );
130
- }
131
-
132
- return createElement(LexiSyncContext.Provider, { value }, children);
133
- }
134
-
135
- export function useLexiSync(): LexiSyncContextValue {
136
- const ctx = useContext(LexiSyncContext);
137
- if (!ctx) {
138
- throw new Error('useLexiSync must be used within <LexiSyncProvider>');
139
- }
140
- return ctx;
141
- }
142
-
143
- /** Shortcut: translation function bound to the provider instance. */
144
- export function useT() {
145
- return useLexiSync().t;
146
- }
147
-
148
- export { LexiSyncContext };