@embedpdf/plugin-i18n 2.14.4 → 3.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +192 -21
  2. package/dist/index.cjs +268 -2
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +159 -0
  5. package/dist/index.d.ts +159 -1
  6. package/dist/index.js +262 -397
  7. package/dist/index.js.map +1 -1
  8. package/package.json +18 -58
  9. package/dist/lib/actions.d.ts +0 -15
  10. package/dist/lib/i18n-plugin.d.ts +0 -28
  11. package/dist/lib/index.d.ts +0 -9
  12. package/dist/lib/locales/en.d.ts +0 -2
  13. package/dist/lib/locales/es.d.ts +0 -2
  14. package/dist/lib/locales/index.d.ts +0 -2
  15. package/dist/lib/manifest.d.ts +0 -4
  16. package/dist/lib/reducer.d.ts +0 -5
  17. package/dist/lib/types.d.ts +0 -104
  18. package/dist/preact/adapter.d.ts +0 -5
  19. package/dist/preact/core.d.ts +0 -1
  20. package/dist/preact/index.cjs +0 -2
  21. package/dist/preact/index.cjs.map +0 -1
  22. package/dist/preact/index.d.ts +0 -1
  23. package/dist/preact/index.js +0 -70
  24. package/dist/preact/index.js.map +0 -1
  25. package/dist/react/adapter.d.ts +0 -2
  26. package/dist/react/core.d.ts +0 -1
  27. package/dist/react/index.cjs +0 -2
  28. package/dist/react/index.cjs.map +0 -1
  29. package/dist/react/index.d.ts +0 -1
  30. package/dist/react/index.js +0 -69
  31. package/dist/react/index.js.map +0 -1
  32. package/dist/shared/components/index.d.ts +0 -1
  33. package/dist/shared/components/translate.d.ts +0 -35
  34. package/dist/shared/hooks/index.d.ts +0 -1
  35. package/dist/shared/hooks/use-i18n.d.ts +0 -43
  36. package/dist/shared/index.d.ts +0 -3
  37. package/dist/shared-preact/components/index.d.ts +0 -1
  38. package/dist/shared-preact/components/translate.d.ts +0 -35
  39. package/dist/shared-preact/hooks/index.d.ts +0 -1
  40. package/dist/shared-preact/hooks/use-i18n.d.ts +0 -43
  41. package/dist/shared-preact/index.d.ts +0 -3
  42. package/dist/shared-react/components/index.d.ts +0 -1
  43. package/dist/shared-react/components/translate.d.ts +0 -35
  44. package/dist/shared-react/hooks/index.d.ts +0 -1
  45. package/dist/shared-react/hooks/use-i18n.d.ts +0 -43
  46. package/dist/shared-react/index.d.ts +0 -3
  47. package/dist/svelte/components/Translate.svelte.d.ts +0 -9
  48. package/dist/svelte/components/index.d.ts +0 -1
  49. package/dist/svelte/hooks/index.d.ts +0 -1
  50. package/dist/svelte/hooks/use-i18n.svelte.d.ts +0 -41
  51. package/dist/svelte/index.cjs +0 -2
  52. package/dist/svelte/index.cjs.map +0 -1
  53. package/dist/svelte/index.d.ts +0 -3
  54. package/dist/svelte/index.js +0 -90
  55. package/dist/svelte/index.js.map +0 -1
  56. package/dist/vue/components/index.d.ts +0 -1
  57. package/dist/vue/components/translate.vue.d.ts +0 -9
  58. package/dist/vue/hooks/index.d.ts +0 -1
  59. package/dist/vue/hooks/use-i18n.d.ts +0 -30
  60. package/dist/vue/index.cjs +0 -2
  61. package/dist/vue/index.cjs.map +0 -1
  62. package/dist/vue/index.d.ts +0 -3
  63. package/dist/vue/index.js +0 -99
  64. package/dist/vue/index.js.map +0 -1
package/LICENSE CHANGED
@@ -1,21 +1,192 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 CloudPDF
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.
1
+ Copyright 2026 CloudPDF LTD
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use files in this distribution except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ https://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ -----------------------------------------------------------------------
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/dist/index.cjs CHANGED
@@ -1,2 +1,268 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core"),a={code:"en",name:"English",translations:{commands:{zoom:{in:"Zoom In",out:"Zoom Out",fitWidth:"Fit to Width",fitPage:"Fit to Page",automatic:"Automatic",level:"Zoom Level ({level}%)",inArea:"Zoom In Area"},fullscreen:{enter:"Enter Full Screen",exit:"Exit Full Screen"},rotate:{clockwise:"Rotate Clockwise",counterclockwise:"Rotate Counter-Clockwise"},menu:"Menu",sidebar:"Sidebar",search:"Search",comment:"Comment",download:"Download",print:"Print",openFile:"Open PDF",save:"Save",settings:"Settings",view:"View",annotate:"Annotate",shapes:"Shapes",redact:"Redact",fillAndSign:"Fill and Sign",form:"Form",pan:"Pan",pointer:"Pointer",undo:"Undo",redo:"Redo",copy:"Copy",screenshot:"Screenshot",nextPage:"Next Page",previousPage:"Previous Page"}}},t={code:"es",name:"Español",translations:{commands:{zoom:{in:"Acercar",out:"Alejar",fitWidth:"Ajustar al ancho",fitPage:"Ajustar a la página",automatic:"Automático",level:"Nivel de zoom ({level}%)",inArea:"Acercar área"},fullscreen:{enter:"Pantalla completa",exit:"Salir de pantalla completa"},rotate:{clockwise:"Girar a la derecha",counterclockwise:"Girar a la izquierda"},menu:"Menú",sidebar:"Barra lateral",search:"Buscar",comment:"Comentario",download:"Descargar",print:"Imprimir",openFile:"Abrir PDF",save:"Guardar",settings:"Configuración",view:"Ver",annotate:"Anotar",shapes:"Formas",redact:"Redactar",fillAndSign:"Rellenar y firmar",form:"Formulario",pan:"Desplazar",pointer:"Puntero",undo:"Deshacer",redo:"Rehacer",copy:"Copiar",screenshot:"Captura de pantalla",nextPage:"Página siguiente",previousPage:"Página anterior"}}},r="i18n",s={id:r,name:"I18n Plugin",version:"1.0.0",provides:["i18n"],requires:[],optional:[],defaultConfig:{defaultLocale:"en",locales:[a,t]}},o="I18N/SET_LOCALE",i="I18N/REGISTER_LOCALE",n=e=>({type:o,payload:e}),l=e=>({type:i,payload:e}),c=class extends e.BasePlugin{constructor(a,t,r){super(a,t),this.locales=new Map,this.paramResolvers=new Map,this.paramsCache=new Map,this.localeChange$=e.createEmitter(),this.paramsChanged$=e.createScopedEmitter((e,a)=>({documentId:e,...a}),{cache:!1}),this.config=r,r.locales.forEach(e=>{this.locales.set(e.code,e),this.dispatch(l(e.code))}),r.paramResolvers&&Object.entries(r.paramResolvers).forEach(([e,a])=>{this.paramResolvers.set(e,a)}),this.dispatch(n(r.defaultLocale)),this.registry.getStore().subscribe((e,a)=>{this.detectParamChanges(a)})}async initialize(){this.logger.info("I18nPlugin","Initialize","I18n plugin initialized")}async destroy(){this.localeChange$.clear(),this.paramsChanged$.clear(),this.paramResolvers.clear(),this.paramsCache.clear(),super.destroy()}onDocumentClosed(e){this.paramsCache.delete(e),this.paramsChanged$.clearScope(e),this.logger.debug("I18nPlugin","DocumentClosed",`Cleaned up params cache for document: ${e}`)}buildCapability(){return{t:(e,a)=>this.translate(e,a),forDocument:e=>this.createI18nScope(e),registerParamResolver:(e,a)=>this.registerParamResolver(e,a),unregisterParamResolver:e=>this.unregisterParamResolver(e),setLocale:e=>this.setLocale(e),getLocale:()=>this.state.currentLocale,getAvailableLocales:()=>[...this.state.availableLocales],getLocaleInfo:e=>this.locales.get(e)??null,registerLocale:e=>this.registerLocale(e),hasLocale:e=>this.locales.has(e),onLocaleChange:this.localeChange$.on,onParamsChanged:this.paramsChanged$.onGlobal}}createI18nScope(e){return{t:(a,t)=>this.translate(a,{documentId:e,...t}),onParamsChanged:this.paramsChanged$.forScope(e)}}translate(e,a){const t=this.locales.get(this.state.currentLocale),r=this.config.fallbackLocale?this.locales.get(this.config.fallbackLocale):null;let s=this.getNestedValue(null==t?void 0:t.translations,e);if(!s&&r&&(s=this.getNestedValue(r.translations,e)),!s){if(!(null==a?void 0:a.fallback))return this.logger.warn("I18nPlugin","MissingTranslation",`Translation not found for key: ${e}`),e;s=a.fallback}let o=null==a?void 0:a.params;return!o&&this.paramResolvers.has(e)&&(o=this.resolveParams(e,null==a?void 0:a.documentId)),this.interpolate(s,o)}resolveParams(e,a){const t=this.paramResolvers.get(e);if(!t)return;const r=this.registry.getStore().getState();try{return t({state:r,documentId:a})}catch(s){return void this.logger.error("I18nPlugin","ParamResolverError",`Error resolving params for key "${e}":`,s)}}getNestedValue(e,a){if(!e)return;const t=a.split(".");let r=e;for(const s of t){if(null==r)return;r=r[s]}return"string"==typeof r?r:void 0}interpolate(e,a){return a?e.replace(/\{(\w+)\}/g,(e,t)=>{const r=a[t];return void 0!==r?String(r):e}):e}detectParamChanges(e){Object.keys(e.core.documents).forEach(a=>{this.detectDocumentParamChanges(a,e)})}detectDocumentParamChanges(a,t){const r=this.paramsCache.get(a),s=[];this.paramResolvers.forEach((o,i)=>{try{const n=o({state:t,documentId:a}),l=null==r?void 0:r.get(i);e.arePropsEqual(l,n)||(s.push(i),this.paramsCache.has(a)||this.paramsCache.set(a,new Map),this.paramsCache.get(a).set(i,n))}catch(n){this.logger.error("I18nPlugin","ParamDetectionError",`Error detecting param changes for key "${i}":`,n)}}),s.length>0&&(this.paramsChanged$.emit(a,{changedKeys:s}),this.logger.debug("I18nPlugin","ParamsChanged",`Translation params changed for document ${a}:`,s))}registerParamResolver(e,a){this.paramResolvers.has(e)&&this.logger.warn("I18nPlugin","ResolverOverwrite",`Param resolver for "${e}" already exists and will be overwritten`),this.paramResolvers.set(e,a),this.paramsCache.forEach(a=>{a.delete(e)}),this.logger.debug("I18nPlugin","ResolverRegistered",`Param resolver registered for: ${e}`)}unregisterParamResolver(e){this.paramResolvers.delete(e)&&(this.paramsCache.forEach(a=>{a.delete(e)}),this.logger.debug("I18nPlugin","ResolverUnregistered",`Param resolver unregistered for: ${e}`))}setLocale(e){if(!this.locales.has(e))return void this.logger.warn("I18nPlugin","LocaleNotFound",`Locale '${e}' is not registered`);const a=this.state.currentLocale;a!==e&&(this.dispatch(n(e)),this.localeChange$.emit({previousLocale:a,currentLocale:e}),this.logger.info("I18nPlugin","LocaleChanged",`Locale changed to: ${e}`))}registerLocale(e){this.locales.has(e.code)?this.logger.warn("I18nPlugin","LocaleAlreadyRegistered",`Locale '${e.code}' is already registered`):(this.locales.set(e.code,e),this.dispatch(l(e.code)),this.logger.info("I18nPlugin","LocaleRegistered",`Locale registered: ${e.code}`))}};c.id="i18n";let h=c;const g={currentLocale:"en",availableLocales:[]},d={manifest:s,create:(e,a)=>new h(r,e,a),reducer:(e=g,a)=>{switch(a.type){case o:{const t=a.payload;return e.availableLocales.includes(t)?{...e,currentLocale:t}:(console.warn(`I18nPlugin: Locale '${t}' not available`),e)}case i:{const t=a.payload;return e.availableLocales.includes(t)?e:{...e,availableLocales:[...e.availableLocales,t]}}default:return e}},initialState:g};exports.I18N_PLUGIN_ID=r,exports.I18nPlugin=h,exports.I18nPluginPackage=d,exports.enUS=a,exports.esES=t,exports.manifest=s;
2
- //# sourceMappingURL=index.cjs.map
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _embedpdf_core = require("@embedpdf/core");
3
+ //#region src/translate.ts
4
+ /**
5
+ * The pure lookup core — state in, string out. No platform access anywhere
6
+ * (`Intl.PluralRules` is core ECMAScript, not DOM); this is the part that
7
+ * ports to Rust verbatim.
8
+ */
9
+ /** Walk a dotted path ('commands.zoom.in') through a dictionary tree. */
10
+ function lookup(dict, key) {
11
+ if (!dict) return void 0;
12
+ let node = dict;
13
+ for (const part of key.split(".")) {
14
+ if (node === void 0 || typeof node === "string") return void 0;
15
+ node = node[part];
16
+ }
17
+ return node;
18
+ }
19
+ /** CLDR plural category for a count, with a safe fallback when the runtime
20
+ * lacks ICU data for the locale. */
21
+ function pluralCategory(locale, count) {
22
+ try {
23
+ return new Intl.PluralRules(locale).select(count);
24
+ } catch {
25
+ return count === 1 ? "one" : "other";
26
+ }
27
+ }
28
+ /** A leaf hit is a string; a branch object needs a plural pick via `count`. */
29
+ function resolveNode(node, locale, params) {
30
+ if (typeof node === "string") return node;
31
+ if (node !== void 0 && typeof params?.count === "number") {
32
+ const branch = node[pluralCategory(locale, params.count)] ?? node["other"];
33
+ if (typeof branch === "string") return branch;
34
+ }
35
+ }
36
+ /** Replace `{slot}` markers; unknown slots stay verbatim (visible in QA). */
37
+ function interpolate(text, params) {
38
+ if (!params) return text;
39
+ return text.replace(/\{(\w+)\}/g, (match, slot) => params[slot] !== void 0 ? String(params[slot]) : match);
40
+ }
41
+ /**
42
+ * Resolve a key against the state: current locale → fallback locale →
43
+ * `options.fallback` (interpolated too) → the key itself.
44
+ */
45
+ function translate(state, key, options) {
46
+ const { locale, fallbackLocale, locales } = state;
47
+ const text = resolveNode(lookup(locales[locale]?.translations, key), locale, options?.params) ?? resolveNode(lookup(locales[fallbackLocale]?.translations, key), fallbackLocale, options?.params);
48
+ if (text !== void 0) return {
49
+ text: interpolate(text, options?.params),
50
+ found: true
51
+ };
52
+ if (options?.fallback !== void 0) return {
53
+ text: interpolate(options.fallback, options.params),
54
+ found: false
55
+ };
56
+ return {
57
+ text: key,
58
+ found: false
59
+ };
60
+ }
61
+ //#endregion
62
+ //#region src/capability.ts
63
+ /**
64
+ * The i18n capability — selectors (pure reads over state) + intents (the only
65
+ * writers). Built synchronously in `createKernel()`, so `t()` works before the
66
+ * engine exists — including inside the viewer shell's loading UI.
67
+ */
68
+ function createI18nCapability(ctx, config) {
69
+ const warned = /* @__PURE__ */ new Set();
70
+ const warnOnce = (id, message) => {
71
+ if (warned.has(id)) return;
72
+ warned.add(id);
73
+ console.warn(message);
74
+ };
75
+ return {
76
+ t: (key, options) => {
77
+ const result = translate(ctx.getState(), key, options);
78
+ if (!result.found && options?.fallback === void 0) warnOnce(`key:${key}`, `[i18n] missing translation "${key}" (locale: ${ctx.getState().locale})`);
79
+ return result.text;
80
+ },
81
+ locale: () => ctx.getState().locale,
82
+ dir: () => {
83
+ const { locales, locale } = ctx.getState();
84
+ return locales[locale]?.dir ?? "ltr";
85
+ },
86
+ locales: () => {
87
+ const { locales } = ctx.getState();
88
+ const known = Object.values(locales).map((locale) => ({
89
+ code: locale.code,
90
+ name: locale.name,
91
+ dir: locale.dir ?? "ltr",
92
+ loaded: true
93
+ }));
94
+ for (const code of Object.keys(config.loaders ?? {})) if (!locales[code]) known.push({
95
+ code,
96
+ name: code,
97
+ dir: "ltr",
98
+ loaded: false
99
+ });
100
+ return known;
101
+ },
102
+ loading: () => ctx.getState().loading,
103
+ setLocale: (code) => {
104
+ if (ctx.getState().locales[code]) ctx.dispatch({
105
+ type: "I18N/SET_LOCALE",
106
+ locale: code
107
+ });
108
+ else if (config.loaders?.[code]) ctx.dispatch({
109
+ type: "I18N/LOAD_STARTED",
110
+ locale: code
111
+ });
112
+ else warnOnce(`locale:${code}`, `[i18n] unknown locale "${code}" — not registered and no loader configured`);
113
+ },
114
+ registerLocale: (locale) => ctx.dispatch({
115
+ type: "I18N/REGISTER_LOCALE",
116
+ locale
117
+ })
118
+ };
119
+ }
120
+ //#endregion
121
+ //#region src/effects.ts
122
+ /**
123
+ * The plugin's ONE side-effect: fetching lazy locale packs. State-driven — a
124
+ * load is `state.loading`, set by the capability (a switch to a lazy pack) or
125
+ * by the initial state (a lazy startup locale), so a load requested before
126
+ * effects ran is picked up here and nothing is lost to boot ordering.
127
+ */
128
+ function registerI18nEffects(config) {
129
+ return (ctx) => {
130
+ const load = (code) => {
131
+ const loader = config.loaders?.[code];
132
+ if (!loader) return;
133
+ loader().then((locale) => {
134
+ ctx.dispatch({
135
+ type: "I18N/REGISTER_LOCALE",
136
+ locale
137
+ });
138
+ if (ctx.getState().loading === code) ctx.dispatch({
139
+ type: "I18N/SET_LOCALE",
140
+ locale: locale.code
141
+ });
142
+ }, () => ctx.dispatch({
143
+ type: "I18N/LOAD_FAILED",
144
+ locale: code
145
+ }));
146
+ };
147
+ const pending = ctx.getState().loading;
148
+ if (pending) load(pending);
149
+ ctx.watch(() => ctx.getState().loading, (code) => {
150
+ if (code) load(code);
151
+ });
152
+ };
153
+ }
154
+ //#endregion
155
+ //#region src/reducer.ts
156
+ /**
157
+ * Pure and serializable — locale packs are data, so they live HERE, not in a
158
+ * side-table. One source of truth: `t()` is a pure function of this state and
159
+ * reactivity rides the kernel's one change stream (no emitters).
160
+ */
161
+ function initialI18nState(config) {
162
+ const fallbackLocale = config.fallbackLocale ?? "en";
163
+ const locales = {};
164
+ for (const locale of config.locales ?? []) locales[locale.code] = locale;
165
+ const locale = config.locale ?? fallbackLocale;
166
+ return {
167
+ locale,
168
+ fallbackLocale,
169
+ locales,
170
+ loading: !locales[locale] && config.loaders?.[locale] !== void 0 ? locale : null
171
+ };
172
+ }
173
+ function i18nReducer(state, action) {
174
+ switch (action.type) {
175
+ case "I18N/SET_LOCALE":
176
+ if (!state.locales[action.locale]) return state;
177
+ if (state.locale === action.locale && state.loading === null) return state;
178
+ return {
179
+ ...state,
180
+ locale: action.locale,
181
+ loading: null
182
+ };
183
+ case "I18N/REGISTER_LOCALE": return {
184
+ ...state,
185
+ locales: {
186
+ ...state.locales,
187
+ [action.locale.code]: action.locale
188
+ }
189
+ };
190
+ case "I18N/LOAD_STARTED": return state.loading === action.locale ? state : {
191
+ ...state,
192
+ loading: action.locale
193
+ };
194
+ case "I18N/LOAD_FAILED": return state.loading === action.locale ? {
195
+ ...state,
196
+ loading: null
197
+ } : state;
198
+ default: return state;
199
+ }
200
+ }
201
+ //#endregion
202
+ //#region src/types.ts
203
+ const I18nToken = (0, _embedpdf_core.createCapabilityToken)("i18n");
204
+ //#endregion
205
+ //#region src/i18n.plugin.ts
206
+ /**
207
+ * The i18n plugin: workspace-scoped (locale is a workspace concern) with NO
208
+ * dependencies — engine-free, DOM-free. Its capability is built synchronously
209
+ * in `createKernel()`, so the shell translates from the first frame, while
210
+ * the engine is still booting.
211
+ */
212
+ const i18nPlugin = (config = {}) => (0, _embedpdf_core.definePlugin)({
213
+ id: "i18n",
214
+ scope: "workspace",
215
+ token: I18nToken,
216
+ initialState: () => initialI18nState(config),
217
+ reduce: i18nReducer,
218
+ capability: (ctx) => createI18nCapability(ctx, config),
219
+ effects: registerI18nEffects(config)
220
+ });
221
+ //#endregion
222
+ //#region src/negotiate.ts
223
+ /**
224
+ * Pure BCP-47 locale negotiation — strings in, string out. The plugin never
225
+ * reads the platform; the EMBEDDER feeds it whatever request list its
226
+ * environment offers:
227
+ *
228
+ * ```ts
229
+ * // browser shell: negotiateLocale(['en', 'es', 'ar'], navigator.languages)
230
+ * // server render: negotiateLocale(codes, parseAcceptLanguage(header))
231
+ * ```
232
+ *
233
+ * Matching, per requested code in preference order:
234
+ * 1. exact match (case-insensitive): 'es-MX' → 'es-MX'
235
+ * 2. request narrowed to its language: 'en-GB' → 'en'
236
+ * 3. any available dialect of the language: 'zh' → 'zh-Hans'
237
+ *
238
+ * Returns the matched code exactly as it appears in `available`, or null.
239
+ */
240
+ function negotiateLocale(available, requested) {
241
+ const byCanon = /* @__PURE__ */ new Map();
242
+ for (const code of available) {
243
+ const canon = code.toLowerCase();
244
+ if (!byCanon.has(canon)) byCanon.set(canon, code);
245
+ }
246
+ const languageOf = (code) => code.toLowerCase().split("-")[0];
247
+ for (const want of requested) {
248
+ const exact = byCanon.get(want.toLowerCase());
249
+ if (exact !== void 0) return exact;
250
+ }
251
+ for (const want of requested) {
252
+ const narrowed = byCanon.get(languageOf(want));
253
+ if (narrowed !== void 0) return narrowed;
254
+ }
255
+ for (const want of requested) {
256
+ const language = languageOf(want);
257
+ for (const [canon, original] of byCanon) if (languageOf(canon) === language) return original;
258
+ }
259
+ return null;
260
+ }
261
+ //#endregion
262
+ exports.I18nToken = I18nToken;
263
+ exports.i18nPlugin = i18nPlugin;
264
+ exports.interpolate = interpolate;
265
+ exports.negotiateLocale = negotiateLocale;
266
+ exports.translate = translate;
267
+
268
+ //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/lib/locales/en.ts","../src/lib/locales/es.ts","../src/lib/manifest.ts","../src/lib/actions.ts","../src/lib/i18n-plugin.ts","../src/lib/reducer.ts","../src/lib/index.ts"],"sourcesContent":["import { Locale } from '../types';\n\nexport const enUS: Locale = {\n code: 'en',\n name: 'English',\n translations: {\n commands: {\n zoom: {\n in: 'Zoom In',\n out: 'Zoom Out',\n fitWidth: 'Fit to Width',\n fitPage: 'Fit to Page',\n automatic: 'Automatic',\n level: 'Zoom Level ({level}%)',\n inArea: 'Zoom In Area',\n },\n fullscreen: {\n enter: 'Enter Full Screen',\n exit: 'Exit Full Screen',\n },\n rotate: {\n clockwise: 'Rotate Clockwise',\n counterclockwise: 'Rotate Counter-Clockwise',\n },\n menu: 'Menu',\n sidebar: 'Sidebar',\n search: 'Search',\n comment: 'Comment',\n download: 'Download',\n print: 'Print',\n openFile: 'Open PDF',\n save: 'Save',\n settings: 'Settings',\n view: 'View',\n annotate: 'Annotate',\n shapes: 'Shapes',\n redact: 'Redact',\n fillAndSign: 'Fill and Sign',\n form: 'Form',\n pan: 'Pan',\n pointer: 'Pointer',\n undo: 'Undo',\n redo: 'Redo',\n copy: 'Copy',\n screenshot: 'Screenshot',\n nextPage: 'Next Page',\n previousPage: 'Previous Page',\n },\n },\n};\n","import { Locale } from '../types';\n\nexport const esES: Locale = {\n code: 'es',\n name: 'Español',\n translations: {\n commands: {\n zoom: {\n in: 'Acercar',\n out: 'Alejar',\n fitWidth: 'Ajustar al ancho',\n fitPage: 'Ajustar a la página',\n automatic: 'Automático',\n level: 'Nivel de zoom ({level}%)',\n inArea: 'Acercar área',\n },\n fullscreen: {\n enter: 'Pantalla completa',\n exit: 'Salir de pantalla completa',\n },\n rotate: {\n clockwise: 'Girar a la derecha',\n counterclockwise: 'Girar a la izquierda',\n },\n menu: 'Menú',\n sidebar: 'Barra lateral',\n search: 'Buscar',\n comment: 'Comentario',\n download: 'Descargar',\n print: 'Imprimir',\n openFile: 'Abrir PDF',\n save: 'Guardar',\n settings: 'Configuración',\n view: 'Ver',\n annotate: 'Anotar',\n shapes: 'Formas',\n redact: 'Redactar',\n fillAndSign: 'Rellenar y firmar',\n form: 'Formulario',\n pan: 'Desplazar',\n pointer: 'Puntero',\n undo: 'Deshacer',\n redo: 'Rehacer',\n copy: 'Copiar',\n screenshot: 'Captura de pantalla',\n nextPage: 'Página siguiente',\n previousPage: 'Página anterior',\n },\n },\n};\n","import { PluginManifest } from '@embedpdf/core';\nimport { I18nPluginConfig } from './types';\nimport { enUS, esES } from './locales';\n\nexport const I18N_PLUGIN_ID = 'i18n';\n\nexport const manifest: PluginManifest<I18nPluginConfig> = {\n id: I18N_PLUGIN_ID,\n name: 'I18n Plugin',\n version: '1.0.0',\n provides: ['i18n'],\n requires: [],\n optional: [],\n defaultConfig: {\n defaultLocale: 'en',\n locales: [enUS, esES],\n },\n};\n","import { Action } from '@embedpdf/core';\nimport { Locale, LocaleCode } from './types';\n\nexport const SET_LOCALE = 'I18N/SET_LOCALE';\nexport const REGISTER_LOCALE = 'I18N/REGISTER_LOCALE';\n\nexport interface SetLocaleAction extends Action {\n type: typeof SET_LOCALE;\n payload: LocaleCode;\n}\n\nexport interface RegisterLocaleAction extends Action {\n type: typeof REGISTER_LOCALE;\n payload: LocaleCode;\n}\n\nexport type I18nAction = SetLocaleAction | RegisterLocaleAction;\n\nexport const setLocale = (locale: LocaleCode): SetLocaleAction => ({\n type: SET_LOCALE,\n payload: locale,\n});\n\nexport const registerLocale = (locale: LocaleCode): RegisterLocaleAction => ({\n type: REGISTER_LOCALE,\n payload: locale,\n});\n","import {\n BasePlugin,\n PluginRegistry,\n StoreState,\n arePropsEqual,\n createEmitter,\n createScopedEmitter,\n} from '@embedpdf/core';\nimport {\n I18nCapability,\n I18nPluginConfig,\n I18nState,\n I18nScope,\n Locale,\n LocaleCode,\n LocaleChangeEvent,\n TranslationKey,\n TranslateOptions,\n ParamResolver,\n TranslationParamsChangedData,\n TranslationParamsChangedEvent,\n} from './types';\nimport {\n I18nAction,\n setLocale as setLocaleAction,\n registerLocale as registerLocaleAction,\n} from './actions';\n\nexport class I18nPlugin extends BasePlugin<\n I18nPluginConfig,\n I18nCapability,\n I18nState,\n I18nAction\n> {\n static readonly id = 'i18n' as const;\n\n private config: I18nPluginConfig;\n private locales = new Map<LocaleCode, Locale>();\n private paramResolvers = new Map<TranslationKey, ParamResolver>();\n\n // Cache resolved params per document per key\n // Map<documentId, Map<translationKey, resolvedParams>>\n private paramsCache = new Map<string, Map<TranslationKey, Record<string, string | number>>>();\n\n // Events\n private readonly localeChange$ = createEmitter<LocaleChangeEvent>();\n private readonly paramsChanged$ = createScopedEmitter<\n TranslationParamsChangedData,\n TranslationParamsChangedEvent,\n string\n >((documentId, data) => ({ documentId, ...data }), { cache: false });\n\n constructor(id: string, registry: PluginRegistry, config: I18nPluginConfig) {\n super(id, registry);\n\n this.config = config;\n\n // Register all provided locales\n config.locales.forEach((locale) => {\n this.locales.set(locale.code, locale);\n this.dispatch(registerLocaleAction(locale.code));\n });\n\n // Register param resolvers\n if (config.paramResolvers) {\n Object.entries(config.paramResolvers).forEach(([key, resolver]) => {\n this.paramResolvers.set(key, resolver);\n });\n }\n\n // Set initial locale\n this.dispatch(setLocaleAction(config.defaultLocale));\n\n // Subscribe to global store changes for param change detection\n this.registry.getStore().subscribe((_action, newState) => {\n this.detectParamChanges(newState);\n });\n }\n\n async initialize(): Promise<void> {\n this.logger.info('I18nPlugin', 'Initialize', 'I18n plugin initialized');\n }\n\n async destroy(): Promise<void> {\n this.localeChange$.clear();\n this.paramsChanged$.clear();\n this.paramResolvers.clear();\n this.paramsCache.clear();\n super.destroy();\n }\n\n protected override onDocumentClosed(documentId: string): void {\n // Clean up cache for closed document\n this.paramsCache.delete(documentId);\n this.paramsChanged$.clearScope(documentId);\n\n this.logger.debug(\n 'I18nPlugin',\n 'DocumentClosed',\n `Cleaned up params cache for document: ${documentId}`,\n );\n }\n\n protected buildCapability(): I18nCapability {\n return {\n t: (key, options) => this.translate(key, options),\n forDocument: (documentId) => this.createI18nScope(documentId),\n registerParamResolver: (key, resolver) => this.registerParamResolver(key, resolver),\n unregisterParamResolver: (key) => this.unregisterParamResolver(key),\n setLocale: (locale) => this.setLocale(locale),\n getLocale: () => this.state.currentLocale,\n getAvailableLocales: () => [...this.state.availableLocales],\n getLocaleInfo: (code) => this.locales.get(code) ?? null,\n registerLocale: (locale) => this.registerLocale(locale),\n hasLocale: (code) => this.locales.has(code),\n onLocaleChange: this.localeChange$.on,\n onParamsChanged: this.paramsChanged$.onGlobal,\n };\n }\n\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n\n private createI18nScope(documentId: string): I18nScope {\n return {\n t: (key, options) => this.translate(key, { documentId, ...options }),\n onParamsChanged: this.paramsChanged$.forScope(documentId),\n };\n }\n\n // ─────────────────────────────────────────────────────────\n // Translation Logic\n // ─────────────────────────────────────────────────────────\n\n private translate(key: TranslationKey, options?: TranslateOptions): string {\n const locale = this.locales.get(this.state.currentLocale);\n const fallbackLocale = this.config.fallbackLocale\n ? this.locales.get(this.config.fallbackLocale)\n : null;\n\n // Try current locale\n let value = this.getNestedValue(locale?.translations, key);\n\n // Try fallback locale\n if (!value && fallbackLocale) {\n value = this.getNestedValue(fallbackLocale.translations, key);\n }\n\n // If still not found, use fallback or return key\n if (!value) {\n if (options?.fallback) {\n // Use provided fallback string\n value = options.fallback;\n } else {\n this.logger.warn(\n 'I18nPlugin',\n 'MissingTranslation',\n `Translation not found for key: ${key}`,\n );\n return key;\n }\n }\n\n // Resolve params: explicit params take precedence over registered resolvers\n let params = options?.params;\n\n // If no explicit params and we have a resolver, try to resolve\n if (!params && this.paramResolvers.has(key)) {\n params = this.resolveParams(key, options?.documentId);\n }\n\n // Interpolate parameters (works for both found translations and fallback)\n return this.interpolate(value, params);\n }\n\n private resolveParams(\n key: TranslationKey,\n documentId?: string,\n ): Record<string, string | number> | undefined {\n const resolver = this.paramResolvers.get(key);\n if (!resolver) return undefined;\n\n const state = this.registry.getStore().getState();\n\n try {\n // Pass documentId (which may be undefined) to resolver\n return resolver({ state, documentId });\n } catch (error) {\n this.logger.error(\n 'I18nPlugin',\n 'ParamResolverError',\n `Error resolving params for key \"${key}\":`,\n error,\n );\n return undefined;\n }\n }\n\n private getNestedValue(obj: any, path: string): string | undefined {\n if (!obj) return undefined;\n\n const parts = path.split('.');\n let current = obj;\n\n for (const part of parts) {\n if (current === undefined || current === null) return undefined;\n current = current[part];\n }\n\n return typeof current === 'string' ? current : undefined;\n }\n\n private interpolate(str: string, params?: Record<string, string | number>): string {\n if (!params) return str;\n\n // Replace {key} with params[key]\n return str.replace(/\\{(\\w+)\\}/g, (match, key) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n }\n\n // ─────────────────────────────────────────────────────────\n // Smart Param Change Detection\n // ─────────────────────────────────────────────────────────\n\n private detectParamChanges(newState: StoreState<any>): void {\n // Get all documents from core state\n const documentIds = Object.keys(newState.core.documents);\n\n documentIds.forEach((documentId) => {\n this.detectDocumentParamChanges(documentId, newState);\n });\n }\n\n private detectDocumentParamChanges(documentId: string, newState: StoreState<any>): void {\n const previousCache = this.paramsCache.get(documentId);\n const changedKeys: TranslationKey[] = [];\n\n // Re-resolve all params that have resolvers\n this.paramResolvers.forEach((resolver, key) => {\n try {\n const newParams = resolver({ state: newState, documentId });\n const prevParams = previousCache?.get(key);\n\n // Compare params (deep equality for simplicity)\n if (!arePropsEqual(prevParams, newParams)) {\n changedKeys.push(key);\n\n // Update cache\n if (!this.paramsCache.has(documentId)) {\n this.paramsCache.set(documentId, new Map());\n }\n this.paramsCache.get(documentId)!.set(key, newParams);\n }\n } catch (error) {\n this.logger.error(\n 'I18nPlugin',\n 'ParamDetectionError',\n `Error detecting param changes for key \"${key}\":`,\n error,\n );\n }\n });\n\n // Emit event if any params changed\n if (changedKeys.length > 0) {\n this.paramsChanged$.emit(documentId, { changedKeys });\n\n this.logger.debug(\n 'I18nPlugin',\n 'ParamsChanged',\n `Translation params changed for document ${documentId}:`,\n changedKeys,\n );\n }\n }\n\n // ─────────────────────────────────────────────────────────\n // Param Resolver Management\n // ─────────────────────────────────────────────────────────\n\n private registerParamResolver(key: TranslationKey, resolver: ParamResolver): void {\n if (this.paramResolvers.has(key)) {\n this.logger.warn(\n 'I18nPlugin',\n 'ResolverOverwrite',\n `Param resolver for \"${key}\" already exists and will be overwritten`,\n );\n }\n\n this.paramResolvers.set(key, resolver);\n\n // Clear cache for this key in all documents\n this.paramsCache.forEach((docCache) => {\n docCache.delete(key);\n });\n\n this.logger.debug('I18nPlugin', 'ResolverRegistered', `Param resolver registered for: ${key}`);\n }\n\n private unregisterParamResolver(key: TranslationKey): void {\n if (this.paramResolvers.delete(key)) {\n // Clear cache for this key in all documents\n this.paramsCache.forEach((docCache) => {\n docCache.delete(key);\n });\n\n this.logger.debug(\n 'I18nPlugin',\n 'ResolverUnregistered',\n `Param resolver unregistered for: ${key}`,\n );\n }\n }\n\n // ─────────────────────────────────────────────────────────\n // Locale Management\n // ─────────────────────────────────────────────────────────\n\n private setLocale(locale: LocaleCode): void {\n if (!this.locales.has(locale)) {\n this.logger.warn('I18nPlugin', 'LocaleNotFound', `Locale '${locale}' is not registered`);\n return;\n }\n\n const previousLocale = this.state.currentLocale;\n if (previousLocale === locale) return;\n\n this.dispatch(setLocaleAction(locale));\n\n this.localeChange$.emit({\n previousLocale,\n currentLocale: locale,\n });\n\n this.logger.info('I18nPlugin', 'LocaleChanged', `Locale changed to: ${locale}`);\n }\n\n private registerLocale(locale: Locale): void {\n if (this.locales.has(locale.code)) {\n this.logger.warn(\n 'I18nPlugin',\n 'LocaleAlreadyRegistered',\n `Locale '${locale.code}' is already registered`,\n );\n return;\n }\n\n this.locales.set(locale.code, locale);\n this.dispatch(registerLocaleAction(locale.code));\n\n this.logger.info('I18nPlugin', 'LocaleRegistered', `Locale registered: ${locale.code}`);\n }\n}\n","import { Reducer } from '@embedpdf/core';\nimport { I18nState } from './types';\nimport { I18nAction, SET_LOCALE, REGISTER_LOCALE } from './actions';\n\nexport const initialState: I18nState = {\n currentLocale: 'en',\n availableLocales: [],\n};\n\nexport const i18nReducer: Reducer<I18nState, I18nAction> = (state = initialState, action) => {\n switch (action.type) {\n case SET_LOCALE: {\n const locale = action.payload;\n if (!state.availableLocales.includes(locale)) {\n console.warn(`I18nPlugin: Locale '${locale}' not available`);\n return state;\n }\n return {\n ...state,\n currentLocale: locale,\n };\n }\n\n case REGISTER_LOCALE: {\n const locale = action.payload;\n if (state.availableLocales.includes(locale)) {\n return state; // Already registered\n }\n return {\n ...state,\n availableLocales: [...state.availableLocales, locale],\n };\n }\n\n default:\n return state;\n }\n};\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, I18N_PLUGIN_ID } from './manifest';\nimport { I18nPluginConfig, I18nState } from './types';\nimport { I18nPlugin } from './i18n-plugin';\nimport { I18nAction } from './actions';\nimport { i18nReducer, initialState } from './reducer';\n\nexport const I18nPluginPackage: PluginPackage<I18nPlugin, I18nPluginConfig, I18nState, I18nAction> =\n {\n manifest,\n create: (registry, config) => new I18nPlugin(I18N_PLUGIN_ID, registry, config),\n reducer: i18nReducer,\n initialState,\n };\n\nexport * from './i18n-plugin';\nexport * from './types';\nexport * from './manifest';\nexport * from './locales';\n"],"names":["enUS","code","name","translations","commands","zoom","in","out","fitWidth","fitPage","automatic","level","inArea","fullscreen","enter","exit","rotate","clockwise","counterclockwise","menu","sidebar","search","comment","download","print","openFile","save","settings","view","annotate","shapes","redact","fillAndSign","form","pan","pointer","undo","redo","copy","screenshot","nextPage","previousPage","esES","I18N_PLUGIN_ID","manifest","id","version","provides","requires","optional","defaultConfig","defaultLocale","locales","SET_LOCALE","REGISTER_LOCALE","setLocale","locale","type","payload","registerLocale","_I18nPlugin","BasePlugin","constructor","registry","config","super","this","Map","paramResolvers","paramsCache","localeChange$","createEmitter","paramsChanged$","createScopedEmitter","documentId","data","cache","forEach","set","dispatch","registerLocaleAction","Object","entries","key","resolver","setLocaleAction","getStore","subscribe","_action","newState","detectParamChanges","initialize","logger","info","destroy","clear","onDocumentClosed","delete","clearScope","debug","buildCapability","t","options","translate","forDocument","createI18nScope","registerParamResolver","unregisterParamResolver","getLocale","state","currentLocale","getAvailableLocales","availableLocales","getLocaleInfo","get","hasLocale","has","onLocaleChange","on","onParamsChanged","onGlobal","forScope","fallbackLocale","value","getNestedValue","fallback","warn","params","resolveParams","interpolate","getState","error","obj","path","parts","split","current","part","str","replace","match","String","keys","core","documents","detectDocumentParamChanges","previousCache","changedKeys","newParams","prevParams","arePropsEqual","push","length","emit","docCache","previousLocale","I18nPlugin","initialState","I18nPluginPackage","create","reducer","action","includes","console"],"mappings":"kHAEaA,EAAe,CAC1BC,KAAM,KACNC,KAAM,UACNC,aAAc,CACZC,SAAU,CACRC,KAAM,CACJC,GAAI,UACJC,IAAK,WACLC,SAAU,eACVC,QAAS,cACTC,UAAW,YACXC,MAAO,wBACPC,OAAQ,gBAEVC,WAAY,CACVC,MAAO,oBACPC,KAAM,oBAERC,OAAQ,CACNC,UAAW,mBACXC,iBAAkB,4BAEpBC,KAAM,OACNC,QAAS,UACTC,OAAQ,SACRC,QAAS,UACTC,SAAU,WACVC,MAAO,QACPC,SAAU,WACVC,KAAM,OACNC,SAAU,WACVC,KAAM,OACNC,SAAU,WACVC,OAAQ,SACRC,OAAQ,SACRC,YAAa,gBACbC,KAAM,OACNC,IAAK,MACLC,QAAS,UACTC,KAAM,OACNC,KAAM,OACNC,KAAM,OACNC,WAAY,aACZC,SAAU,YACVC,aAAc,mBC5CPC,EAAe,CAC1BzC,KAAM,KACNC,KAAM,UACNC,aAAc,CACZC,SAAU,CACRC,KAAM,CACJC,GAAI,UACJC,IAAK,SACLC,SAAU,mBACVC,QAAS,sBACTC,UAAW,aACXC,MAAO,2BACPC,OAAQ,gBAEVC,WAAY,CACVC,MAAO,oBACPC,KAAM,8BAERC,OAAQ,CACNC,UAAW,qBACXC,i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AQgE,IAAI5D,GAEpB,YADAU,KAAK0B,OAAOkC,KAAK,aAAc,iBAAkB,WAAWtE,wBAI9D,MAAMmG,EAAiBzF,KAAK2C,MAAMC,cAC9B6C,IAAmBnG,IAEvBU,KAAKa,SAASM,EAAgB7B,IAE9BU,KAAKI,cAAcmF,KAAK,CACtBE,iBACA7C,cAAetD,IAGjBU,KAAK0B,OAAOC,KAAK,aAAc,gBAAiB,sBAAsBrC,KACxE,CAEQ,cAAAG,CAAeH,GACjBU,KAAKd,QAAQgE,IAAI5D,EAAOvD,MAC1BiE,KAAK0B,OAAOkC,KACV,aACA,0BACA,WAAWtE,EAAOvD,gCAKtBiE,KAAKd,QAAQ0B,IAAItB,EAAOvD,KAAMuD,GAC9BU,KAAKa,SAASC,EAAqBxB,EAAOvD,OAE1CiE,KAAK0B,OAAOC,KAAK,aAAc,mBAAoB,sBAAsBrC,EAAOvD,QAClF,GAhUA2D,EAAgBf,GAAK,OANhB,IAAM+G,EAANhG,ECxBA,MAAMiG,EAA0B,CACrC/C,cAAe,KACfE,iBAAkB,ICCP8C,EACX,CACElH,WACAmH,OAAQ,CAAChG,EAAUC,IAAW,IAAI4F,EAAWjH,EAAgBoB,EAAUC,GACvEgG,QDFuD,CAACnD,EAAQgD,EAAcI,KAChF,OAAQA,EAAOxG,MACb,KAAKJ,EAAY,CACf,MAAMG,EAASyG,EAAOvG,QACtB,OAAKmD,EAAMG,iBAAiBkD,SAAS1G,GAI9B,IACFqD,EACHC,cAAetD,IALf2G,QAAQrC,KAAK,uBAAuBtE,oBAC7BqD,EAMX,CAEA,KAAKvD,EAAiB,CACpB,MAAME,EAASyG,EAAOvG,QACtB,OAAImD,EAAMG,iBAAiBkD,SAAS1G,GAC3BqD,EAEF,IACFA,EACHG,iBAAkB,IAAIH,EAAMG,iBAAkBxD,GAElD,CAEA,QACE,OAAOqD,ICvBTgD"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/translate.ts","../src/capability.ts","../src/effects.ts","../src/reducer.ts","../src/types.ts","../src/i18n.plugin.ts","../src/negotiate.ts"],"sourcesContent":["import type { I18nState, TranslateOptions, TranslationDictionary } from './types';\n\n/**\n * The pure lookup core — state in, string out. No platform access anywhere\n * (`Intl.PluralRules` is core ECMAScript, not DOM); this is the part that\n * ports to Rust verbatim.\n */\n\n/** Walk a dotted path ('commands.zoom.in') through a dictionary tree. */\nfunction lookup(\n dict: TranslationDictionary | undefined,\n key: string,\n): string | TranslationDictionary | undefined {\n if (!dict) return undefined;\n let node: string | TranslationDictionary | undefined = dict;\n for (const part of key.split('.')) {\n if (node === undefined || typeof node === 'string') return undefined;\n node = node[part];\n }\n return node;\n}\n\n/** CLDR plural category for a count, with a safe fallback when the runtime\n * lacks ICU data for the locale. */\nfunction pluralCategory(locale: string, count: number): string {\n try {\n return new Intl.PluralRules(locale).select(count);\n } catch {\n return count === 1 ? 'one' : 'other';\n }\n}\n\n/** A leaf hit is a string; a branch object needs a plural pick via `count`. */\nfunction resolveNode(\n node: string | TranslationDictionary | undefined,\n locale: string,\n params?: Record<string, string | number>,\n): string | undefined {\n if (typeof node === 'string') return node;\n if (node !== undefined && typeof params?.count === 'number') {\n const branch = node[pluralCategory(locale, params.count)] ?? node['other'];\n if (typeof branch === 'string') return branch;\n }\n return undefined;\n}\n\n/** Replace `{slot}` markers; unknown slots stay verbatim (visible in QA). */\nexport function interpolate(text: string, params?: Record<string, string | number>): string {\n if (!params) return text;\n return text.replace(/\\{(\\w+)\\}/g, (match, slot) =>\n params[slot] !== undefined ? String(params[slot]) : match,\n );\n}\n\nexport interface TranslateResult {\n readonly text: string;\n /** False when the key missed every pack (text is then the fallback or the key). */\n readonly found: boolean;\n}\n\n/**\n * Resolve a key against the state: current locale → fallback locale →\n * `options.fallback` (interpolated too) → the key itself.\n */\nexport function translate(\n state: I18nState,\n key: string,\n options?: TranslateOptions,\n): TranslateResult {\n const { locale, fallbackLocale, locales } = state;\n const text =\n resolveNode(lookup(locales[locale]?.translations, key), locale, options?.params) ??\n resolveNode(\n lookup(locales[fallbackLocale]?.translations, key),\n fallbackLocale,\n options?.params,\n );\n if (text !== undefined) return { text: interpolate(text, options?.params), found: true };\n if (options?.fallback !== undefined)\n return { text: interpolate(options.fallback, options.params), found: false };\n return { text: key, found: false };\n}\n","import type { PluginContext } from '@embedpdf/core';\nimport { translate } from './translate';\nimport type { I18nAction, I18nCapability, I18nConfig, I18nState, LocaleInfo } from './types';\n\n/**\n * The i18n capability — selectors (pure reads over state) + intents (the only\n * writers). Built synchronously in `createKernel()`, so `t()` works before the\n * engine exists — including inside the viewer shell's loading UI.\n */\nexport function createI18nCapability(\n ctx: PluginContext<I18nState, I18nAction>,\n config: I18nConfig,\n): I18nCapability {\n // Dev signal, once per offender — a missing key otherwise fails silently\n // (by design: `t()` always returns a usable string).\n const warned = new Set<string>();\n const warnOnce = (id: string, message: string) => {\n if (warned.has(id)) return;\n warned.add(id);\n console.warn(message);\n };\n\n return {\n t: (key, options) => {\n const result = translate(ctx.getState(), key, options);\n if (!result.found && options?.fallback === undefined) {\n warnOnce(\n `key:${key}`,\n `[i18n] missing translation \"${key}\" (locale: ${ctx.getState().locale})`,\n );\n }\n return result.text;\n },\n locale: () => ctx.getState().locale,\n dir: () => {\n const { locales, locale } = ctx.getState();\n return locales[locale]?.dir ?? 'ltr';\n },\n locales: () => {\n const { locales } = ctx.getState();\n const known: LocaleInfo[] = Object.values(locales).map((locale) => ({\n code: locale.code,\n name: locale.name,\n dir: locale.dir ?? 'ltr',\n loaded: true,\n }));\n for (const code of Object.keys(config.loaders ?? {})) {\n if (!locales[code]) known.push({ code, name: code, dir: 'ltr', loaded: false });\n }\n return known;\n },\n loading: () => ctx.getState().loading,\n setLocale: (code) => {\n const state = ctx.getState();\n if (state.locales[code]) {\n ctx.dispatch({ type: 'I18N/SET_LOCALE', locale: code });\n } else if (config.loaders?.[code]) {\n ctx.dispatch({ type: 'I18N/LOAD_STARTED', locale: code });\n } else {\n warnOnce(\n `locale:${code}`,\n `[i18n] unknown locale \"${code}\" — not registered and no loader configured`,\n );\n }\n },\n registerLocale: (locale) => ctx.dispatch({ type: 'I18N/REGISTER_LOCALE', locale }),\n };\n}\n","import type { EffectContext } from '@embedpdf/core';\nimport type { I18nAction, I18nConfig, I18nState } from './types';\n\n/**\n * The plugin's ONE side-effect: fetching lazy locale packs. State-driven — a\n * load is `state.loading`, set by the capability (a switch to a lazy pack) or\n * by the initial state (a lazy startup locale), so a load requested before\n * effects ran is picked up here and nothing is lost to boot ordering.\n */\nexport function registerI18nEffects(config: I18nConfig) {\n return (ctx: EffectContext<I18nState, I18nAction>): void => {\n const load = (code: string) => {\n const loader = config.loaders?.[code];\n if (!loader) return; // unreachable via the capability; guards bad dispatches\n loader().then(\n (locale) => {\n ctx.dispatch({ type: 'I18N/REGISTER_LOCALE', locale });\n // Complete the switch only if this load is still the wanted one —\n // the user may have switched again while the pack was in flight.\n if (ctx.getState().loading === code) {\n ctx.dispatch({ type: 'I18N/SET_LOCALE', locale: locale.code });\n }\n },\n () => ctx.dispatch({ type: 'I18N/LOAD_FAILED', locale: code }),\n );\n };\n\n const pending = ctx.getState().loading;\n if (pending) load(pending);\n ctx.watch(\n () => ctx.getState().loading,\n (code) => {\n if (code) load(code);\n },\n );\n };\n}\n","import type { I18nAction, I18nConfig, I18nState, Locale } from './types';\n\n/**\n * Pure and serializable — locale packs are data, so they live HERE, not in a\n * side-table. One source of truth: `t()` is a pure function of this state and\n * reactivity rides the kernel's one change stream (no emitters).\n */\n\nexport function initialI18nState(config: I18nConfig): I18nState {\n const fallbackLocale = config.fallbackLocale ?? 'en';\n const locales: Record<string, Locale> = {};\n for (const locale of config.locales ?? []) locales[locale.code] = locale;\n const locale = config.locale ?? fallbackLocale;\n // A startup locale that is a lazy pack: show the fallback chain until the\n // pack arrives — seeding `loading` makes effects fetch it at startup.\n const needsLoad = !locales[locale] && config.loaders?.[locale] !== undefined;\n return { locale, fallbackLocale, locales, loading: needsLoad ? locale : null };\n}\n\nexport function i18nReducer(state: I18nState, action: I18nAction): I18nState {\n switch (action.type) {\n case 'I18N/SET_LOCALE': {\n // Only registered packs can become current — lazy ones arrive via\n // LOAD_STARTED → REGISTER_LOCALE → SET_LOCALE (effects drive the middle).\n if (!state.locales[action.locale]) return state;\n if (state.locale === action.locale && state.loading === null) return state;\n return { ...state, locale: action.locale, loading: null };\n }\n case 'I18N/REGISTER_LOCALE':\n return { ...state, locales: { ...state.locales, [action.locale.code]: action.locale } };\n case 'I18N/LOAD_STARTED':\n return state.loading === action.locale ? state : { ...state, loading: action.locale };\n case 'I18N/LOAD_FAILED':\n return state.loading === action.locale ? { ...state, loading: null } : state;\n default:\n return state;\n }\n}\n","import { createCapabilityToken } from '@embedpdf/core';\n\n/**\n * @embedpdf/plugin-i18n — the contract.\n *\n * Translation is pure data over pure state: locale packs live IN the store\n * (not in a side-table), so `t()` is a pure read, every consumer is reactive\n * through the one kernel change stream, and the whole thing serializes (SSR,\n * snapshots, persist). Workspace-scoped, `requires: []`, never touches the\n * engine or the DOM — the capability is alive from `createKernel()`, before\n * a single WASM byte is fetched. The plugin ships NO strings: mechanism here,\n * content (locale packs) in the product that embeds it.\n */\n\n/** Nested tree of translation strings. Leaves interpolate `{param}` slots. */\nexport interface TranslationDictionary {\n readonly [key: string]: string | TranslationDictionary;\n}\n\nexport interface Locale {\n /** BCP-47 code: 'en', 'es', 'ar', 'zh-Hans'. */\n readonly code: string;\n /** Native display name: 'Español' — what a locale switcher shows. */\n readonly name: string;\n /** Text direction for viewer chrome. Defaults to 'ltr'. */\n readonly dir?: 'ltr' | 'rtl';\n readonly translations: TranslationDictionary;\n}\n\nexport interface I18nState {\n readonly locale: string;\n readonly fallbackLocale: string;\n /** Registered packs by code — the lookup table `t()` reads. */\n readonly locales: Readonly<Record<string, Locale>>;\n /** Code of a lazy pack currently being fetched (drives switcher spinners). */\n readonly loading: string | null;\n}\n\nexport type I18nAction =\n /** Switch to a REGISTERED locale. The reducer ignores unregistered codes —\n * loading a lazy pack goes through LOAD_STARTED (the capability routes). */\n | { type: 'I18N/SET_LOCALE'; locale: string }\n | { type: 'I18N/REGISTER_LOCALE'; locale: Locale }\n | { type: 'I18N/LOAD_STARTED'; locale: string }\n | { type: 'I18N/LOAD_FAILED'; locale: string };\n\nexport interface I18nConfig {\n /**\n * Startup locale. Compute platform inputs OUTSIDE the plugin — it never\n * touches the DOM:\n *\n * ```ts\n * i18nPlugin({ locale: negotiateLocale(codes, navigator.languages) ?? 'en' })\n * ```\n *\n * May name a `loaders` pack: the fallback locale shows until the pack\n * arrives (effects fetch it at startup). Defaults to `fallbackLocale`.\n */\n locale?: string;\n /** The pack tried when a key misses the current locale. Default 'en'. */\n fallbackLocale?: string;\n /** Eagerly available packs. */\n locales?: Locale[];\n /**\n * Lazy packs: code → loader. `setLocale(code)` fetches on demand (in\n * effects), registers the pack, then switches. Until a lazy pack loads, a\n * locale switcher shows its code as the name — register eagerly (packs are\n * small) when you want native names in the switcher up front.\n */\n loaders?: Record<string, () => Promise<Locale>>;\n}\n\nexport interface TranslateOptions {\n /**\n * `{slot}` interpolation values. When `count` is a number and the key\n * resolves to a branch object, the branch is picked by CLDR plural\n * category (`Intl.PluralRules`), falling back to `other`:\n *\n * ```ts\n * // pages: { one: '{count} page', other: '{count} pages' }\n * t('pages', { params: { count: 1 } }) // '1 page'\n * ```\n */\n params?: Record<string, string | number>;\n /** Returned (interpolated) when the key misses every pack — instead of the key. */\n fallback?: string;\n}\n\n/** A locale as a switcher sees it — registered packs plus not-yet-loaded lazy ones. */\nexport interface LocaleInfo {\n readonly code: string;\n /** Native name; the bare code until a lazy pack has loaded. */\n readonly name: string;\n readonly dir: 'ltr' | 'rtl';\n readonly loaded: boolean;\n}\n\nexport interface I18nCapability {\n /** Translate a key: current locale → fallback locale → `options.fallback` → the key. */\n t(key: string, options?: TranslateOptions): string;\n locale(): string;\n /** Text direction of the CURRENT locale — wire to `dir=` on the shell. */\n dir(): 'ltr' | 'rtl';\n /** Every known locale (registered + lazy), in registration order. */\n locales(): LocaleInfo[];\n /** Code of the lazy pack being fetched right now, if any. */\n loading(): string | null;\n /** Switch locale; fetches the pack first when it's a lazy one. */\n setLocale(code: string): void;\n /** Register a pack at runtime (customer-supplied translations). */\n registerLocale(locale: Locale): void;\n}\n\nexport const I18nToken = createCapabilityToken<I18nCapability>('i18n');\n","import { definePlugin } from '@embedpdf/core';\nimport { createI18nCapability } from './capability';\nimport { registerI18nEffects } from './effects';\nimport { i18nReducer, initialI18nState } from './reducer';\nimport { I18nToken } from './types';\nimport type { I18nAction, I18nCapability, I18nConfig, I18nState } from './types';\n\n/**\n * The i18n plugin: workspace-scoped (locale is a workspace concern) with NO\n * dependencies — engine-free, DOM-free. Its capability is built synchronously\n * in `createKernel()`, so the shell translates from the first frame, while\n * the engine is still booting.\n */\nexport const i18nPlugin = (config: I18nConfig = {}) =>\n definePlugin<I18nState, I18nAction, I18nCapability>({\n id: 'i18n',\n scope: 'workspace',\n token: I18nToken,\n initialState: () => initialI18nState(config),\n reduce: i18nReducer,\n capability: (ctx) => createI18nCapability(ctx, config),\n effects: registerI18nEffects(config),\n });\n","/**\n * Pure BCP-47 locale negotiation — strings in, string out. The plugin never\n * reads the platform; the EMBEDDER feeds it whatever request list its\n * environment offers:\n *\n * ```ts\n * // browser shell: negotiateLocale(['en', 'es', 'ar'], navigator.languages)\n * // server render: negotiateLocale(codes, parseAcceptLanguage(header))\n * ```\n *\n * Matching, per requested code in preference order:\n * 1. exact match (case-insensitive): 'es-MX' → 'es-MX'\n * 2. request narrowed to its language: 'en-GB' → 'en'\n * 3. any available dialect of the language: 'zh' → 'zh-Hans'\n *\n * Returns the matched code exactly as it appears in `available`, or null.\n */\nexport function negotiateLocale(\n available: readonly string[],\n requested: readonly string[],\n): string | null {\n const byCanon = new Map<string, string>();\n for (const code of available) {\n const canon = code.toLowerCase();\n if (!byCanon.has(canon)) byCanon.set(canon, code);\n }\n const languageOf = (code: string) => code.toLowerCase().split('-')[0];\n\n for (const want of requested) {\n const exact = byCanon.get(want.toLowerCase());\n if (exact !== undefined) return exact;\n }\n for (const want of requested) {\n const narrowed = byCanon.get(languageOf(want));\n if (narrowed !== undefined) return narrowed;\n }\n for (const want of requested) {\n const language = languageOf(want);\n for (const [canon, original] of byCanon) {\n if (languageOf(canon) === language) return original;\n }\n }\n return null;\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,OACP,MACA,KAC4C;CAC5C,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,IAAI,OAAmD;CACvD,KAAK,MAAM,QAAQ,IAAI,MAAM,GAAG,GAAG;EACjC,IAAI,SAAS,KAAA,KAAa,OAAO,SAAS,UAAU,OAAO,KAAA;EAC3D,OAAO,KAAK;CACd;CACA,OAAO;AACT;;;AAIA,SAAS,eAAe,QAAgB,OAAuB;CAC7D,IAAI;EACF,OAAO,IAAI,KAAK,YAAY,MAAM,CAAC,CAAC,OAAO,KAAK;CAClD,QAAQ;EACN,OAAO,UAAU,IAAI,QAAQ;CAC/B;AACF;;AAGA,SAAS,YACP,MACA,QACA,QACoB;CACpB,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,IAAI,SAAS,KAAA,KAAa,OAAO,QAAQ,UAAU,UAAU;EAC3D,MAAM,SAAS,KAAK,eAAe,QAAQ,OAAO,KAAK,MAAM,KAAK;EAClE,IAAI,OAAO,WAAW,UAAU,OAAO;CACzC;AAEF;;AAGA,SAAgB,YAAY,MAAc,QAAkD;CAC1F,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,KAAK,QAAQ,eAAe,OAAO,SACxC,OAAO,UAAU,KAAA,IAAY,OAAO,OAAO,KAAK,IAAI,KACtD;AACF;;;;;AAYA,SAAgB,UACd,OACA,KACA,SACiB;CACjB,MAAM,EAAE,QAAQ,gBAAgB,YAAY;CAC5C,MAAM,OACJ,YAAY,OAAO,QAAQ,OAAO,EAAE,cAAc,GAAG,GAAG,QAAQ,SAAS,MAAM,KAC/E,YACE,OAAO,QAAQ,eAAe,EAAE,cAAc,GAAG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