@juicesharp/rpiv-i18n 1.1.2 → 1.1.4

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 (2) hide show
  1. package/README.md +96 -17
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -110,7 +110,39 @@ export default function (pi: ExtensionAPI) {
110
110
 
111
111
  ## Localizing your extension — step by step
112
112
 
113
- The inline example above is fine for a one-key smoke test. For a real Pi extension, use the file-based pattern that scales to dozens of strings and ten contributors. Same shape proven in production.
113
+ The inline example above is fine for a one-key smoke test. For a real Pi extension, use the file-based pattern that scales to dozens of strings and ten contributors. Two production exemplars in this monorepo follow this exact shape: `packages/rpiv-ask-user-question/` (questionnaire UI; bridge owns `t` + `displayLabel(kind)` for sentinel rows) and `packages/rpiv-todo/` (todo overlay + `/todos` command; bridge owns `t` + `formatStatusLabel(status)` reused across overlay and command). Read either alongside this guide.
114
+
115
+ End state on disk:
116
+
117
+ ```
118
+ my-extension/
119
+ ├── index.ts ← default export + registerStrings(...)
120
+ ├── state/
121
+ │ └── i18n-bridge.ts ← exports `t` + I18N_NAMESPACE
122
+ ├── locales/
123
+ │ ├── en.json ← canonical baseline (required)
124
+ │ ├── uk.json ← optional additional locales
125
+ │ └── …
126
+ └── package.json ← peerDependencies + files[] + pi.extensions
127
+ ```
128
+
129
+ ### 0. Declare the SDK as an OPTIONAL peer dependency
130
+
131
+ ```json
132
+ {
133
+ "peerDependencies": {
134
+ "@juicesharp/rpiv-i18n": "*",
135
+ "@mariozechner/pi-coding-agent": "*"
136
+ },
137
+ "peerDependenciesMeta": {
138
+ "@juicesharp/rpiv-i18n": { "optional": true }
139
+ }
140
+ }
141
+ ```
142
+
143
+ Use `peerDependencies`, not `dependencies` — the user's Pi session loads one copy of the SDK; if you bundle your own, `/languages` toggles a different runtime instance and your strings never switch.
144
+
145
+ Mark it `optional: true` in `peerDependenciesMeta` so npm doesn't warn when a user installs your extension standalone without rpiv-i18n. Pair this with the dynamic-import shim shown in step 3 — your extension stays online with English-only UI when the SDK isn't installed, and lights up localization automatically when it is.
114
146
 
115
147
  ### 1. Author a `locales/en.json` next to your source
116
148
 
@@ -128,26 +160,43 @@ Conventions: flat dotted lowercase keys, `snake_case` only for multi-word leaves
128
160
 
129
161
  ### 2. Add a one-file bridge inside your package
130
162
 
131
- `state/i18n-bridge.ts` (or wherever your package keeps cross-cutting helpers):
163
+ `state/i18n-bridge.ts` (or wherever your package keeps cross-cutting helpers). Use a dynamic-import shim with top-level `await` so a missing peer degrades to English-only instead of failing module load:
132
164
 
133
165
  ```ts
134
- import { scope } from "@juicesharp/rpiv-i18n";
135
-
136
166
  export const I18N_NAMESPACE = "@my-org/cool-tool";
137
167
 
138
- export const t = scope(I18N_NAMESPACE);
168
+ type ScopeFn = (key: string, fallback: string) => string;
169
+ type I18nSDK = { scope: (namespace: string) => ScopeFn };
170
+
171
+ let scopeImpl: ScopeFn;
172
+ try {
173
+ const sdk = (await import("@juicesharp/rpiv-i18n")) as I18nSDK;
174
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
175
+ } catch {
176
+ // SDK not installed — every t(key, fallback) returns the fallback verbatim.
177
+ scopeImpl = (_key, fallback) => fallback;
178
+ }
179
+
180
+ export const t: ScopeFn = scopeImpl;
139
181
  ```
140
182
 
141
183
  Every render-time call site imports `t` from this one file. If you ever switch namespaces, change the SDK, or add a `displayLabel(kind)` convenience for sentinel-row enums, you touch one place.
142
184
 
185
+ **Why dynamic import instead of static `import { scope } from "@juicesharp/rpiv-i18n"`?** A static ESM import is hoisted and evaluated at module load — if the SDK isn't on disk, your entire extension fails to load with `Cannot find module '@juicesharp/rpiv-i18n'`. The dynamic `await import()` inside a try/catch lets module load proceed, and the identity-fallback closure keeps your render call sites working with English. Top-level await is required because the `t` export is consumed synchronously by every render call site downstream.
186
+
143
187
  ### 3. Register strings at extension load
144
188
 
189
+ Use the same dynamic-import shim pattern as the bridge — `registerStrings` is a runtime call, so it goes inside a try/catch that no-ops when the SDK is missing:
190
+
145
191
  ```ts
146
192
  import { readFileSync } from "node:fs";
147
193
  import { fileURLToPath } from "node:url";
148
- import { registerStrings, type TranslationMap } from "@juicesharp/rpiv-i18n";
194
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
149
195
  import { I18N_NAMESPACE } from "./state/i18n-bridge.js";
150
196
 
197
+ type TranslationMap = Readonly<Record<string, string>>;
198
+ type I18nSDK = { registerStrings: (ns: string, byLocale: Record<string, TranslationMap>) => void };
199
+
151
200
  function loadLocale(code: string): TranslationMap {
152
201
  // A missing/malformed locale file MUST NOT crash module init — the bridge's
153
202
  // literal English fallbacks will keep every render readable.
@@ -161,13 +210,18 @@ function loadLocale(code: string): TranslationMap {
161
210
  }
162
211
  }
163
212
 
164
- registerStrings(I18N_NAMESPACE, {
165
- en: loadLocale("en"),
166
- // Add more as files arrive. Order doesn't matter; keys missing from a non-en
167
- // map fall back to en automatically.
168
- });
213
+ try {
214
+ const sdk = (await import("@juicesharp/rpiv-i18n")) as I18nSDK;
215
+ sdk.registerStrings(I18N_NAMESPACE, {
216
+ en: loadLocale("en"),
217
+ // Add more as files arrive. Order doesn't matter; keys missing from a
218
+ // non-en map fall back to en automatically.
219
+ });
220
+ } catch {
221
+ // SDK absent — extension still loads with English-only UI.
222
+ }
169
223
 
170
- export default function (pi /* : ExtensionAPI */) {
224
+ export default function (pi: ExtensionAPI): void {
171
225
  // your tool/command/hook registrations here…
172
226
  }
173
227
  ```
@@ -246,6 +300,24 @@ Wire it into `registerStrings({ en: …, uk: loadLocale("uk") })`. To make the l
246
300
 
247
301
  Done. `/languages` now switches your extension's UI alongside every other extension that adopts the SDK.
248
302
 
303
+ ### Verify it works locally before publishing
304
+
305
+ The SDK only flips strings when it's loaded by a real Pi session — `npm test` won't catch a missing `files[]` entry or a wrong namespace. Smoke-test against a live `pi` shell:
306
+
307
+ ```bash
308
+ # from your extension's directory
309
+ npm pack # produces my-extension-x.y.z.tgz
310
+ pi install file:./my-extension-x.y.z.tgz # install into your Pi session
311
+ pi install npm:@juicesharp/rpiv-i18n # if not already installed
312
+ pi # launch the session
313
+ > /languages # pick a non-English locale
314
+ > <invoke a command/tool from your extension> # confirm the strings flip
315
+ ```
316
+
317
+ Two failure modes this catches that unit tests do not:
318
+ 1. **Locale JSON not shipped** — `/languages` switches but your strings stay English. Fix: add `"locales/"` to `package.json` `files[]`.
319
+ 2. **Module-init `tr(...)` capture** — picker switches, other extensions flip, yours doesn't. Fix: move the `t(...)` call inside the render function.
320
+
249
321
  ## Contributing translations
250
322
 
251
323
  Want to add or improve a translation for a Pi extension that uses this SDK? Open a PR — the contract is small and uniform across packages.
@@ -326,11 +398,18 @@ For tools that prefer not to import this package, the active state is also publi
326
398
 
327
399
  ```ts
328
400
  const I18N = Symbol.for("rpiv-i18n");
329
- const state = (globalThis as any)[I18N] as
330
- | { locale: string | undefined; namespaces: Record<string, Record<string, string>> }
331
- | undefined;
332
401
 
333
- const value = state?.namespaces["@my-org/cool-tool"]?.["welcome"] ?? "Welcome!";
402
+ function lookup(key: string, fallback: string): string {
403
+ // Re-read the symbol on every call — the SDK *replaces* the snapshot
404
+ // (frozen object) on every registerStrings/applyLocale, so a cached
405
+ // reference will silently serve stale strings after `/languages`.
406
+ const state = (globalThis as { [k: symbol]: unknown })[I18N] as
407
+ | { locale: string | undefined; namespaces: Record<string, Record<string, string>> }
408
+ | undefined;
409
+ return state?.namespaces["@my-org/cool-tool"]?.[key] ?? fallback;
410
+ }
411
+
412
+ lookup("welcome", "Welcome!");
334
413
  ```
335
414
 
336
- This is read-only; registration MUST go through `registerStrings(...)`.
415
+ The published object is frozen *per snapshot*, so each new locale produces a new frozen object — read the symbol at call time, never hoist it into a module-scope `const`. Registration MUST still go through `registerStrings(...)`; writing into `globalThis[I18N]` directly is unsupported.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-i18n",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "Pi extension: i18n/localization foundation — locale detection, /languages command, --locale flag, cross-package locale registry",
5
5
  "keywords": [
6
6
  "pi-package",