@fanee/core 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,201 @@
1
+ # @fanee/core
2
+
3
+ Core runtime for the OTB (Open Translation Bundle) format.
4
+
5
+ Provides `FaneeRuntime`, a plugin-based i18n runtime with MF2 MessageFormat support, and `i18n`, a pre-instantiated singleton.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @fanee/core
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import { FaneeRuntime } from "@fanee/core";
17
+
18
+ const runtime = new FaneeRuntime().config({
19
+ defaultLocale: "en",
20
+ currentLocale: "en",
21
+ resources: {
22
+ "": {
23
+ en: { greeting: "Hello, {name}!" },
24
+ fr: { greeting: "Bonjour, {name}!" },
25
+ },
26
+ },
27
+ });
28
+
29
+ runtime.t("greeting"); // "Hello, {name}!"
30
+ runtime.t("greeting", { name: "World" }); // "Hello, World!"
31
+
32
+ runtime.setLocale("fr");
33
+ runtime.t("greeting", { name: "World" }); // "Bonjour, World!"
34
+ ```
35
+
36
+ Or use the global singleton:
37
+
38
+ ```typescript
39
+ import { i18n } from "@fanee/core";
40
+
41
+ i18n.config({
42
+ defaultLocale: "en",
43
+ currentLocale: "en",
44
+ resources: {
45
+ "": { en: { hello: "Hello, World!" } },
46
+ },
47
+ });
48
+
49
+ i18n.t("hello"); // "Hello, World!"
50
+ ```
51
+
52
+ ## API
53
+
54
+ ### `FaneeRuntime`
55
+
56
+ #### `config(patch)`
57
+
58
+ Shallow-merges a partial state patch into the runtime state. Returns `this` for chaining.
59
+
60
+ ```typescript
61
+ runtime.config({
62
+ defaultLocale: "en",
63
+ currentLocale: "en",
64
+ baseNamespace: "web",
65
+ resources: { /* ... */ },
66
+ });
67
+ ```
68
+
69
+ #### `use(fn)`
70
+
71
+ Registers a plugin function that transforms the runtime state. Plugins run sequentially in registration order. Returns `this` for chaining.
72
+
73
+ ```typescript
74
+ runtime.use(async (state) => {
75
+ const resources = await loadFromAPI();
76
+ return { ...state, resources };
77
+ });
78
+ ```
79
+
80
+ #### `ready()`
81
+
82
+ Returns a `Promise<void>` that resolves when all queued plugins have completed. The runtime is also thenable, so `await runtime` works as a shorthand.
83
+
84
+ ```typescript
85
+ const runtime = new FaneeRuntime()
86
+ .use(asyncPlugin)
87
+ .config({ defaultLocale: "en" });
88
+
89
+ await runtime.ready();
90
+ // or: await runtime;
91
+ ```
92
+
93
+ ### Translation Methods
94
+
95
+ #### `t(key, vars?)`
96
+
97
+ Translates a key using the current locale and base namespace. Returns a string.
98
+
99
+ ```typescript
100
+ runtime.t("key"); // looks up in base namespace with current locale
101
+ runtime.t("greeting", { name: "World" }); // with MF2 variable interpolation
102
+ ```
103
+
104
+ #### `getT(context?)`
105
+
106
+ Returns a translation function bound to the given context. The `context.namespace` appends to the base namespace with `:` as separator.
107
+
108
+ ```typescript
109
+ const t = runtime.getT();
110
+ t("key"); // looks up in base namespace
111
+
112
+ const tAuth = runtime.getT({ namespace: "auth" });
113
+ tAuth("login"); // looks up in "base:auth" (or "auth" if base namespace is "")
114
+
115
+ const tFr = runtime.getT({ locale: "fr" });
116
+ tFr("key"); // looks up with locale "fr"
117
+ ```
118
+
119
+ #### `tAll(key, vars?)`
120
+
121
+ Returns translations for a key in all available locales within the base namespace.
122
+
123
+ ```typescript
124
+ runtime.tAll("greeting");
125
+ // { en: "Hello", fr: "Bonjour", de: "Hallo" }
126
+ ```
127
+
128
+ #### `getLocale()`
129
+
130
+ Returns the current locale BCP 47 tag.
131
+
132
+ #### `getLocales()`
133
+
134
+ Returns a sorted array of all locales present in loaded resources.
135
+
136
+ #### `setLocale(locale)`
137
+
138
+ Sets the current locale. Subsequent `t()` calls use the new locale.
139
+
140
+ ```typescript
141
+ runtime.setLocale("fr");
142
+ runtime.t("greeting"); // "Bonjour"
143
+ ```
144
+
145
+ #### `setNamespace(ns)`
146
+
147
+ Sets the base namespace. Subsequent lookups resolve against this namespace.
148
+
149
+ ```typescript
150
+ runtime.setNamespace("admin");
151
+ runtime.t("dashboard_title");
152
+ ```
153
+
154
+ #### `getAllTranslations()`
155
+
156
+ Returns the full resource tree (`BundleResources`).
157
+
158
+ #### `getTranslationsForNamespace(ns)`
159
+
160
+ Returns locale-indexed messages for a namespace, or `undefined`.
161
+
162
+ #### `subscribe(callback)`
163
+
164
+ Subscribes to state changes. Returns an unsubscribe function.
165
+
166
+ ```typescript
167
+ const unsub = runtime.subscribe((state) => {
168
+ console.log("locale changed to", state.currentLocale);
169
+ });
170
+ unsub();
171
+ ```
172
+
173
+ ### `i18n` singleton
174
+
175
+ A pre-instantiated `FaneeRuntime` exported for convenience.
176
+
177
+ ```typescript
178
+ import { i18n } from "@fanee/core";
179
+ ```
180
+
181
+ ## Translation Format
182
+
183
+ By default, messages are formatted using MF2 MessageFormat with variable interpolation:
184
+
185
+ ```typescript
186
+ runtime.t("greeting", { name: "World" }); // "Hello, World!"
187
+ runtime.t("price", { amount: 1234.56 }); // "Total: $1,234.56"
188
+ runtime.t("date", { today: new Date("2024-02-02") }); // "Today is Feb 2, 2024"
189
+ runtime.t("items", { count: 1 }); // "a item"
190
+ runtime.t("items", { count: 5 }); // "5 items"
191
+ ```
192
+
193
+ Set `formatting` to `"identity"` to disable formatting.
194
+
195
+ ## Locale Fallback
196
+
197
+ When a key is missing in the current locale, the runtime falls back to the default locale. If missing in both, the key itself is returned.
198
+
199
+ ## License
200
+
201
+ MIT
@@ -124,7 +124,8 @@ declare class FaneeRuntime {
124
124
  * @param onfulfilled - Handler for successful queue resolution.
125
125
  * @param onrejected - Handler for queue rejection.
126
126
  */
127
- then<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
127
+ then<TResult1 = void, TResult2 = never>(onfulfilled?: // biome-ignore lint/suspicious/noConfusingVoidType: matches Promise<void> queue resolution
128
+ ((value: void) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
128
129
  /** Resolve locale + namespace from an optional context, falling back to the current state. */
129
130
  private resolveContext;
130
131
  /**
@@ -293,4 +294,4 @@ declare class FaneeRuntime {
293
294
  declare const i18n: FaneeRuntime;
294
295
  //#endregion
295
296
  export { type BundleResources, FaneeRuntime, type FaneeState, type Locale, type LocaleMessages, type MessageKey, type Namespace, type NamespaceResources, type OTBManifest, type TranslateContext, type TranslateFunction, type TranslateOptions, type TranslationsByLocale, i18n };
296
- //# sourceMappingURL=index.d.mts.map
297
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/runtime.ts","../src/i18n.ts"],"mappings":";;KACY,MAAA;;KAEA,SAAA;;KAEA,UAAA;AAFZ;;;;AAAqB;AAErB;;AAFA,KAUY,qBAAA;;KAGA,cAAA,GAAiB,MAAM,CAAC,UAAA;AAHpC;AAAA,KAMY,kBAAA,GAAqB,MAAA,CAAO,MAAA,EAAQ,cAAA;;KAGpC,eAAA,GAAkB,MAAA,CAAO,SAAA,EAAW,kBAAA;AATf;AAAA,UAYhB,gBAAA;EATS;EAWzB,MAAA;EAX4B;EAa5B,IAAA,GAAO,MAAA;EAVI;EAYX,UAAA,GAAa,qBAAqB;AAAA;;UAIlB,gBAAA;EAhBgB;EAkBhC,SAAA,GAAY,SAAA;EAlB0B;EAoBtC,MAAA,GAAS,MAAM;AAAA;;KAIJ,iBAAA,IAAqB,GAAA,EAAK,UAAA,EAAY,IAAA,GAAO,MAAM;AAxBD;AAAA,KA2BlD,oBAAA,GAAuB,MAAM,CAAC,MAAA;;UAGzB,WAAA;EA3BoB;EA6BpC,MAAA;EA7B6B;EA+B7B,WAAA;EA/BmC;EAiCnC,aAAA;EAjCoC;EAmCpC,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AAA,CAAK,GAAA,EAAK,UAAA,EAAY,IAAA,GAAO,MAAA,oBAA0B,oBAAA;EDlI3C;;;;;ECuJZ,SAAA,IAAa,MAAA;ED7Jb;;;;;;ECuKA,UAAA,IAAc,MAAA;EDjKF;;;;;ECgLZ,kBAAA,IAAsB,eAAA;ED9K6B;;;;ACtEpD;;;EA+PC,2BAAA,CAA4B,EAAA,WAAa,kBAAA;EA7NV;;;;;;;;;;;;;;;;;;;EAoP/B,KAAA,IAAS,OAAA;EAhFoB;;;;;;;;;;;;;;;EAmG7B,SAAA,CAAU,MAAA,EAAQ,MAAA;EAvQlB;;;;;;;;;;;;;;;EA2RA,YAAA,CAAa,EAAA;EAlPiB;;;;;;;;;;;;;;;;;;;;EA2Q9B,SAAA,CAAU,QAAA,GAAW,KAAA,EAAO,UAAA;AAAA;;;cCjWhB,IAAA,EAAI,YAAqB"}
@@ -1,3 +1,3 @@
1
1
  const e=/^[\u061c\u200e\u200f\u2066-\u2069]+/,t=/^[-.+0-9A-Z_a-z\u{a1}-\u{61b}\u{61d}-\u{167f}\u{1681}-\u{1fff}\u{200b}-\u{200d}\u{2010}-\u{2027}\u{2030}-\u{205e}\u{2060}-\u{2065}\u{206a}-\u{2fff}\u{3001}-\u{d7ff}\u{e000}-\u{fdcf}\u{fdf0}-\u{fffd}\u{10000}-\u{1fffd}\u{20000}-\u{2fffd}\u{30000}-\u{3fffd}\u{40000}-\u{4fffd}\u{50000}-\u{5fffd}\u{60000}-\u{6fffd}\u{70000}-\u{7fffd}\u{80000}-\u{8fffd}\u{90000}-\u{9fffd}\u{a0000}-\u{afffd}\u{b0000}-\u{bfffd}\u{c0000}-\u{cfffd}\u{d0000}-\u{dfffd}\u{e0000}-\u{efffd}\u{f0000}-\u{ffffd}\u{100000}-\u{10fffd}]+/u,n=/^[-.0-9]/;function r(r,i){let a=i,o=r.slice(a).match(e);o&&(a+=o[0].length);let s=r.slice(a).match(t);if(!s)return null;let c=s[0];if(n.test(c))return null;a+=c.length;let l=r.slice(a).match(e);return l&&(a+=l[0].length),{value:c.normalize(),end:a}}const i=(e,n)=>e.slice(n).match(t)?.[0]??``,a=Symbol.for(`CST`);var o=class extends Error{type;constructor(e,t){super(t),this.type=e}},s=class extends o{start;end;constructor(e,t,n,r){let i=r?`Missing ${r}`:e;t>=0&&(i+=` at ${t}`),super(e,i),this.start=t,this.end=n??t+1}},c=class extends s{constructor(e,t){let{start:n,end:r}=t[a]??{start:-1,end:-1};super(e,n,r)}},l=class extends o{source;cause;constructor(e,t,n,r){super(e,t),this.source=n,r!==void 0&&(this.cause=r)}},u=class extends o{source;cause;constructor(e,t){super(e,t),this.source=`�`}};const d=new Set(`؜‎‏⁦⁧⁨⁩`),f=new Set(`
2
2
  \r  `);let p,m;const h=(e,t)=>new s(`missing-syntax`,e,e+t.length,t),g=(...e)=>new s(...e);function _(e,t){if(m.startsWith(e,p))t&&(p+=e.length);else throw h(p,e)}function ee(e){p=0,m=e;let t=re();if(m.startsWith(`.match`,p))return te(t);let n=t.length>0||m.startsWith(`{{`,p);!n&&p>0&&(p=0);let r=v(n);if(n&&(D(),p<m.length))throw g(`extra-content`,p,m.length);return{type:`message`,declarations:t,pattern:r}}function te(e){p+=6,D(!0);let t=[];for(;m[p]===`$`;)t.push(C()),D(!0);if(t.length===0)throw g(`empty-token`,p);let n=[];for(;p<m.length;)n.push(ne()),D();return{type:`select`,declarations:e,selectors:t,variants:n}}function ne(){let e=[];for(;p<m.length;){D(e.length?`{`:!1);let t=m[p];if(t===`{`)break;if(t===`*`)e.push({type:`*`}),p+=1;else{let t=w(!0);t.value=t.value.normalize(),e.push(t)}}return{keys:e,value:v(!0)}}function v(e){if(e)if(m.startsWith(`{{`,p))p+=2;else throw h(p,`{{`);let t=[];loop:for(;p<m.length;)switch(m[p]){case`{`:t.push(b(!0));break;case`}`:if(!e)throw g(`parse-error`,p);break loop;default:t.push(oe())}if(e)if(m.startsWith(`}}`,p))p+=2;else throw h(p,`}}`);return t}function re(){let e=[];D();loop:for(;m[p]===`.`;){switch(m.substr(p,6)){case`.input`:e.push(ie());break;case`.local`:e.push(y());break;case`.match`:break loop;default:throw g(`parse-error`,p)}D()}return e}function ie(){p+=6,D(),_(`{`,!1);let e=p,t=b(!1);if(t.type===`expression`&&t.arg?.type===`variable`)return{type:`input`,name:t.arg.name,value:t};throw g(`bad-input-expression`,e,p)}function y(){p+=6,D(!0),_(`$`,!0);let e=E();return D(),_(`=`,!0),D(),_(`{`,!1),{type:`local`,name:e,value:b(!1)}}function b(e){let t=p;p+=1,D();let n=S(!1);n&&D(`}`);let r=m[p],i,a;switch(r){case`@`:case`}`:break;case`:`:{p+=1,i={type:`function`,name:T()};let e=x();e&&(i.options=e);break}case`#`:case`/`:{if(n||!e)throw g(`parse-error`,p);p+=1,a={type:`markup`,kind:r===`#`?`open`:`close`,name:T()};let t=x();t&&(a.options=t);break}default:throw g(`parse-error`,p)}let o=ae();if(a?.kind===`open`&&m[p]===`/`&&(a.kind=`standalone`,p+=1),_(`}`,!0),i){let e=n?{type:`expression`,arg:n,functionRef:i}:{type:`expression`,functionRef:i};return o&&(e.attributes=o),e}if(a)return o&&(a.attributes=o),a;if(!n)throw g(`empty-token`,t,p);return o?{type:`expression`,arg:n,attributes:o}:{type:`expression`,arg:n}}function x(){D(`/}`);let e={},t=!0;for(;p<m.length;){let n=m[p];if(n===`@`||n===`/`||n===`}`)break;let r=p,i=T();if(Object.hasOwn(e,i))throw g(`duplicate-option-name`,r,p);D(),_(`=`,!0),D(),e[i]=S(!0),t=!1,D(`/}`)}return t?null:e}function ae(){let e={},t=!0;for(;m[p]===`@`;){let n=p;p+=1;let r=T();if(Object.hasOwn(e,r))throw g(`duplicate-attribute`,n,p);D(`=/}`),m[p]===`=`?(p+=1,D(),e[r]=w(!0),D(`/}`)):e[r]=!0,t=!1}return t?null:e}function oe(){let e=``,t=p;loop:for(;t<m.length;++t)switch(m[t]){case`\\`:{let n=m[t+1];if(!`\\{|}`.includes(n))throw g(`bad-escape`,t,t+2);e+=m.substring(p,t)+n,t+=1,p=t+1;break}case`{`:case`}`:break loop}return e+=m.substring(p,t),p=t,e}function S(e){return m[p]===`$`?C():w(e)}function C(){return p+=1,{type:`variable`,name:E()}}function w(e){if(m[p]===`|`)return se();let t=i(m,p);if(!t){if(e)throw g(`empty-token`,p);return}return p+=t.length,{type:`literal`,value:t}}function se(){p+=1;let e=``;for(let t=p;t<m.length;++t)switch(m[t]){case`\\`:{let n=m[t+1];if(!`\\{|}`.includes(n))throw g(`bad-escape`,t,t+2);e+=m.substring(p,t)+n,t+=1,p=t+1;break}case`|`:return e+=m.substring(p,t),p=t+1,{type:`literal`,value:e}}throw h(m.length,`|`)}function T(){let e=E();return m[p]===`:`?(p+=1,e+`:`+E()):e}function E(){let e=r(m,p);if(!e)throw g(`empty-token`,p);return p=e.end,e.value}function D(e=!1){let t=m[p],n=!1;if(e){for(;d.has(t);)t=m[++p];for(;f.has(t);)t=m[++p],n=!0}for(;d.has(t)||f.has(t);)t=m[++p];if(e&&!n&&(e===!0||!e.includes(m[p])))throw h(p,`' '`)}function ce(e,t){let{node:n,pattern:r}=t,{functionRef:i=n,attributes:a=null,declaration:o=n,expression:s=n,key:c=n,markup:l=n,options:u=null,value:d=n,variant:f=n}=t,p=(e,t)=>{if(e){let n=u?.(e,t);if(d)for(let n of Object.values(e))d(n,t,`option`);n?.()}},m=(e,t)=>{if(e){let n=a?.(e,t);if(d)for(let n of Object.values(e))n!==!0&&d(n,t,`attribute`);n?.()}},h=(e,t)=>{if(typeof e==`object`){let n;switch(e.type){case`expression`:if(n=s?.(e,t),e.arg&&d?.(e.arg,t,`arg`),e.functionRef){let n=i?.(e.functionRef,t,e.arg);p(e.functionRef.options,t),n?.()}m(e.attributes,t);break;case`markup`:n=l?.(e,t),p(e.options,t),m(e.attributes,t);break}n?.()}},g=e=>{let t=r?.(e);for(let t of e)h(t,`placeholder`);t?.()};for(let t of e.declarations){let e=o?.(t);t.value&&h(t.value,`declaration`),e?.()}if(e.type===`message`)g(e.pattern);else{if(d)for(let t of e.selectors)d(t,`selector`,`arg`);for(let t of e.variants){let e=f?.(t);c&&t.keys.forEach(c),g(t.value),e?.()}}}function le(e,t=(e,t)=>{throw new c(e,t)}){let n=0,r=null,i=new Set,a=new Set,o=new Set,s=new Set,l=new Set,u=new Set,d=!0;ce(e,{declaration(e){if(e.name)return(e.value.functionRef||e.type===`local`&&e.value.arg?.type===`variable`&&i.has(e.value.arg.name))&&i.add(e.name),e.type===`local`&&s.add(e.name),d=e.type===`local`,()=>{a.has(e.name)?t(`duplicate-declaration`,e):a.add(e.name)}},expression({functionRef:e}){e&&o.add(e.name)},value(e,o,s){if(e.type===`variable`)switch(l.add(e.name),o){case`declaration`:(s!==`arg`||d)&&a.add(e.name);break;case`selector`:n+=1,r=e,i.has(e.name)||t(`missing-selector-annotation`,e)}},variant(e){let{keys:i}=e;i.length!==n&&t(`key-mismatch`,e);let a=JSON.stringify(i.map(e=>e.type===`literal`?e.value:0));u.has(a)?t(`duplicate-variant`,e):u.add(a),r&&=i.every(e=>e.type===`*`)?null:e}}),r&&t(`missing-fallback`,r);for(let e of s)l.delete(e);return{functions:o,variables:l}}function O(e){if(e)try{typeof e==`string`&&(e=new Intl.Locale(e));let t=e.getTextInfo?.()??e.textInfo;if(t?.direction)return t.direction;let n=e.maximize().script;if(n)return`Adlm,Arab,Hebr,Mand,Nkoo,Rohg,Syrc,Thaa`.includes(n)?`rtl`:`ltr`}catch{}return`auto`}function ue(e){if(e&&typeof e==`object`&&(e=e.valueOf()),typeof e==`boolean`)return e;if(e&&typeof e==`object`&&(e=String(e)),e===`true`)return!0;if(e===`false`)return!1;throw RangeError(`Not a boolean`)}function k(e){if(e&&typeof e==`object`&&(e=e.valueOf()),e&&typeof e==`object`&&(e=String(e)),typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)&&(e=Number(e)),typeof e==`number`&&e>=0&&Number.isInteger(e))return e;throw RangeError(`Not a positive integer`)}function A(e){if(e&&typeof e==`object`&&(e=e.valueOf()),typeof e==`string`)return e;if(e&&typeof e==`object`)return String(e);throw RangeError(`Not a string`)}function j(e){let t;if(typeof e==`object`){let n=e?.valueOf;typeof n==`function`&&(t=e.options,e=n.call(e))}if(typeof e==`string`)try{e=JSON.parse(e)}catch{}if(typeof e!=`bigint`&&typeof e!=`number`)throw new u(`bad-operand`,`Input is not numeric`);return{value:e,options:t}}function M(e,t,n,r){let{dir:i,locales:a}=e;n.useGrouping===`never`&&(n.useGrouping=!1),r&&`select`in n&&!e.literalOptionKeys.has(`select`)&&(e.onError(`bad-option`,`The option select may only be set by a literal value`),r=!1);let o,s,c,l;return{type:`number`,get dir(){return i??=(o??=Intl.NumberFormat.supportedLocalesOf(a,n)[0],O(o)),i},get options(){return{...n}},selectKey:r?e=>{let r=t;n.style===`percent`&&(typeof r==`bigint`?r*=100n:r*=100);let i=String(r);if(e.has(i))return i;if(n.select===`exact`)return null;let o=n.select?{...n,select:void 0,type:n.select}:n;return c??=new Intl.PluralRules(a,o).select(Number(r)),e.has(c)?c:null}:void 0,toParts(){s??=new Intl.NumberFormat(a,n);let e=s.formatToParts(t);return o??=s.resolvedOptions().locale,i??=O(o),i===`ltr`||i===`rtl`?[{type:`number`,dir:i,locale:o,parts:e}]:[{type:`number`,locale:o,parts:e}]},toString(){return s??=new Intl.NumberFormat(a,n),l??=s.format(t),l},valueOf:()=>t}}function N(e,t,n){let r=j(n),i=r.value,a=Object.assign({},r.options,{localeMatcher:e.localeMatcher,style:`decimal`});for(let[n,r]of Object.entries(t))if(r!==void 0)try{switch(n){case`minimumIntegerDigits`:case`minimumFractionDigits`:case`maximumFractionDigits`:case`minimumSignificantDigits`:case`maximumSignificantDigits`:case`roundingIncrement`:a[n]=k(r);break;case`roundingMode`:case`roundingPriority`:case`select`:case`signDisplay`:case`trailingZeroDisplay`:case`useGrouping`:a[n]=A(r)}}catch{e.onError(`bad-option`,`Value ${r} is not valid for :number option ${n}`)}return M(e,i,a,!0)}function de(e,t,n){let r=j(n),i=Number.isFinite(r.value)?Math.round(r.value):r.value,a=Object.assign({},r.options,{maximumFractionDigits:0,minimumFractionDigits:void 0,minimumSignificantDigits:void 0,style:`decimal`});for(let[n,r]of Object.entries(t))if(r!==void 0)try{switch(n){case`minimumIntegerDigits`:case`maximumSignificantDigits`:a[n]=k(r);break;case`select`:case`signDisplay`:case`useGrouping`:a[n]=A(r)}}catch{e.onError(`bad-option`,`Value ${r} is not valid for :integer option ${n}`)}return M(e,i,a,!0)}function fe(e,t,n){let r=j(n),i=Object.assign({},r.options,{localeMatcher:e.localeMatcher,style:`currency`});for(let[n,r]of Object.entries(t))if(r!==void 0)try{switch(n){case`currency`:case`currencySign`:case`roundingMode`:case`roundingPriority`:case`trailingZeroDisplay`:case`useGrouping`:i[n]=A(r);break;case`minimumIntegerDigits`:case`minimumSignificantDigits`:case`maximumSignificantDigits`:case`roundingIncrement`:i[n]=k(r);break;case`currencyDisplay`:{let t=A(r);t===`never`?e.onError(`unsupported-operation`,`Currency display "never" is not yet supported`):i[n]=t;break}case`fractionDigits`:{let e=A(r);if(e===`auto`)i.minimumFractionDigits=void 0,i.maximumFractionDigits=void 0;else{let t=k(e);i.minimumFractionDigits=t,i.maximumFractionDigits=t}break}}}catch{e.onError(`bad-option`,`Value ${r} is not valid for :currency option ${n}`)}if(!i.currency)throw new u(`bad-operand`,`A currency code is required for :currency`);return M(e,r.value,i,!1)}const pe=new Set([`weekday`,`day-weekday`,`month-day`,`month-day-weekday`,`year-month-day`,`year-month-day-weekday`]),me=new Set([`long`,`medium`,`short`]),he=new Set([`hour`,`minute`,`second`]),ge=new Set([`long`,`short`]),_e=(e,t,n)=>P(`datetime`,e,t,n),ve=(e,t,n)=>P(`date`,e,t,n),ye=(e,t,n)=>P(`time`,e,t,n);function P(e,t,n,r){let i={localeMatcher:t.localeMatcher},a=r;if(typeof a==`object`&&a){let t=a.options;t&&(i.calendar=t.calendar,e!==`date`&&(i.hour12=t.hour12),i.timeZone=t.timeZone),typeof a.valueOf==`function`&&(a=a.valueOf())}switch(typeof a){case`number`:case`string`:a=new Date(a)}if(!(a instanceof Date)||isNaN(a.getTime()))throw new u(`bad-operand`,`Input is not a valid date`);if(n.calendar!==void 0)try{i.calendar=A(n.calendar)}catch{t.onError(`bad-option`,`Invalid :${e} calendar option value`)}if(n.hour12!==void 0&&e!==`date`)try{i.hour12=ue(n.hour12)}catch{t.onError(`bad-option`,`Invalid :${e} hour12 option value`)}if(n.timeZone!==void 0){let r;try{r=A(n.timeZone)}catch{t.onError(`bad-option`,`Invalid :${e} timeZone option value`)}if(r===`input`)i.timeZone===void 0&&t.onError(`bad-operand`,`Missing input timeZone value for :${e}`);else if(r!==void 0){if(i.timeZone!==void 0&&r!==i.timeZone)throw new u(`bad-option`,`Time zone conversion is not supported`);i.timeZone=r}}if(e!==`time`){let r=e===`date`?`fields`:`dateFields`,a=e===`date`?`length`:`dateLength`,o=F(t,n,r,pe)??`year-month-day`,s=F(t,n,a,me),c=new Set(o.split(`-`));c.has(`year`)&&(i.year=`numeric`),c.has(`month`)&&(i.month=s===`long`?`long`:s===`short`?`numeric`:`short`),c.has(`day`)&&(i.day=`numeric`),c.has(`weekday`)&&(i.weekday=s===`long`?`long`:`short`)}if(e!==`date`){switch(F(t,n,e===`time`?`precision`:`timePrecision`,he)){case`hour`:i.hour=`numeric`;break;case`second`:i.hour=`numeric`,i.minute=`numeric`,i.second=`numeric`;break;default:i.hour=`numeric`,i.minute=`numeric`}i.timeZoneName=F(t,n,`timeZoneStyle`,ge)}let o=new Intl.DateTimeFormat(t.locales,i),s=t.dir,c,l;return{type:`datetime`,get dir(){return s??=(c??=o.resolvedOptions().locale,O(c)),s},get options(){return{...i}},toParts(){let e=o.formatToParts(a);return c??=o.resolvedOptions().locale,s??=O(c),s===`ltr`||s===`rtl`?[{type:`datetime`,dir:s,locale:c,parts:e}]:[{type:`datetime`,locale:c,parts:e}]},toString(){return l??=o.format(a),l},valueOf:()=>a}}function F(e,t,n,r){let i=t[n];if(i!==void 0)try{let e=A(i);if(r&&!r.has(e))throw Error();return e}catch{e.onError(`bad-option`,`Invalid value for ${n} option`)}}function be(e,t,n){let{value:r,options:i}=j(n),a;try{a=`add`in t?k(t.add):-1}catch{throw new u(`bad-option`,`Value ${t.add} is not valid for :offset option add`)}let o;try{o=`subtract`in t?k(t.subtract):-1}catch{throw new u(`bad-option`,`Value ${t.subtract} is not valid for :offset option subtract`)}if(a<0==o<0)throw new u(`bad-option`,`Exactly one of "add" or "subtract" is required as an :offset option`);let s=a<0?-o:a;return typeof r==`number`?r+=s:r+=BigInt(s),N(e,{},{valueOf:()=>r,options:i})}function xe(e,t,n){let r=j(n),i=Object.assign({},r.options,{localeMatcher:e.localeMatcher,style:`percent`});for(let[n,r]of Object.entries(t))if(r!==void 0)try{switch(n){case`roundingMode`:case`roundingPriority`:case`signDisplay`:case`trailingZeroDisplay`:case`useGrouping`:i[n]=A(r);break;case`minimumFractionDigits`:case`maximumFractionDigits`:case`minimumSignificantDigits`:case`maximumSignificantDigits`:i[n]=k(r);break}}catch{e.onError(`bad-option`,`Value ${r} is not valid for :percent option ${n}`)}return M(e,r.value,i,!0)}function I(e,t,n){let r=n===void 0?``:String(n),i=r.normalize();return{type:`string`,dir:e.dir??`auto`,selectKey:e=>e.has(i)?i:null,toParts(){let{dir:t}=e,n=e.locales[0];return t===`ltr`||t===`rtl`?[{type:`string`,dir:t,locale:n,value:r}]:[{type:`string`,locale:n,value:r}]},toString:()=>r,valueOf:()=>r}}function L(e,t,n){let r=j(n),i=Object.assign({},r.options,{localeMatcher:e.localeMatcher,style:`unit`});for(let[n,r]of Object.entries(t))if(r!==void 0)try{switch(n){case`signDisplay`:case`roundingMode`:case`roundingPriority`:case`trailingZeroDisplay`:case`unit`:case`unitDisplay`:case`useGrouping`:i[n]=A(r);break;case`minimumIntegerDigits`:case`minimumFractionDigits`:case`maximumFractionDigits`:case`minimumSignificantDigits`:case`maximumSignificantDigits`:case`roundingIncrement`:i[n]=k(r);break}}catch(t){t instanceof o?e.onError(t):e.onError(`bad-option`,`Value ${r} is not valid for :currency option ${n}`)}if(!i.unit)throw new u(`bad-operand`,`A unit identifier is required for :unit`);return M(e,r.value,i,!1)}let R={integer:de,number:N,offset:be,string:I};R=Object.freeze(Object.assign(Object.create(null),R));let z={currency:fe,date:ve,datetime:_e,percent:xe,time:ye,unit:L};z=Object.freeze(Object.assign(Object.create(null),z));const B=Symbol(`bidi-isolate`),V=(e=`�`)=>({type:`fallback`,source:e,toParts:()=>[{type:`fallback`,source:e}],toString:()=>`{${e}}`}),Se=(e,t)=>({type:`unknown`,source:e,dir:`auto`,toParts:()=>[{type:`unknown`,value:t}],toString:()=>String(t),valueOf:()=>t});var H=class{#e;#t;#n;dir;id;constructor(e,t,n){this.#e=e,this.#n=t,this.dir=void 0;let r=n&&Object.hasOwn(n,`u:dir`)?n[`u:dir`]:void 0;if(r){let t=String(J(e,r));if(t===`ltr`||t===`rtl`||t===`auto`)this.dir=t;else if(t!==`inherit`){let t=new u(`bad-option`,`Unsupported value for u:dir option`);t.source=Y(r),e.onError(t)}}let i=n&&Object.hasOwn(n,`u:id`)?n[`u:id`]:void 0;if(this.id=i?String(J(e,i)):void 0,n){this.#t=new Set;for(let[e,t]of Object.entries(n))t.type===`literal`&&this.#t.add(e)}}get literalOptionKeys(){return new Set(this.#t)}get localeMatcher(){return this.#e.localeMatcher}get locales(){return this.#e.locales.map(String)}onError(e,t){let n;e instanceof u?n=e:typeof e==`string`&&typeof t==`string`?n=new u(e,t):(n=new u(`function-error`,String(e)),n.cause=e),n.source=this.#n,this.#e.onError(n)}};function Ce(e,t,{name:n,options:r}){let i=`:${n}`,a=Y(t)??i;try{let o=t?[J(e,t)]:[],s=e.functions[n];if(!s)throw new l(`unknown-function`,`Unknown function ${i}`,a);let c=new H(e,a,r),u=s(c,we(e,r),...o);if(typeof u!=`object`||!u||typeof u.type!=`string`)throw new l(`bad-function-result`,`Function ${i} did not return a MessageValue`,a);let d={source:a};return c.dir&&(d.dir=c.dir,d[B]=!0),c.id&&typeof u.toParts==`function`&&(d.toParts=()=>{let e=u.toParts();for(let t of e)t.id=c.id;return e}),{...u,...d}}catch(t){return e.onError(t instanceof o?t:new l(`bad-function-result`,String(t),a,t)),V(a)}}function we(e,t){let n=Object.create(null);if(t)for(let[r,i]of Object.entries(t))r.startsWith(`u:`)||(n[r]=J(e,i));return n}function U(e,{arg:t,functionRef:n}){if(n)return Ce(e,t,n);switch(t?.type){case`literal`:{let n=`|${t.value}|`,r=I(new H(e,n),{},t.value);return r.source=n,r}case`variable`:return q(e,t);default:throw Error(`Unsupported expression: ${t?.type}`)}}var W=class{expression;scope;constructor(e,t){this.expression=e,this.scope=t}};const Te=e=>e!==null&&(typeof e==`object`||typeof e==`function`);function G(e,t){if(Te(e)){if(t in e)return e[t];let n=t.split(`.`);for(let t=n.length-1;t>0;--t){let r=n.slice(0,t).join(`.`);if(r in e){let i=n.slice(t).join(`.`);return G(e[r],i)}}for(let[n,r]of Object.entries(e))if(n.normalize()===t)return r}}function K(e,{name:t}){let n=G(e.scope,t);if(n===void 0){let n=`$`+t,r=`Variable not available: ${n}`;e.onError(new l(`unresolved-variable`,r,n))}else if(n instanceof W){let r=U(n.scope?{...e,scope:n.scope}:e,n.expression);return e.scope[t]=r,e.localVars.add(r),r}return n}function q(e,t){let n=`$`+t.name,r=K(e,t);if(r===void 0)return V(n);let i=typeof r;if(i===`object`){let t=r;if(t.type===`fallback`)return V(n);if(e.localVars.has(t))return t.source=n,t;r instanceof Number?i=`number`:r instanceof String&&(i=`string`)}let a;switch(i){case`bigint`:case`number`:a=e.functions.number;break;case`string`:a=e.functions.string;break;default:return Se(n,r)}let o=new H(e,n),s=a(o,{},r);return s.source=n,s}function J(e,t){switch(t.type){case`literal`:return t.value;case`variable`:return K(e,t);default:throw Error(`Unsupported value: ${t.type}`)}}function Y(e){switch(e?.type){case`literal`:return`|`+e.value.replaceAll(`\\`,`\\\\`).replaceAll(`|`,`\\|`)+`|`;case`variable`:return`$`+e.name;default:return}}function X(e,{kind:t,name:n,options:r}){let i={type:`markup`,kind:t,name:n},a=r?Object.entries(r):null;if(a?.length){i.options={};for(let[t,n]of a)if(t===`u:dir`){let r=new u(`bad-option`,`The option ${t} is not valid for markup`);r.source=Y(n),e.onError(r)}else{let r=J(e,n);typeof r==`object`&&typeof r?.valueOf==`function`&&(r=r.valueOf()),t===`u:id`?i.id=String(r):i.options[t]=r}}return i}function Z(e,t){if(t.type===`message`)return t.pattern;let n=t.selectors.map(t=>{let n=q(e,t),r;return typeof n.selectKey==`function`?r=n.selectKey.bind(n):(e.onError(new l(`bad-selector`,`Selector does not support selection`,n.source)),r=()=>null),{selectKey:r,source:n.source,best:null,keys:null}}),r=t.variants;loop:for(let i=0;i<n.length;++i){let a=n[i];if(!a.keys){a.keys=new Set;for(let{keys:e}of r){let t=e[i];if(!t)break loop;t.type!==`*`&&a.keys.add(t.value)}}try{a.best=a.keys.size?a.selectKey(a.keys):null}catch(t){e.onError(new l(`bad-selector`,`Selection failed`,a.source,t)),a.selectKey=()=>null,a.best=null}if(r=r.filter(e=>{let t=e.keys[i];return t.type===`*`?a.best==null:a.best===t.value}),r.length===0){if(i===0)break;let e=n[i-1];e.best==null?e.keys?.clear():e.keys?.delete(e.best);for(let e=i;e<n.length;++e)n[e].keys=null;r=t.variants,i=-1}}let i=r[0];return i?i.value:(e.onError(new l(`no-match`,`No variant was selected!?`,`.match`)),[])}var Ee=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=n?.bidiIsolation!==`none`,this.#n=n?.localeMatcher??`best fit`,this.#r=Array.isArray(e)?e.map(e=>new Intl.Locale(e)):e?[new Intl.Locale(e)]:[],this.#t=n?.dir??O(this.#r[0]),this.#i=typeof t==`string`?ee(t):t,le(this.#i),this.#a=n?.functions?Object.assign(Object.create(null),R,n.functions):R}format(e,t){let n=this.#o(e,t),r=``;for(let e of Z(n,this.#i))if(typeof e==`string`)r+=e;else if(e.type===`markup`)X(n,e);else{let t;try{if(t=U(n,e),typeof t.toString==`function`)if(this.#e&&(this.#t!==`ltr`||t.dir!==`ltr`||t[B])){let e=t.dir===`ltr`?`⁦`:t.dir===`rtl`?`⁧`:`⁨`;r+=e+t.toString()+`⁩`}else r+=t.toString();else{let e=new u(`not-formattable`,`Message part is not formattable`);throw e.source=t.source,e}}catch(e){n.onError(e);let i=`{${t?.source??`�`}}`;r+=this.#e?`⁨`+i+`⁩`:i}}return r}formatToParts(e,t){let n=this.#o(e,t),r=[];for(let e of Z(n,this.#i))if(typeof e==`string`)r.push({type:`text`,value:e});else if(e.type===`markup`)r.push(X(n,e));else{let t;try{if(t=U(n,e),typeof t.toParts==`function`){let e=t.toParts();if(this.#e&&(this.#t!==`ltr`||t.dir!==`ltr`||t[B])){let n=t.dir===`ltr`?`⁦`:t.dir===`rtl`?`⁧`:`⁨`;r.push({type:`bidiIsolation`,value:n},...e,{type:`bidiIsolation`,value:`⁩`})}else r.push(...e)}else{let e=new u(`not-formattable`,`Message part is not formattable`);throw e.source=t.source,e}}catch(e){n.onError(e);let i={type:`fallback`,source:t?.source??`�`};this.#e?r.push({type:`bidiIsolation`,value:`⁨`},i,{type:`bidiIsolation`,value:`⁩`}):r.push(i)}}return r}#o(e,t=e=>{try{process.emitWarning(e)}catch{console.warn(e)}}){let n={...e};for(let t of this.#i.declarations)n[t.name]=new W(t.value,t.type===`input`?e??{}:void 0);return{onError:t,localeMatcher:this.#n,locales:this.#r,localVars:new WeakSet,functions:this.#a,scope:n}}};const Q=new Map;function De(e,t,n){let r=Q.get(e);r||(r=new Map,Q.set(e,r));let i=r.get(t);return i||(i=new Ee([e],n,{functions:z}),r.set(t,i),i)}function Oe(e,t){if(!t?.vars||Object.keys(t.vars).length===0||t.formatting===`identity`)return e;let{locale:n,vars:r}=t;return De(n,e,e).format(r,e=>{console.warn(`[fanee] Failed to format message: ${e}`)})}function ke(){return{resources:{},defaultLocale:`en`,currentLocale:`en`,baseNamespace:``,formatting:`mf2`,translate:Oe}}var $=class{state;queue;listeners;constructor(){this.state=ke(),this.queue=Promise.resolve(),this.listeners=new Set}notify(){let e=this.state;for(let t of this.listeners)t(e)}use(e){return this.queue=this.queue.then(async()=>{this.state=await e(this.state),this.notify()}),this}config(e){return this.queue=this.queue.then(async()=>{this.state={...this.state,...e},this.notify()}),this}then(e,t){return this.queue.then(e,t)}resolveContext(e){let{currentLocale:t,baseNamespace:n}=this.state;return{locale:e?.locale??t,ns:e?.namespace?n?`${n}:${e.namespace}`:e.namespace:n}}localize(e,t,n,r){if(!e)return n;let i=e[t];if(!i&&(i=e[this.state.defaultLocale],!i))return n;let a=i[n];return a===void 0?n:r===void 0||Object.keys(r).length===0?a:this.state.translate(a,{locale:t,vars:r,formatting:this.state.formatting})}t(e,t){let{locale:n,ns:r}=this.resolveContext();return this.localize(this.state.resources[r],n,e,t)}getT(e){let{locale:t,ns:n}=this.resolveContext(e),r=this.state.resources[n];return(e,n)=>this.localize(r,t,e,n)}tAll(e,t){let{baseNamespace:n,resources:r}=this.state,i=r[n],a={};if(!i)return a;for(let n of Object.keys(i))a[n]=this.localize(i,n,e,t);return a}getLocale(){return this.state.currentLocale}getLocales(){let e=new Set;for(let t of Object.values(this.state.resources))for(let n of Object.keys(t))e.add(n);return Array.from(e).sort()}getAllTranslations(){return this.state.resources}getTranslationsForNamespace(e){return this.state.resources[e]}ready(){return this.queue}setLocale(e){this.state.currentLocale=e,this.notify()}setNamespace(e){this.state.baseNamespace=e,this.notify()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};const Ae=new $;export{$ as FaneeRuntime,Ae as i18n};
3
- //# sourceMappingURL=index.mjs.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["bidiChars","#ctx","#source","#litKeys","#bidiIsolation","#localeMatcher","#locales","#dir","#message","#functions","#createContext"],"sources":["../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/cst/names.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/from-cst.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/errors.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/parse.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/visit.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/validate.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/dir-utils.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/utils.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/number.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/currency.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/datetime.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/offset.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/percent.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/string.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/unit.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/index.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/message-value.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/fallback.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/unknown.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/function-context.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-function-ref.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-expression.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-variable.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-value.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/format-markup.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/select-pattern.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/messageformat.js","../src/translator.ts","../src/state.ts","../src/runtime.ts","../src/i18n.ts"],"sourcesContent":["const bidiChars = /^[\\u061c\\u200e\\u200f\\u2066-\\u2069]+/;\nconst nameChars = /^[-.+0-9A-Z_a-z\\u{a1}-\\u{61b}\\u{61d}-\\u{167f}\\u{1681}-\\u{1fff}\\u{200b}-\\u{200d}\\u{2010}-\\u{2027}\\u{2030}-\\u{205e}\\u{2060}-\\u{2065}\\u{206a}-\\u{2fff}\\u{3001}-\\u{d7ff}\\u{e000}-\\u{fdcf}\\u{fdf0}-\\u{fffd}\\u{10000}-\\u{1fffd}\\u{20000}-\\u{2fffd}\\u{30000}-\\u{3fffd}\\u{40000}-\\u{4fffd}\\u{50000}-\\u{5fffd}\\u{60000}-\\u{6fffd}\\u{70000}-\\u{7fffd}\\u{80000}-\\u{8fffd}\\u{90000}-\\u{9fffd}\\u{a0000}-\\u{afffd}\\u{b0000}-\\u{bfffd}\\u{c0000}-\\u{cfffd}\\u{d0000}-\\u{dfffd}\\u{e0000}-\\u{efffd}\\u{f0000}-\\u{ffffd}\\u{100000}-\\u{10fffd}]+/u;\nconst notNameStart = /^[-.0-9]/;\nexport function parseNameValue(source, start) {\n let pos = start;\n const startBidi = source.slice(pos).match(bidiChars);\n if (startBidi)\n pos += startBidi[0].length;\n const match = source.slice(pos).match(nameChars);\n if (!match)\n return null;\n const name = match[0];\n if (notNameStart.test(name))\n return null;\n pos += name.length;\n const endBidi = source.slice(pos).match(bidiChars);\n if (endBidi)\n pos += endBidi[0].length;\n return { value: name.normalize(), end: pos };\n}\nexport function isValidUnquotedLiteral(str) {\n const match = str.match(nameChars);\n return !!match && match[0].length === str.length;\n}\nexport const parseUnquotedLiteralValue = (source, start) => source.slice(start).match(nameChars)?.[0] ?? '';\n","import { MessageSyntaxError } from \"../errors.js\";\n/**\n * Shared symbol used as a key on message data model nodes\n * to reference their CST source.\n *\n * Only set on message data model nodes when parsed by {@link messageFromCST}.\n */\nexport const cstKey = Symbol.for('CST');\n/**\n * Convert a CST message structure into its data model representation.\n *\n * In the returned {@link Model.Message},\n * all nodes include a reference to their source {@link CST} node\n * as a {@link cstKey} symbol-keyed property.\n */\nexport function messageFromCST(msg) {\n for (const error of msg.errors)\n throw error;\n const declarations = msg.declarations\n ? msg.declarations.map(asDeclaration)\n : [];\n if (msg.type === 'select') {\n return {\n type: 'select',\n declarations,\n selectors: msg.selectors.map(sel => asValue(sel)),\n variants: msg.variants.map(variant => ({\n keys: variant.keys.map(key => key.type === '*' ? { type: '*', [cstKey]: key } : asValue(key)),\n value: asPattern(variant.value),\n [cstKey]: variant\n })),\n [cstKey]: msg\n };\n }\n else {\n return {\n type: 'message',\n declarations,\n pattern: asPattern(msg.pattern),\n [cstKey]: msg\n };\n }\n}\nfunction asDeclaration(decl) {\n switch (decl.type) {\n case 'input': {\n const value = asExpression(decl.value, false);\n if (value.arg?.type !== 'variable') {\n const { start, end } = decl.value;\n throw new MessageSyntaxError('parse-error', start, end);\n }\n return {\n type: 'input',\n name: value.arg.name,\n value: value,\n [cstKey]: decl\n };\n }\n case 'local':\n return {\n type: 'local',\n name: asValue(decl.target).name,\n value: asExpression(decl.value, false),\n [cstKey]: decl\n };\n default:\n throw new MessageSyntaxError('parse-error', decl.start, decl.end);\n }\n}\nconst asPattern = (pattern) => pattern.body.map(el => el.type === 'text' ? el.value : asExpression(el, true));\nfunction asExpression(exp, allowMarkup) {\n if (exp.type === 'expression') {\n if (allowMarkup && exp.markup) {\n const cm = exp.markup;\n const name = asName(cm.name);\n const kind = cm.open.value === '/' ? 'close' : cm.close ? 'standalone' : 'open';\n const markup = { type: 'markup', kind, name };\n if (cm.options.length)\n markup.options = asOptions(cm.options);\n if (exp.attributes.length) {\n markup.attributes = asAttributes(exp.attributes);\n }\n markup[cstKey] = exp;\n return markup;\n }\n const arg = exp.arg ? asValue(exp.arg) : undefined;\n let functionRef;\n const ca = exp.functionRef;\n if (ca) {\n if (ca.type === 'function') {\n functionRef = { type: 'function', name: asName(ca.name) };\n if (ca.options.length)\n functionRef.options = asOptions(ca.options);\n }\n else {\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n }\n }\n let expression = arg\n ? { type: 'expression', arg }\n : undefined;\n if (functionRef) {\n functionRef[cstKey] = ca;\n if (expression)\n expression.functionRef = functionRef;\n else\n expression = { type: 'expression', functionRef: functionRef };\n }\n if (expression) {\n if (exp.attributes.length) {\n expression.attributes = asAttributes(exp.attributes);\n }\n expression[cstKey] = exp;\n return expression;\n }\n }\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n}\nfunction asOptions(options) {\n const map = {};\n for (const opt of options) {\n const name = asName(opt.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-option-name', opt.start, opt.end);\n }\n map[name] = asValue(opt.value);\n }\n return map;\n}\nfunction asAttributes(attributes) {\n const map = {};\n for (const attr of attributes) {\n const name = asName(attr.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-attribute', attr.start, attr.end);\n }\n map[name] = attr.value ? asValue(attr.value) : true;\n }\n return map;\n}\nfunction asName(id) {\n switch (id.length) {\n case 1:\n return id[0].value;\n case 3:\n return `${id[0].value}:${id[2].value}`;\n default:\n throw new MessageSyntaxError('parse-error', id[0]?.start ?? -1, id.at(-1)?.end ?? -1);\n }\n}\nfunction asValue(value) {\n switch (value.type) {\n case 'literal':\n return { type: 'literal', value: value.value, [cstKey]: value };\n case 'variable':\n return { type: 'variable', name: value.name, [cstKey]: value };\n default:\n throw new MessageSyntaxError('parse-error', value.start, value.end);\n }\n}\n","import { cstKey } from \"./data-model/from-cst.js\";\n/**\n * Base error class used by MessageFormat\n *\n * @category Errors\n */\nexport class MessageError extends Error {\n type;\n constructor(type, message) {\n super(message);\n this.type = type;\n }\n}\n/**\n * Errors in the message syntax.\n *\n * @category Errors\n */\nexport class MessageSyntaxError extends MessageError {\n start;\n end;\n /** @private */\n constructor(type, start, end, expected) {\n let message = expected ? `Missing ${expected}` : type;\n if (start >= 0)\n message += ` at ${start}`;\n super(type, message);\n this.start = start;\n this.end = end ?? start + 1;\n }\n}\n/**\n * Errors in the message data model.\n *\n * @category Errors\n */\nexport class MessageDataModelError extends MessageSyntaxError {\n /** @private */\n constructor(type, node) {\n const { start, end } = node[cstKey] ?? { start: -1, end: -1 };\n super(type, start, end);\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageResolutionError extends MessageError {\n source;\n cause;\n constructor(type, message, source, cause) {\n super(type, message);\n this.source = source;\n if (cause !== undefined)\n this.cause = cause;\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageFunctionError extends MessageError {\n source;\n cause;\n constructor(type, message) {\n super(type, message);\n this.source = '�';\n }\n}\n","import { parseNameValue, parseUnquotedLiteralValue } from \"../cst/names.js\";\nimport { MessageSyntaxError } from \"../errors.js\";\nconst bidiChars = new Set('\\u061C\\u200E\\u200F\\u2066\\u2067\\u2068\\u2069');\nconst whitespaceChars = new Set('\\t\\n\\r \\u3000');\n//// Parser State ////\nlet pos;\nlet source;\n//// Utilities & Error Wrappers ////\n// These indirections allow for the function names to be mangled,\n// while keeping the error class name intact.\nconst MissingSyntax = (pos, expected) => new MessageSyntaxError('missing-syntax', pos, pos + expected.length, expected);\nconst SyntaxError = (...args) => new MessageSyntaxError(...args);\nfunction expect(searchString, consume) {\n if (source.startsWith(searchString, pos)) {\n if (consume)\n pos += searchString.length;\n }\n else {\n throw MissingSyntax(pos, searchString);\n }\n}\nexport function parseMessage(source_) {\n pos = 0;\n source = source_;\n const decl = declarations();\n if (source.startsWith('.match', pos))\n return selectMessage(decl);\n const quoted = decl.length > 0 || source.startsWith('{{', pos);\n if (!quoted && pos > 0)\n pos = 0;\n const pattern_ = pattern(quoted);\n if (quoted) {\n ws();\n if (pos < source.length) {\n throw SyntaxError('extra-content', pos, source.length);\n }\n }\n return { type: 'message', declarations: decl, pattern: pattern_ };\n}\nfunction selectMessage(declarations) {\n pos += 6; // '.match'\n ws(true);\n const selectors = [];\n while (source[pos] === '$') {\n selectors.push(variable());\n ws(true);\n }\n if (selectors.length === 0)\n throw SyntaxError('empty-token', pos);\n const variants = [];\n while (pos < source.length) {\n variants.push(variant());\n ws();\n }\n return { type: 'select', declarations, selectors, variants };\n}\nfunction variant() {\n const keys = [];\n while (pos < source.length) {\n ws(keys.length ? '{' : false);\n const next = source[pos];\n if (next === '{')\n break;\n if (next === '*') {\n keys.push({ type: '*' });\n pos += 1;\n }\n else {\n const key = literal(true);\n key.value = key.value.normalize();\n keys.push(key);\n }\n }\n return { keys, value: pattern(true) };\n}\nfunction pattern(quoted) {\n if (quoted) {\n if (source.startsWith('{{', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '{{');\n }\n const pattern = [];\n loop: while (pos < source.length) {\n switch (source[pos]) {\n case '{': {\n pattern.push(expression(true));\n break;\n }\n case '}':\n if (!quoted)\n throw SyntaxError('parse-error', pos);\n break loop;\n default: {\n pattern.push(text());\n }\n }\n }\n if (quoted) {\n if (source.startsWith('}}', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '}}');\n }\n return pattern;\n}\nfunction declarations() {\n const declarations = [];\n ws();\n loop: while (source[pos] === '.') {\n const keyword = source.substr(pos, 6);\n switch (keyword) {\n case '.input':\n declarations.push(inputDeclaration());\n break;\n case '.local':\n declarations.push(localDeclaration());\n break;\n case '.match':\n break loop;\n default:\n throw SyntaxError('parse-error', pos);\n }\n ws();\n }\n return declarations;\n}\nfunction inputDeclaration() {\n pos += 6; // '.input'\n ws();\n expect('{', false);\n const valueStart = pos;\n const value = expression(false);\n if (value.type === 'expression' && value.arg?.type === 'variable') {\n // @ts-expect-error TS isn't catching that value is Expression<VariableRef>\n return { type: 'input', name: value.arg.name, value };\n }\n throw SyntaxError('bad-input-expression', valueStart, pos);\n}\nfunction localDeclaration() {\n pos += 6; // '.local'\n ws(true);\n expect('$', true);\n const name_ = name();\n ws();\n expect('=', true);\n ws();\n expect('{', false);\n const value = expression(false);\n return { type: 'local', name: name_, value };\n}\nfunction expression(allowMarkup) {\n const start = pos;\n pos += 1; // '{'\n ws();\n const arg = value(false);\n if (arg)\n ws('}');\n const sigil = source[pos];\n let functionRef;\n let markup;\n switch (sigil) {\n case '@':\n case '}':\n break;\n case ':': {\n pos += 1; // ':'\n functionRef = { type: 'function', name: identifier() };\n const options_ = options();\n if (options_)\n functionRef.options = options_;\n break;\n }\n case '#':\n case '/': {\n if (arg || !allowMarkup)\n throw SyntaxError('parse-error', pos);\n pos += 1; // '#' or '/'\n const kind = sigil === '#' ? 'open' : 'close';\n markup = { type: 'markup', kind, name: identifier() };\n const options_ = options();\n if (options_)\n markup.options = options_;\n break;\n }\n default:\n throw SyntaxError('parse-error', pos);\n }\n const attributes_ = attributes();\n if (markup?.kind === 'open' && source[pos] === '/') {\n markup.kind = 'standalone';\n pos += 1; // '/'\n }\n expect('}', true);\n if (functionRef) {\n const exp = arg\n ? { type: 'expression', arg, functionRef: functionRef }\n : { type: 'expression', functionRef: functionRef };\n if (attributes_)\n exp.attributes = attributes_;\n return exp;\n }\n if (markup) {\n if (attributes_)\n markup.attributes = attributes_;\n return markup;\n }\n if (!arg)\n throw SyntaxError('empty-token', start, pos);\n return attributes_\n ? { type: 'expression', arg, attributes: attributes_ }\n : { type: 'expression', arg };\n}\n/** Requires and consumes leading and trailing whitespace. */\nfunction options() {\n ws('/}');\n const options = {};\n let isEmpty = true;\n while (pos < source.length) {\n const next = source[pos];\n if (next === '@' || next === '/' || next === '}')\n break;\n const start = pos;\n const name_ = identifier();\n if (Object.hasOwn(options, name_)) {\n throw SyntaxError('duplicate-option-name', start, pos);\n }\n ws();\n expect('=', true);\n ws();\n options[name_] = value(true);\n isEmpty = false;\n ws('/}');\n }\n return isEmpty ? null : options;\n}\nfunction attributes() {\n const attributes = {};\n let isEmpty = true;\n while (source[pos] === '@') {\n const start = pos;\n pos += 1; // '@'\n const name_ = identifier();\n if (Object.hasOwn(attributes, name_)) {\n throw SyntaxError('duplicate-attribute', start, pos);\n }\n ws('=/}');\n if (source[pos] === '=') {\n pos += 1; // '='\n ws();\n attributes[name_] = literal(true);\n ws('/}');\n }\n else {\n attributes[name_] = true;\n }\n isEmpty = false;\n }\n return isEmpty ? null : attributes;\n}\nfunction text() {\n let value = '';\n let i = pos;\n loop: for (; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '{':\n case '}':\n break loop;\n }\n }\n value += source.substring(pos, i);\n pos = i;\n return value;\n}\nfunction value(required) {\n return source[pos] === '$' ? variable() : literal(required);\n}\nfunction variable() {\n pos += 1; // '$'\n return { type: 'variable', name: name() };\n}\nfunction literal(required) {\n if (source[pos] === '|')\n return quotedLiteral();\n const value = parseUnquotedLiteralValue(source, pos);\n if (!value) {\n if (required)\n throw SyntaxError('empty-token', pos);\n else\n return undefined;\n }\n pos += value.length;\n return { type: 'literal', value };\n}\nfunction quotedLiteral() {\n pos += 1; // '|'\n let value = '';\n for (let i = pos; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '|':\n value += source.substring(pos, i);\n pos = i + 1;\n return { type: 'literal', value };\n }\n }\n throw MissingSyntax(source.length, '|');\n}\nfunction identifier() {\n const name_ = name();\n if (source[pos] === ':') {\n pos += 1;\n return name_ + ':' + name();\n }\n return name_;\n}\nfunction name() {\n const name = parseNameValue(source, pos);\n if (!name)\n throw SyntaxError('empty-token', pos);\n pos = name.end;\n return name.value;\n}\nfunction ws(req = false) {\n let next = source[pos];\n let hasWS = false;\n if (req) {\n while (bidiChars.has(next))\n next = source[++pos];\n while (whitespaceChars.has(next)) {\n next = source[++pos];\n hasWS = true;\n }\n }\n while (bidiChars.has(next) || whitespaceChars.has(next))\n next = source[++pos];\n if (req && !hasWS && (req === true || !req.includes(source[pos]))) {\n throw MissingSyntax(pos, \"' '\");\n }\n}\n","/**\n * Apply visitor functions to message nodes.\n *\n * The visitors are applied in source order, starting from the root.\n * Visitors for nodes that contain other nodes may return a callback function\n * that will be called with no arguments when exiting the node.\n *\n * If set, the `node` visitor is called for all {@link Node} values\n * for which an explicit visitor is not defined.\n *\n * Many visitors will be called with additional arguments\n * identifying some of the context for the visited node.\n *\n * @category Message Data Model\n */\nexport function visit(msg, visitors) {\n const { node, pattern } = visitors;\n const { functionRef = node, attributes = null, declaration = node, expression = node, key = node, markup = node, options = null, value = node, variant = node } = visitors;\n const handleOptions = (options_, context) => {\n if (options_) {\n const end = options?.(options_, context);\n if (value) {\n for (const value_ of Object.values(options_)) {\n value(value_, context, 'option');\n }\n }\n end?.();\n }\n };\n const handleAttributes = (attributes_, context) => {\n if (attributes_) {\n const end = attributes?.(attributes_, context);\n if (value) {\n for (const value_ of Object.values(attributes_)) {\n if (value_ !== true)\n value(value_, context, 'attribute');\n }\n }\n end?.();\n }\n };\n const handleElement = (exp, context) => {\n if (typeof exp === 'object') {\n let end;\n switch (exp.type) {\n case 'expression': {\n end = expression?.(exp, context);\n if (exp.arg)\n value?.(exp.arg, context, 'arg');\n if (exp.functionRef) {\n const endA = functionRef?.(exp.functionRef, context, exp.arg);\n handleOptions(exp.functionRef.options, context);\n endA?.();\n }\n handleAttributes(exp.attributes, context);\n break;\n }\n case 'markup': {\n end = markup?.(exp, context);\n handleOptions(exp.options, context);\n handleAttributes(exp.attributes, context);\n break;\n }\n }\n end?.();\n }\n };\n const handlePattern = (pat) => {\n const end = pattern?.(pat);\n for (const el of pat)\n handleElement(el, 'placeholder');\n end?.();\n };\n for (const decl of msg.declarations) {\n const end = declaration?.(decl);\n if (decl.value)\n handleElement(decl.value, 'declaration');\n end?.();\n }\n if (msg.type === 'message') {\n handlePattern(msg.pattern);\n }\n else {\n if (value)\n for (const sel of msg.selectors)\n value(sel, 'selector', 'arg');\n for (const vari of msg.variants) {\n const end = variant?.(vari);\n if (key)\n vari.keys.forEach(key);\n handlePattern(vari.value);\n end?.();\n }\n }\n}\n","import { MessageDataModelError } from \"../errors.js\";\nimport { visit } from \"./visit.js\";\n/**\n * Ensure that the `msg` data model is _valid_, calling `onError` on errors.\n * If `onError` is not defined, a {@link MessageDataModelError} will be thrown on error.\n *\n * Detects the following errors:\n *\n * - `'key-mismatch'`: **Variant Key Mismatch**<br>\n * The number of keys on a _variant_ does not equal the number of _selectors_.\n *\n * - `'missing-fallback'`: **Missing Fallback Variant**<br>\n * The message does not include a _variant_ with only catch-all keys.\n *\n * - `'missing-selector-annotation'`: **Missing Selector Annotation**<br>\n * A _selector_ does not contains a _variable_ that directly or indirectly\n * reference a _declaration_ with a _function_.\n *\n * - `'duplicate-declaration'`: **Duplicate Declaration**<br>\n * A _variable_ appears in two _declarations_.\n *\n * - `'duplicate-variant'`: **Duplicate Variant**<br>\n * The same list of _keys_ is used for more than one _variant_.\n *\n * @category Message Data Model\n * @returns The sets of runtime `functions` and `variables` used by the message.\n */\nexport function validate(msg, onError = (type, node) => {\n throw new MessageDataModelError(type, node);\n}) {\n let selectorCount = 0;\n let missingFallback = null;\n /** Tracks directly & indirectly annotated variables for `missing-selector-annotation` */\n const annotated = new Set();\n /** Tracks declared variables for `duplicate-declaration` */\n const declared = new Set();\n const functions = new Set();\n const localVars = new Set();\n const variables = new Set();\n const variants = new Set();\n let setArgAsDeclared = true;\n visit(msg, {\n declaration(decl) {\n // Skip all ReservedStatement\n if (!decl.name)\n return undefined;\n if (decl.value.functionRef ||\n (decl.type === 'local' &&\n decl.value.arg?.type === 'variable' &&\n annotated.has(decl.value.arg.name))) {\n annotated.add(decl.name);\n }\n if (decl.type === 'local')\n localVars.add(decl.name);\n setArgAsDeclared = decl.type === 'local';\n return () => {\n if (declared.has(decl.name))\n onError('duplicate-declaration', decl);\n else\n declared.add(decl.name);\n };\n },\n expression({ functionRef }) {\n if (functionRef)\n functions.add(functionRef.name);\n },\n value(value, context, position) {\n if (value.type !== 'variable')\n return;\n variables.add(value.name);\n switch (context) {\n case 'declaration':\n if (position !== 'arg' || setArgAsDeclared) {\n declared.add(value.name);\n }\n break;\n case 'selector':\n selectorCount += 1;\n missingFallback = value;\n if (!annotated.has(value.name)) {\n onError('missing-selector-annotation', value);\n }\n }\n },\n variant(variant) {\n const { keys } = variant;\n if (keys.length !== selectorCount)\n onError('key-mismatch', variant);\n const strKeys = JSON.stringify(keys.map(key => (key.type === 'literal' ? key.value : 0)));\n if (variants.has(strKeys))\n onError('duplicate-variant', variant);\n else\n variants.add(strKeys);\n missingFallback &&= keys.every(key => key.type === '*') ? null : variant;\n }\n });\n if (missingFallback)\n onError('missing-fallback', missingFallback);\n for (const lv of localVars)\n variables.delete(lv);\n return { functions, variables };\n}\n","export const LRI = '\\u2066';\nexport const RLI = '\\u2067';\nexport const FSI = '\\u2068';\nexport const PDI = '\\u2069';\n// Data source: RECOMMENDED and LIMITED_USE scripts from\n// https://github.com/unicode-org/cldr/blob/1a914d1/common/properties/scriptMetadata.txt\nconst RTL = 'Adlm,Arab,Hebr,Mand,Nkoo,Rohg,Syrc,Thaa';\n/** Get a default text direction for `locale`. */\nexport function getLocaleDir(locale) {\n if (locale) {\n try {\n if (typeof locale === 'string')\n locale = new Intl.Locale(locale);\n // @ts-expect-error -- New feature, API changed during Stage 3\n const info = locale.getTextInfo?.() ?? locale.textInfo;\n if (info?.direction)\n return info.direction;\n const script = locale.maximize().script;\n if (script)\n return RTL.includes(script) ? 'rtl' : 'ltr';\n }\n catch {\n // Use 'auto' on error\n }\n }\n return 'auto';\n}\n","/**\n * Utility function for custom functions.\n * Cast a value as a Boolean,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts `'true'` and `'false'`.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asBoolean(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'boolean')\n return value;\n if (value && typeof value === 'object')\n value = String(value);\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n throw new RangeError('Not a boolean');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a non-negative integer,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts JSON string reprentations of integers.\n * Throws a `RangeError` for invalid inputs.\n *\n * The default functions use this to validate _digit size options_.\n */\nexport function asPositiveInteger(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (value && typeof value === 'object')\n value = String(value);\n if (typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value)) {\n value = Number(value);\n }\n if (typeof value === 'number' && value >= 0 && Number.isInteger(value)) {\n return value;\n }\n throw new RangeError('Not a positive integer');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a string,\n * unwrapping objects using their `valueOf()` methods.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asString(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'string')\n return value;\n if (value && typeof value === 'object')\n return String(value);\n throw new RangeError('Not a string');\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\nexport function readNumericOperand(value) {\n let options = undefined;\n if (typeof value === 'object') {\n const valueOf = value?.valueOf;\n if (typeof valueOf === 'function') {\n options = value.options;\n value = valueOf.call(value);\n }\n }\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value);\n }\n catch {\n // handled below\n }\n }\n if (typeof value !== 'bigint' && typeof value !== 'number') {\n throw new MessageFunctionError('bad-operand', 'Input is not numeric');\n }\n return { value, options };\n}\nexport function getMessageNumber(ctx, value, options, canSelect) {\n let { dir, locales } = ctx;\n // @ts-expect-error We may have been a bit naughty earlier.\n if (options.useGrouping === 'never')\n options.useGrouping = false;\n if (canSelect &&\n 'select' in options &&\n !ctx.literalOptionKeys.has('select')) {\n ctx.onError('bad-option', 'The option select may only be set by a literal value');\n canSelect = false;\n }\n let locale;\n let nf;\n let cat;\n let str;\n return {\n type: 'number',\n get dir() {\n if (dir == null) {\n locale ??= Intl.NumberFormat.supportedLocalesOf(locales, options)[0];\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n selectKey: canSelect\n ? keys => {\n let numVal = value;\n if (options.style === 'percent') {\n if (typeof numVal === 'bigint')\n numVal *= 100n;\n else\n numVal *= 100;\n }\n const str = String(numVal);\n if (keys.has(str))\n return str;\n if (options.select === 'exact')\n return null;\n const pluralOpt = options.select\n ? { ...options, select: undefined, type: options.select }\n : options;\n // Intl.PluralRules needs a number, not bigint\n cat ??= new Intl.PluralRules(locales, pluralOpt).select(Number(numVal));\n return keys.has(cat) ? cat : null;\n }\n : undefined,\n toParts() {\n nf ??= new Intl.NumberFormat(locales, options);\n const parts = nf.formatToParts(value);\n locale ??= nf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'number', dir, locale, parts }]\n : [{ type: 'number', locale, parts }];\n },\n toString() {\n nf ??= new Intl.NumberFormat(locales, options);\n str ??= nf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nexport function number(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = input.value;\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'roundingMode':\n case 'roundingPriority':\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :number option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\nexport function integer(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = Number.isFinite(input.value)\n ? Math.round(input.value)\n : input.value;\n const options = Object.assign({}, input.options, {\n //localeMatcher: ctx.localeMatcher,\n maximumFractionDigits: 0,\n minimumFractionDigits: undefined,\n minimumSignificantDigits: undefined,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :integer option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `currency` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `currency` property.\n *\n * @beta\n */\nexport function currency(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'currency'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'currency':\n case 'currencySign':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'currencyDisplay': {\n const strval = asString(optval);\n if (strval === 'never') {\n ctx.onError('unsupported-operation', 'Currency display \"never\" is not yet supported');\n }\n else {\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = strval;\n }\n break;\n }\n case 'fractionDigits': {\n const strval = asString(optval);\n if (strval === 'auto') {\n options.minimumFractionDigits = undefined;\n options.maximumFractionDigits = undefined;\n }\n else {\n const numval = asPositiveInteger(strval);\n options.minimumFractionDigits = numval;\n options.maximumFractionDigits = numval;\n }\n break;\n }\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n if (!options.currency) {\n throw new MessageFunctionError('bad-operand', 'A currency code is required for :currency');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asBoolean, asString } from \"./utils.js\";\nconst dateFieldsValues = new Set([\n 'weekday',\n 'day-weekday',\n 'month-day',\n 'month-day-weekday',\n 'year-month-day',\n 'year-month-day-weekday'\n]);\nconst dateLengthValues = new Set(['long', 'medium', 'short']);\nconst timePrecisionValues = new Set(['hour', 'minute', 'second']);\nconst timeZoneStyleValues = new Set(['long', 'short']);\n/**\n * The function `:datetime` is used to format a date/time value.\n * Its formatted result will always include both the date and the time, and optionally a timezone.\n *\n * @beta\n */\nexport const datetime = (ctx, options, operand) => dateTimeImplementation('datetime', ctx, options, operand);\n/**\n * The function `:date` is used to format the date portion of date/time values.\n *\n * @beta\n */\nexport const date = (ctx, options, operand) => dateTimeImplementation('date', ctx, options, operand);\n/**\n * The function `:time` is used to format the time portion of date/time values.\n * Its formatted result will always include the time, and optionally a timezone.\n *\n * @beta\n */\nexport const time = (ctx, options, operand) => dateTimeImplementation('time', ctx, options, operand);\nfunction dateTimeImplementation(functionName, ctx, exprOpt, operand) {\n const options = {\n localeMatcher: ctx.localeMatcher\n };\n let value = operand;\n if (typeof value === 'object' && value !== null) {\n const opt = value.options;\n if (opt) {\n options.calendar = opt.calendar;\n if (functionName !== 'date')\n options.hour12 = opt.hour12;\n options.timeZone = opt.timeZone;\n }\n if (typeof value.valueOf === 'function')\n value = value.valueOf();\n }\n switch (typeof value) {\n case 'number':\n case 'string':\n value = new Date(value);\n }\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new MessageFunctionError('bad-operand', 'Input is not a valid date');\n }\n // Override options\n if (exprOpt.calendar !== undefined) {\n try {\n options.calendar = asString(exprOpt.calendar);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} calendar option value`);\n }\n }\n if (exprOpt.hour12 !== undefined && functionName !== 'date') {\n try {\n options.hour12 = asBoolean(exprOpt.hour12);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} hour12 option value`);\n }\n }\n if (exprOpt.timeZone !== undefined) {\n let tz;\n try {\n tz = asString(exprOpt.timeZone);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} timeZone option value`);\n }\n if (tz === 'input') {\n if (options.timeZone === undefined) {\n ctx.onError('bad-operand', `Missing input timeZone value for :${functionName}`);\n }\n }\n else if (tz !== undefined) {\n if (options.timeZone !== undefined && tz !== options.timeZone) {\n // Use fallback value for expression\n throw new MessageFunctionError('bad-option', 'Time zone conversion is not supported');\n }\n options.timeZone = tz;\n }\n }\n // Date formatting options\n if (functionName !== 'time') {\n const dfName = functionName === 'date' ? 'fields' : 'dateFields';\n const dlName = functionName === 'date' ? 'length' : 'dateLength';\n const dateFieldsValue = readStringOption(ctx, exprOpt, dfName, dateFieldsValues) ??\n 'year-month-day';\n const dateLength = readStringOption(ctx, exprOpt, dlName, dateLengthValues);\n const dateFields = new Set(dateFieldsValue.split('-'));\n if (dateFields.has('year'))\n options.year = 'numeric';\n if (dateFields.has('month')) {\n options.month =\n dateLength === 'long'\n ? 'long'\n : dateLength === 'short'\n ? 'numeric'\n : 'short';\n }\n if (dateFields.has('day'))\n options.day = 'numeric';\n if (dateFields.has('weekday')) {\n options.weekday = dateLength === 'long' ? 'long' : 'short';\n }\n }\n // Time formatting options\n if (functionName !== 'date') {\n const tpName = functionName === 'time' ? 'precision' : 'timePrecision';\n switch (readStringOption(ctx, exprOpt, tpName, timePrecisionValues)) {\n case 'hour':\n options.hour = 'numeric';\n break;\n case 'second':\n options.hour = 'numeric';\n options.minute = 'numeric';\n options.second = 'numeric';\n break;\n default:\n options.hour = 'numeric';\n options.minute = 'numeric';\n }\n options.timeZoneName = readStringOption(ctx, exprOpt, 'timeZoneStyle', timeZoneStyleValues);\n }\n // Resolved value\n const dtf = new Intl.DateTimeFormat(ctx.locales, options);\n let dir = ctx.dir;\n let locale;\n let str;\n return {\n type: 'datetime',\n get dir() {\n if (dir == null) {\n locale ??= dtf.resolvedOptions().locale;\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n toParts() {\n const parts = dtf.formatToParts(value);\n locale ??= dtf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'datetime', dir, locale, parts }]\n : [{ type: 'datetime', locale, parts }];\n },\n toString() {\n str ??= dtf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nfunction readStringOption(ctx, options, name, allowed) {\n const value = options[name];\n if (value !== undefined) {\n try {\n const str = asString(value);\n if (allowed && !allowed.has(str))\n throw Error();\n return str;\n }\n catch {\n ctx.onError('bad-option', `Invalid value for ${name} option`);\n }\n }\n return undefined;\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { number, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger } from \"./utils.js\";\n/**\n * `offset` accepts a numeric value as input and adds or subtracts an integer value from it\n *\n * @beta\n */\nexport function offset(ctx, exprOpt, operand) {\n let { value, options } = readNumericOperand(operand);\n let add;\n try {\n add = 'add' in exprOpt ? asPositiveInteger(exprOpt.add) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.add} is not valid for :offset option add`);\n }\n let sub;\n try {\n sub = 'subtract' in exprOpt ? asPositiveInteger(exprOpt.subtract) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.subtract} is not valid for :offset option subtract`);\n }\n if (add < 0 === sub < 0) {\n const msg = 'Exactly one of \"add\" or \"subtract\" is required as an :offset option';\n throw new MessageFunctionError('bad-option', msg);\n }\n const delta = add < 0 ? -sub : add;\n if (typeof value === 'number')\n value += delta;\n else\n value += BigInt(delta);\n return number(ctx, {}, { valueOf: () => value, options });\n}\n","import { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * The function `:percent` is a selector and formatter for percent values.\n *\n * @beta\n */\nexport function percent(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'percent'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'roundingMode':\n case 'roundingPriority':\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :percent option ${name}`);\n }\n }\n return getMessageNumber(ctx, input.value, options, true);\n}\n","export function string(ctx, _options, operand) {\n const str = operand === undefined ? '' : String(operand);\n const selStr = str.normalize();\n return {\n type: 'string',\n dir: ctx.dir ?? 'auto',\n selectKey: keys => (keys.has(selStr) ? selStr : null),\n toParts() {\n const { dir } = ctx;\n const locale = ctx.locales[0];\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'string', dir, locale, value: str }]\n : [{ type: 'string', locale, value: str }];\n },\n toString: () => str,\n valueOf: () => str\n };\n}\n","import { MessageError, MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `unit` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `unit` property.\n *\n * @beta\n */\nexport function unit(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'unit'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'signDisplay':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'unit':\n case 'unitDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch (error) {\n if (error instanceof MessageError) {\n ctx.onError(error);\n }\n else {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n }\n if (!options.unit) {\n throw new MessageFunctionError('bad-operand', 'A unit identifier is required for :unit');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n","/**\n * Implementations for :number, :string, and other default functions,\n * along with some utilities for building custom function handlers.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgSrc, { functions: DraftFunctions });\n * ```\n *\n * @module\n */\nexport { getLocaleDir } from \"../dir-utils.js\";\nexport { asBoolean, asPositiveInteger, asString } from \"./utils.js\";\nimport { currency } from \"./currency.js\";\nimport { date, datetime, time } from \"./datetime.js\";\nimport { integer, number } from \"./number.js\";\nimport { offset } from \"./offset.js\";\nimport { percent } from \"./percent.js\";\nimport { string } from \"./string.js\";\nimport { unit } from \"./unit.js\";\n/**\n * Functions classified as REQUIRED by the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat specification}.\n */\nexport let DefaultFunctions = {\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-integer-function | :integer function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n integer,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-number-function | :number function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n number,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-offset-function | :offset function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n offset,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-string-function | :string function}.\n *\n * The `operand` must be a stringifiable value.\n * An `undefined` value is resolved as an empty string.\n */\n string\n};\nDefaultFunctions = Object.freeze(Object.assign(Object.create(null), DefaultFunctions));\n/**\n * Functions classified as DRAFT by the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat specification}.\n *\n * These are liable to change, and are **_not_** covered by any stability guarantee.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgsrc, { functions: DraftFunctions });\n * ```\n *\n * @beta\n */\nexport let DraftFunctions = {\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-currency-function | :currency function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `currency` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n currency,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-date-function | :date function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n date,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-datetime-function | :datetime function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n datetime,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-percent-function | :percent function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n percent,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-time-function | :time function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n time,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-unit-function | :unit function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `unit` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n unit\n};\nDraftFunctions = Object.freeze(Object.assign(Object.create(null), DraftFunctions));\n","export const BIDI_ISOLATE = Symbol('bidi-isolate');\n","export const fallback = (source = '�') => ({\n type: 'fallback',\n source,\n toParts: () => [{ type: 'fallback', source }],\n toString: () => `{${source}}`\n});\n","export const unknown = (source, input) => ({\n type: 'unknown',\n source,\n dir: 'auto',\n toParts: () => [{ type: 'unknown', value: input }],\n toString: () => String(input),\n valueOf: () => input\n});\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport class MessageFunctionContext {\n #ctx;\n #litKeys;\n #source;\n dir;\n id;\n constructor(ctx, source, options) {\n this.#ctx = ctx;\n this.#source = source;\n this.dir = undefined;\n const dirOpt = options && Object.hasOwn(options, 'u:dir') ? options['u:dir'] : undefined;\n if (dirOpt) {\n const dir = String(resolveValue(ctx, dirOpt));\n if (dir === 'ltr' || dir === 'rtl' || dir === 'auto') {\n this.dir = dir;\n }\n else if (dir !== 'inherit') {\n const error = new MessageFunctionError('bad-option', 'Unsupported value for u:dir option');\n error.source = getValueSource(dirOpt);\n ctx.onError(error);\n }\n }\n const idOpt = options && Object.hasOwn(options, 'u:id') ? options['u:id'] : undefined;\n this.id = idOpt ? String(resolveValue(ctx, idOpt)) : undefined;\n if (options) {\n this.#litKeys = new Set();\n for (const [key, value] of Object.entries(options)) {\n if (value.type === 'literal')\n this.#litKeys.add(key);\n }\n }\n }\n get literalOptionKeys() {\n return new Set(this.#litKeys);\n }\n get localeMatcher() {\n return this.#ctx.localeMatcher;\n }\n get locales() {\n return this.#ctx.locales.map(String);\n }\n onError(error, message) {\n let mfError;\n if (error instanceof MessageFunctionError) {\n mfError = error;\n }\n else if (typeof error === 'string' && typeof message === 'string') {\n mfError = new MessageFunctionError(error, message);\n }\n else {\n mfError = new MessageFunctionError('function-error', String(error));\n mfError.cause = error;\n }\n mfError.source = this.#source;\n this.#ctx.onError(mfError);\n }\n}\n","import { MessageError, MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { BIDI_ISOLATE } from \"../message-value.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function resolveFunctionRef(ctx, operand, { name, options }) {\n const fnSource = `:${name}`;\n const source = getValueSource(operand) ?? fnSource;\n try {\n const fnInput = operand ? [resolveValue(ctx, operand)] : [];\n const rf = ctx.functions[name];\n if (!rf) {\n throw new MessageResolutionError('unknown-function', `Unknown function ${fnSource}`, source);\n }\n const msgCtx = new MessageFunctionContext(ctx, source, options);\n const opt = resolveOptions(ctx, options);\n const res = rf(msgCtx, opt, ...fnInput);\n if (res === null ||\n typeof res !== 'object' ||\n typeof res.type !== 'string') {\n throw new MessageResolutionError('bad-function-result', `Function ${fnSource} did not return a MessageValue`, source);\n }\n const override = { source };\n if (msgCtx.dir) {\n override.dir = msgCtx.dir;\n override[BIDI_ISOLATE] = true;\n }\n if (msgCtx.id && typeof res.toParts === 'function') {\n override.toParts = () => {\n const parts = res.toParts();\n for (const part of parts)\n part.id = msgCtx.id;\n return parts;\n };\n }\n return { ...res, ...override };\n }\n catch (error) {\n ctx.onError(error instanceof MessageError\n ? error\n : new MessageResolutionError('bad-function-result', String(error), source, error));\n return fallback(source);\n }\n}\nfunction resolveOptions(ctx, options) {\n const opt = Object.create(null);\n if (options) {\n for (const [name, value] of Object.entries(options)) {\n if (!name.startsWith('u:'))\n opt[name] = resolveValue(ctx, value);\n }\n }\n return opt;\n}\n","import { string } from \"../functions/string.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveFunctionRef } from \"./resolve-function-ref.js\";\nimport { resolveVariableRef } from \"./resolve-variable.js\";\nexport function resolveExpression(ctx, { arg, functionRef }) {\n if (functionRef) {\n return resolveFunctionRef(ctx, arg, functionRef);\n }\n switch (arg?.type) {\n case 'literal': {\n const source = `|${arg.value}|`;\n const msgCtx = new MessageFunctionContext(ctx, source);\n const msgStr = string(msgCtx, {}, arg.value);\n msgStr.source = source;\n return msgStr;\n }\n case 'variable':\n return resolveVariableRef(ctx, arg);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported expression: ${arg?.type}`);\n }\n}\n","import { MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { unknown } from \"../functions/unknown.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveExpression } from \"./resolve-expression.js\";\n/**\n * Declarations aren't resolved until they're requierd,\n * and their resolution order matters for variable resolution.\n * This internal class is used to store any required data,\n * and to allow for `instanceof` detection.\n *\n * @internal\n */\nexport class UnresolvedExpression {\n expression;\n scope;\n constructor(expression, scope) {\n this.expression = expression;\n this.scope = scope;\n }\n}\nconst isScope = (scope) => scope !== null && (typeof scope === 'object' || typeof scope === 'function');\n/**\n * Looks for the longest matching `.` delimited starting substring of name.\n * @returns `undefined` if value not found\n */\nfunction getValue(scope, name) {\n if (isScope(scope)) {\n if (name in scope)\n return scope[name];\n const parts = name.split('.');\n for (let i = parts.length - 1; i > 0; --i) {\n const head = parts.slice(0, i).join('.');\n if (head in scope) {\n const tail = parts.slice(i).join('.');\n return getValue(scope[head], tail);\n }\n }\n for (const [key, value] of Object.entries(scope)) {\n if (key.normalize() === name)\n return value;\n }\n }\n return undefined;\n}\n/**\n * Get the raw value of a variable.\n * Resolves declarations as necessary\n *\n * @internal\n * @returns `unknown` or `any` for input values;\n * `MessageValue` for `.input` and `.local` declaration values.\n */\nexport function lookupVariableRef(ctx, { name }) {\n const value = getValue(ctx.scope, name);\n if (value === undefined) {\n const source = '$' + name;\n const msg = `Variable not available: ${source}`;\n ctx.onError(new MessageResolutionError('unresolved-variable', msg, source));\n }\n else if (value instanceof UnresolvedExpression) {\n const local = resolveExpression(value.scope ? { ...ctx, scope: value.scope } : ctx, value.expression);\n ctx.scope[name] = local;\n ctx.localVars.add(local);\n return local;\n }\n return value;\n}\nexport function resolveVariableRef(ctx, ref) {\n const source = '$' + ref.name;\n const value = lookupVariableRef(ctx, ref);\n if (value === undefined)\n return fallback(source);\n let type = typeof value;\n if (type === 'object') {\n const mv = value;\n if (mv.type === 'fallback')\n return fallback(source);\n if (ctx.localVars.has(mv)) {\n mv.source = source;\n return mv;\n }\n if (value instanceof Number)\n type = 'number';\n else if (value instanceof String)\n type = 'string';\n }\n let msgFn;\n switch (type) {\n case 'bigint':\n case 'number':\n msgFn = ctx.functions.number;\n break;\n case 'string':\n msgFn = ctx.functions.string;\n break;\n default:\n return unknown(source, value);\n }\n const msgCtx = new MessageFunctionContext(ctx, source);\n const mv = msgFn(msgCtx, {}, value);\n mv.source = source;\n return mv;\n}\n","import { lookupVariableRef } from \"./resolve-variable.js\";\nexport function resolveValue(ctx, value) {\n switch (value.type) {\n case 'literal':\n return value.value;\n case 'variable':\n return lookupVariableRef(ctx, value);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported value: ${value.type}`);\n }\n}\nexport function getValueSource(value) {\n switch (value?.type) {\n case 'literal':\n return ('|' + value.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('|', '\\\\|') + '|');\n case 'variable':\n return '$' + value.name;\n default:\n return undefined;\n }\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function formatMarkup(ctx, { kind, name, options }) {\n const part = { type: 'markup', kind, name };\n const entries = options ? Object.entries(options) : null;\n if (entries?.length) {\n part.options = {};\n for (const [name, value] of entries) {\n if (name === 'u:dir') {\n const error = new MessageFunctionError('bad-option', `The option ${name} is not valid for markup`);\n error.source = getValueSource(value);\n ctx.onError(error);\n }\n else {\n let rv = resolveValue(ctx, value);\n if (typeof rv === 'object' && typeof rv?.valueOf === 'function') {\n rv = rv.valueOf();\n }\n if (name === 'u:id')\n part.id = String(rv);\n else\n part.options[name] = rv;\n }\n }\n }\n return part;\n}\n","import { MessageResolutionError } from \"./errors.js\";\nimport { resolveVariableRef } from \"./resolve/resolve-variable.js\";\nexport function selectPattern(context, message) {\n if (message.type === 'message')\n return message.pattern;\n // message.type === 'select'\n const ctx = message.selectors.map(sel => {\n const selector = resolveVariableRef(context, sel);\n let selectKey;\n if (typeof selector.selectKey === 'function') {\n selectKey = selector.selectKey.bind(selector);\n }\n else {\n const msg = 'Selector does not support selection';\n context.onError(new MessageResolutionError('bad-selector', msg, selector.source));\n selectKey = () => null;\n }\n return {\n selectKey,\n source: selector.source,\n best: null,\n keys: null\n };\n });\n let candidates = message.variants;\n loop: for (let i = 0; i < ctx.length; ++i) {\n const sc = ctx[i];\n if (!sc.keys) {\n sc.keys = new Set();\n for (const { keys } of candidates) {\n const key = keys[i];\n if (!key)\n break loop; // key-mismatch error\n if (key.type !== '*')\n sc.keys.add(key.value);\n }\n }\n try {\n sc.best = sc.keys.size ? sc.selectKey(sc.keys) : null;\n }\n catch (error) {\n const msg = 'Selection failed';\n context.onError(new MessageResolutionError('bad-selector', msg, sc.source, error));\n sc.selectKey = () => null;\n sc.best = null;\n }\n // Leave out all candidate variants that aren't the best,\n // or only the catchall ones, if nothing else matches.\n candidates = candidates.filter(v => {\n const k = v.keys[i];\n if (k.type === '*')\n return sc.best == null;\n return sc.best === k.value;\n });\n // If we've run out of candidates,\n // drop the previous best key of the preceding selector,\n // reset all subsequent key sets,\n // and restart the loop.\n if (candidates.length === 0) {\n if (i === 0)\n break; // No match; should not happen\n const prev = ctx[i - 1];\n if (prev.best == null)\n prev.keys?.clear();\n else\n prev.keys?.delete(prev.best);\n for (let j = i; j < ctx.length; ++j)\n ctx[j].keys = null;\n candidates = message.variants;\n i = -1;\n }\n }\n const res = candidates[0];\n if (!res) {\n // This should not be possible with a valid message.\n const msg = 'No variant was selected!?';\n context.onError(new MessageResolutionError('no-match', msg, '.match'));\n return [];\n }\n return res.value;\n}\n","import { parseMessage } from \"./data-model/parse.js\";\nimport { validate } from \"./data-model/validate.js\";\nimport { FSI, LRI, PDI, RLI, getLocaleDir } from \"./dir-utils.js\";\nimport { MessageFunctionError } from \"./errors.js\";\nimport { DefaultFunctions } from \"./functions/index.js\";\nimport { BIDI_ISOLATE } from \"./message-value.js\";\nimport { formatMarkup } from \"./resolve/format-markup.js\";\nimport { resolveExpression } from \"./resolve/resolve-expression.js\";\nimport { UnresolvedExpression } from \"./resolve/resolve-variable.js\";\nimport { selectPattern } from \"./select-pattern.js\";\n/**\n * A message formatter for that implements the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat}\n * specification as well as the {@link https://github.com/tc39/proposal-intl-messageformat/ | TC39 Intl.MessageFormat proposal}.\n *\n * @category Formatting\n * @typeParam T - The `type` used by custom message functions, if any.\n * These extend the {@link DefaultFunctions | default functions}.\n * @typeParam P - The formatted-parts `type` used by any custom message values.\n */\nexport class MessageFormat {\n #bidiIsolation;\n #dir;\n #localeMatcher;\n #locales;\n #message;\n #functions;\n constructor(locales, source, options) {\n this.#bidiIsolation = options?.bidiIsolation !== 'none';\n this.#localeMatcher = options?.localeMatcher ?? 'best fit';\n this.#locales = Array.isArray(locales)\n ? locales.map(lc => new Intl.Locale(lc))\n : locales\n ? [new Intl.Locale(locales)]\n : [];\n this.#dir = options?.dir ?? getLocaleDir(this.#locales[0]);\n this.#message = typeof source === 'string' ? parseMessage(source) : source;\n validate(this.#message);\n this.#functions = options?.functions\n ? Object.assign(Object.create(null), DefaultFunctions, options.functions)\n : DefaultFunctions;\n }\n /**\n * Format a message to a string.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.format({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * 'Hello Kat, today is March 1, 2025'\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n format(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n let res = '';\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n res += elem;\n }\n else if (elem.type === 'markup') {\n // Handle errors, but discard results\n formatMarkup(ctx, elem);\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toString === 'function') {\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n res += pre + mv.toString() + PDI;\n }\n else {\n res += mv.toString();\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const errStr = `{${mv?.source ?? '�'}}`;\n res += this.#bidiIsolation ? FSI + errStr + PDI : errStr;\n }\n }\n }\n return res;\n }\n /**\n * Format a message to a sequence of parts.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.formatToParts({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * [\n * { type: 'text', value: 'Hello ' },\n * { type: 'bidiIsolation', value: '\\u2068' },\n * { type: 'string', locale: 'en', value: 'Kat' },\n * { type: 'bidiIsolation', value: '\\u2069' },\n * { type: 'text', value: ', today is ' },\n * {\n * type: 'datetime',\n * dir: 'ltr',\n * locale: 'en',\n * parts: [\n * { type: 'month', value: 'March' },\n * { type: 'literal', value: ' ' },\n * { type: 'day', value: '1' },\n * { type: 'literal', value: ', ' },\n * { type: 'year', value: '2025' }\n * ]\n * }\n * ]\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n formatToParts(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n const parts = [];\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n parts.push({ type: 'text', value: elem });\n }\n else if (elem.type === 'markup') {\n parts.push(formatMarkup(ctx, elem));\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toParts === 'function') {\n // Let's presume that parts that look like MessageNumberPart or MessageStringPart are such.\n const mp = mv.toParts();\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n parts.push({ type: 'bidiIsolation', value: pre }, ...mp, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(...mp);\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const fb = {\n type: 'fallback',\n source: mv?.source ?? '�'\n };\n if (this.#bidiIsolation) {\n parts.push({ type: 'bidiIsolation', value: FSI }, fb, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(fb);\n }\n }\n }\n }\n return parts;\n }\n #createContext(msgParams, onError = (error) => {\n // Emit warning for errors by default\n try {\n process.emitWarning(error);\n }\n catch {\n console.warn(error);\n }\n }) {\n const scope = { ...msgParams };\n for (const decl of this.#message.declarations) {\n scope[decl.name] = new UnresolvedExpression(decl.value, decl.type === 'input' ? (msgParams ?? {}) : undefined);\n }\n const ctx = {\n onError,\n localeMatcher: this.#localeMatcher,\n locales: this.#locales,\n localVars: new WeakSet(),\n functions: this.#functions,\n scope\n };\n return ctx;\n }\n}\n","import { MessageFormat } from \"messageformat\";\nimport { DraftFunctions } from \"messageformat/functions\";\nimport type { TranslateOptions } from \"./types\";\n\nconst cache = new Map<string, Map<string, MessageFormat<string, string>>>();\n\nfunction getOrCreateMessageFormat(\n\tlocale: string,\n\tkey: string,\n\tmessage: string\n): MessageFormat<string, string> {\n\tlet localeCache = cache.get(locale);\n\tif (!localeCache) {\n\t\tlocaleCache = new Map();\n\t\tcache.set(locale, localeCache);\n\t}\n\n\tlet mf = localeCache.get(key);\n\tif (mf) {\n\t\treturn mf;\n\t}\n\tmf = new MessageFormat([locale], message, { functions: DraftFunctions });\n\tlocaleCache.set(key, mf);\n\treturn mf;\n}\n\nexport function defaultTranslate(msg: string, options?: TranslateOptions): string {\n\tif (!options?.vars || Object.keys(options.vars).length === 0) {\n\t\treturn msg;\n\t}\n\n\tif (options.formatting === \"identity\") {\n\t\treturn msg;\n\t}\n\n\tconst { locale, vars } = options;\n\tconst mf = getOrCreateMessageFormat(locale, msg, msg);\n\n\treturn mf.format(vars, (error) => {\n\t\tconsole.warn(`[fanee] Failed to format message: ${error}`);\n\t});\n}\n","import type { FaneeState } from \"./types\";\nimport { defaultTranslate } from \"./translator\";\n\nexport function defaultState(): FaneeState {\n\treturn {\n\t\tresources: {},\n\t\tdefaultLocale: \"en\",\n\t\tcurrentLocale: \"en\",\n\t\tbaseNamespace: \"\",\n\t\tformatting: \"mf2\",\n\t\ttranslate: defaultTranslate,\n\t};\n}\n","import type {\n\tFaneeState,\n\tLocale,\n\tMessageKey,\n\tTranslateContext,\n\tTranslateFunction,\n\tTranslationsByLocale,\n\tNamespaceResources,\n\tBundleResources,\n} from \"./types\";\nimport { defaultState } from \"./state\";\n\n/** Sequenced runtime that processes plugin setup before translations are available. */\nexport class FaneeRuntime {\n\tprivate state: FaneeState;\n\tprivate queue: Promise<void>;\n\tprivate listeners: Set<(state: FaneeState) => void>;\n\n\tconstructor() {\n\t\tthis.state = defaultState();\n\t\tthis.queue = Promise.resolve();\n\t\tthis.listeners = new Set();\n\t}\n\n\tprivate notify() {\n\t\tconst s = this.state;\n\t\tfor (const fn of this.listeners) {\n\t\t\tfn(s);\n\t\t}\n\t}\n\n\t/**\n\t * Register a plugin function that transforms the runtime state.\n\t *\n\t * Plugins are executed sequentially (FIFO) in the order they are registered.\n\t * Each plugin receives the current {@link FaneeState} and may return a new state\n\t * (or a promise thereof). The entire chain must resolve before the runtime\n\t * is considered \"ready\" (see {@link ready}).\n\t *\n\t * @param fn - A plugin function receiving the current state.\n\t * @returns `this` for chaining.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.use((state) => ({ ...state, currentLocale: \"zh-CN\" }));\n\t * ```\n\t */\n\tuse(fn: (state: FaneeState) => FaneeState | Promise<FaneeState>): this {\n\t\tthis.queue = this.queue.then(async () => {\n\t\t\tthis.state = await fn(this.state);\n\t\t\tthis.notify();\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Shallow-merge a partial state patch into the current state.\n\t *\n\t * This operation is queued and runs after all previously registered plugins.\n\t * It is equivalent to a plugin that destructures the patch over the state.\n\t *\n\t * @param patch - A partial {@link FaneeState} whose properties override the current state.\n\t * @returns `this` for chaining.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.config({ defaultLocale: \"en\", formatting: \"mf2\" });\n\t * ```\n\t */\n\tconfig(patch: Partial<FaneeState>): this {\n\t\tthis.queue = this.queue.then(async () => {\n\t\t\tthis.state = { ...this.state, ...patch };\n\t\t\tthis.notify();\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * @internal\n\t * Makes the runtime thenable so callers can `await` plugin setup before\n\t * calling translation methods.\n\t *\n\t * @param onfulfilled - Handler for successful queue resolution.\n\t * @param onrejected - Handler for queue rejection.\n\t */\n\t// biome-ignore lint/suspicious/noThenProperty: intentional thenable for await support\n\tthen<TResult1 = void, TResult2 = never>(\n\t\tonfulfilled?: // biome-ignore lint/suspicious/noConfusingVoidType: matches Promise<void> queue resolution\n\t\t((value: void) => TResult1 | PromiseLike<TResult1>) | null,\n\t\tonrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n\t): Promise<TResult1 | TResult2> {\n\t\treturn this.queue.then(onfulfilled, onrejected);\n\t}\n\n\t/** Resolve locale + namespace from an optional context, falling back to the current state. */\n\tprivate resolveContext(context?: Partial<TranslateContext>) {\n\t\tconst { currentLocale, baseNamespace } = this.state;\n\n\t\tconst locale = context?.locale ?? currentLocale;\n\t\tconst ns = context?.namespace\n\t\t\t? baseNamespace\n\t\t\t\t? `${baseNamespace}:${context.namespace}`\n\t\t\t\t: context.namespace\n\t\t\t: baseNamespace;\n\n\t\treturn { locale, ns };\n\t}\n\n\t/**\n\t * Look up a message in the resource tree and (if vars are provided)\n\t * delegate to the configured formatter.\n\t */\n\tprivate localize(\n\t\tresources: NamespaceResources | undefined,\n\t\tlocale: Locale,\n\t\tkey: MessageKey,\n\t\tvars?: Record<string, unknown>\n\t): string {\n\t\tif (!resources) {\n\t\t\treturn key;\n\t\t}\n\n\t\tlet localeData = resources[locale];\n\t\tif (!localeData) {\n\t\t\tlocaleData = resources[this.state.defaultLocale];\n\t\t\tif (!localeData) {\n\t\t\t\treturn key;\n\t\t\t}\n\t\t}\n\n\t\tconst value = localeData[key];\n\t\tif (value === undefined) {\n\t\t\treturn key;\n\t\t}\n\n\t\tif (vars === undefined || Object.keys(vars).length === 0) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn this.state.translate(value, {\n\t\t\tlocale,\n\t\t\tvars,\n\t\t\tformatting: this.state.formatting,\n\t\t});\n\t}\n\n\t/**\n\t * Translate a message key in the current locale and base namespace.\n\t *\n\t * Falls back through:\n\t * 1. {@link FaneeState.currentLocale Current locale}\n\t * 2. The {@link FaneeState.defaultLocale default locale}\n\t * 3. Returns the key itself if no translation is found\n\t *\n\t * @param key - The message key to translate.\n\t * @param vars - Optional variables for interpolation.\n\t * @returns The translated string, or `key` if no translation exists.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.t(\"hello\"); // \"你好\"\n\t * runtime.t(\"greeting\", { name: \"Alice\" }); // \"Hello, Alice\"\n\t * ```\n\t */\n\tt(key: MessageKey, vars?: Record<string, unknown>): string {\n\t\tconst { locale, ns } = this.resolveContext();\n\t\treturn this.localize(this.state.resources[ns], locale, key, vars);\n\t}\n\n\t/**\n\t * Return a bound translate function pinned to a specific locale/namespace.\n\t *\n\t * Unlike {@link t}, this method captures the locale and namespace at call time\n\t * so the returned function can be passed around (e.g. as a prop to a component)\n\t * without retaining a reference to the runtime.\n\t *\n\t * @param context - Optional overrides for locale and/or namespace.\n\t * If omitted, the current runtime values are captured.\n\t * @returns A function with the signature `(key, vars?) => string`.\n\t *\n\t * @example\n\t * ```ts\n\t * const t = runtime.getT({ locale: \"ja\", namespace: \"errors\" });\n\t * t(\"not_found\"); // \"見つかりませんでした\"\n\t * ```\n\t */\n\tgetT(context?: Partial<TranslateContext>): TranslateFunction {\n\t\tconst { locale, ns } = this.resolveContext(context);\n\t\tconst nsResources = this.state.resources[ns];\n\n\t\treturn (key: MessageKey, vars?: Record<string, unknown>): string =>\n\t\t\tthis.localize(nsResources, locale, key, vars);\n\t}\n\n\t/**\n\t * Translate a message key into every available locale within the base namespace.\n\t *\n\t * Useful for generating locale-switching UIs, SEO hreflang tags, or\n\t * pre-rendering all translations on the server.\n\t *\n\t * @param key - The message key to translate.\n\t * @param vars - Optional variables for interpolation (applied to every locale).\n\t * @returns A record mapping each locale to its translated string.\n\t * Returns an empty object if the base namespace has no resources.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.tAll(\"welcome\");\n\t * // { en: \"Welcome\", \"es\": \"Bienvenido\", \"fr\": \"Bienvenue\", \"zh-CN\": \"欢迎\", ja: \"ようこそ\" }\n\t * ```\n\t */\n\ttAll(key: MessageKey, vars?: Record<string, unknown>): TranslationsByLocale {\n\t\tconst { baseNamespace, resources } = this.state;\n\t\tconst nsResources = resources[baseNamespace];\n\t\tconst result: TranslationsByLocale = {};\n\n\t\tif (!nsResources) {\n\t\t\treturn result;\n\t\t}\n\n\t\tfor (const loc of Object.keys(nsResources)) {\n\t\t\tresult[loc as Locale] = this.localize(nsResources, loc as Locale, key, vars);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get the currently active locale.\n\t *\n\t * @returns The BCP 47 tag of the active locale (e.g. `\"en\"`, `\"zh-CN\"`).\n\t */\n\tgetLocale(): Locale {\n\t\treturn this.state.currentLocale;\n\t}\n\n\t/**\n\t * Collect every unique locale present across all loaded namespaces.\n\t *\n\t * @returns A sorted array of locale tags. Returns an empty array if no\n\t * resources have been loaded.\n\t */\n\tgetLocales(): Locale[] {\n\t\tconst locales = new Set<Locale>();\n\t\tfor (const resource of Object.values(this.state.resources)) {\n\t\t\tfor (const locale of Object.keys(resource)) {\n\t\t\t\tlocales.add(locale as Locale);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(locales).sort();\n\t}\n\n\t/**\n\t * Return the complete resource tree.\n\t *\n\t * @returns The full {@link BundleResources} object (namespace → locale → messages).\n\t */\n\tgetAllTranslations(): BundleResources {\n\t\treturn this.state.resources;\n\t}\n\n\t/**\n\t * Return resources for a single namespace.\n\t *\n\t * @param ns - The namespace to look up.\n\t * @returns The locale-indexed messages for that namespace, or `undefined`\n\t * if the namespace has not been loaded.\n\t */\n\tgetTranslationsForNamespace(ns: string): NamespaceResources | undefined {\n\t\treturn this.state.resources[ns];\n\t}\n\n\t/**\n\t * Wait for all queued plugins to finish.\n\t *\n\t * Because plugin registration and configuration are queued as a promise chain,\n\t * you must `await runtime.ready()` (or `await runtime` directly) before calling\n\t * translation methods if any plugin is asynchronous.\n\t *\n\t * @returns A promise that resolves once the plugin queue is empty.\n\t *\n\t * @example\n\t * ```ts\n\t * const runtime = new FaneeRuntime()\n\t * .use(asyncLoaderPlugin)\n\t * .config({ defaultLocale: \"en\" });\n\t *\n\t * await runtime.ready();\n\t * console.log(runtime.t(\"hello\")); // safe\n\t * ```\n\t */\n\tready(): Promise<void> {\n\t\treturn this.queue;\n\t}\n\n\t/**\n\t * Switch the active locale at runtime.\n\t *\n\t * This is a synchronous operation that updates the current locale instantly.\n\t * Subsequent calls to {@link t} and {@link getT} (without an explicit locale)\n\t * will use this new locale.\n\t *\n\t * @param locale - The BCP 47 tag of the target locale.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.setLocale(\"fr\");\n\t * runtime.t(\"hello\"); // \"Bonjour\"\n\t * ```\n\t */\n\tsetLocale(locale: Locale) {\n\t\tthis.state.currentLocale = locale;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Switch the base namespace at runtime.\n\t *\n\t * Subsequent calls to {@link t} and related methods will resolve keys against\n\t * this namespace. When a scoped namespace is set via {@link getT},\n\t * it is prefixed with the base namespace using `:` as separator.\n\t *\n\t * @param ns - The namespace to set as the base.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.setNamespace(\"admin\");\n\t * runtime.t(\"dashboard_title\"); // resolved from \"admin\" namespace\n\t * ```\n\t */\n\tsetNamespace(ns: string) {\n\t\tthis.state.baseNamespace = ns;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Subscribe to state changes.\n\t *\n\t * The callback is invoked synchronously whenever the runtime state is mutated\n\t * (via {@link setLocale}, {@link setNamespace}, or after a queued\n\t * {@link use} / {@link config} operation resolves).\n\t *\n\t * @param callback - Called with the current {@link FaneeState} on every change.\n\t * @returns An unsubscribe function. Call it to stop receiving notifications.\n\t *\n\t * @example\n\t * ```ts\n\t * const unsub = runtime.subscribe((state) => {\n\t * console.log(\"locale changed to\", state.currentLocale);\n\t * });\n\t *\n\t * runtime.setLocale(\"fr\"); // logs \"locale changed to fr\"\n\t * unsub();\n\t * ```\n\t */\n\tsubscribe(callback: (state: FaneeState) => void): () => void {\n\t\tthis.listeners.add(callback);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(callback);\n\t\t};\n\t}\n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BAAe,aAAc,KAAK,MACpC,EAAc,EAAU,GACxB,EAA+B,CAAC,EAEtC,GAAI,CAAC,EACJ,OAAO,EAGR,IAAK,IAAM,KAAO,OAAO,KAAK,CAAW,EACxC,EAAO,GAAiB,KAAK,SAAS,EAAa,EAAe,EAAK,CAAI,EAG5E,OAAO,CACR,CAOA,WAAoB,CACnB,OAAO,KAAK,MAAM,aACnB,CAQA,YAAuB,CACtB,IAAM,EAAU,IAAI,IACpB,IAAK,IAAM,KAAY,OAAO,OAAO,KAAK,MAAM,SAAS,EACxD,IAAK,IAAM,KAAU,OAAO,KAAK,CAAQ,EACxC,EAAQ,IAAI,CAAgB,EAG9B,OAAO,MAAM,KAAK,CAAO,CAAC,CAAC,KAAK,CACjC,CAOA,oBAAsC,CACrC,OAAO,KAAK,MAAM,SACnB,CASA,4BAA4B,EAA4C,CACvE,OAAO,KAAK,MAAM,UAAU,EAC7B,CAqBA,OAAuB,CACtB,OAAO,KAAK,KACb,CAiBA,UAAU,EAAgB,CACzB,KAAK,MAAM,cAAgB,EAC3B,KAAK,OAAO,CACb,CAiBA,aAAa,EAAY,CACxB,KAAK,MAAM,cAAgB,EAC3B,KAAK,OAAO,CACb,CAsBA,UAAU,EAAmD,CAE5D,OADA,KAAK,UAAU,IAAI,CAAQ,MACd,CACZ,KAAK,UAAU,OAAO,CAAQ,CAC/B,CACD,CACD,ECvWA,MAAa,GAAO,IAAI"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@fanee/core",
3
- "main": "dist/index.mjs",
4
- "module": "dist/index.mjs",
5
- "types": "dist/index.d.mts",
6
- "version": "0.5.0",
3
+ "main": "dist/index.js",
4
+ "module": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "version": "0.6.1",
7
7
  "type": "module",
8
8
  "private": false,
9
9
  "license": "MIT",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/runtime.ts","../src/i18n.ts"],"m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.mjs","names":["bidiChars","#ctx","#source","#litKeys","#bidiIsolation","#localeMatcher","#locales","#dir","#message","#functions","#createContext"],"sources":["../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/cst/names.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/from-cst.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/errors.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/parse.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/visit.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/data-model/validate.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/dir-utils.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/utils.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/number.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/currency.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/datetime.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/offset.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/percent.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/string.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/unit.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/index.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/message-value.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/fallback.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/functions/unknown.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/function-context.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-function-ref.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-expression.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-variable.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-value.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/resolve/format-markup.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/select-pattern.js","../../../node_modules/.bun/messageformat@4.0.0/node_modules/messageformat/lib/messageformat.js","../src/translator.ts","../src/state.ts","../src/runtime.ts","../src/i18n.ts"],"sourcesContent":["const bidiChars = /^[\\u061c\\u200e\\u200f\\u2066-\\u2069]+/;\nconst nameChars = /^[-.+0-9A-Z_a-z\\u{a1}-\\u{61b}\\u{61d}-\\u{167f}\\u{1681}-\\u{1fff}\\u{200b}-\\u{200d}\\u{2010}-\\u{2027}\\u{2030}-\\u{205e}\\u{2060}-\\u{2065}\\u{206a}-\\u{2fff}\\u{3001}-\\u{d7ff}\\u{e000}-\\u{fdcf}\\u{fdf0}-\\u{fffd}\\u{10000}-\\u{1fffd}\\u{20000}-\\u{2fffd}\\u{30000}-\\u{3fffd}\\u{40000}-\\u{4fffd}\\u{50000}-\\u{5fffd}\\u{60000}-\\u{6fffd}\\u{70000}-\\u{7fffd}\\u{80000}-\\u{8fffd}\\u{90000}-\\u{9fffd}\\u{a0000}-\\u{afffd}\\u{b0000}-\\u{bfffd}\\u{c0000}-\\u{cfffd}\\u{d0000}-\\u{dfffd}\\u{e0000}-\\u{efffd}\\u{f0000}-\\u{ffffd}\\u{100000}-\\u{10fffd}]+/u;\nconst notNameStart = /^[-.0-9]/;\nexport function parseNameValue(source, start) {\n let pos = start;\n const startBidi = source.slice(pos).match(bidiChars);\n if (startBidi)\n pos += startBidi[0].length;\n const match = source.slice(pos).match(nameChars);\n if (!match)\n return null;\n const name = match[0];\n if (notNameStart.test(name))\n return null;\n pos += name.length;\n const endBidi = source.slice(pos).match(bidiChars);\n if (endBidi)\n pos += endBidi[0].length;\n return { value: name.normalize(), end: pos };\n}\nexport function isValidUnquotedLiteral(str) {\n const match = str.match(nameChars);\n return !!match && match[0].length === str.length;\n}\nexport const parseUnquotedLiteralValue = (source, start) => source.slice(start).match(nameChars)?.[0] ?? '';\n","import { MessageSyntaxError } from \"../errors.js\";\n/**\n * Shared symbol used as a key on message data model nodes\n * to reference their CST source.\n *\n * Only set on message data model nodes when parsed by {@link messageFromCST}.\n */\nexport const cstKey = Symbol.for('CST');\n/**\n * Convert a CST message structure into its data model representation.\n *\n * In the returned {@link Model.Message},\n * all nodes include a reference to their source {@link CST} node\n * as a {@link cstKey} symbol-keyed property.\n */\nexport function messageFromCST(msg) {\n for (const error of msg.errors)\n throw error;\n const declarations = msg.declarations\n ? msg.declarations.map(asDeclaration)\n : [];\n if (msg.type === 'select') {\n return {\n type: 'select',\n declarations,\n selectors: msg.selectors.map(sel => asValue(sel)),\n variants: msg.variants.map(variant => ({\n keys: variant.keys.map(key => key.type === '*' ? { type: '*', [cstKey]: key } : asValue(key)),\n value: asPattern(variant.value),\n [cstKey]: variant\n })),\n [cstKey]: msg\n };\n }\n else {\n return {\n type: 'message',\n declarations,\n pattern: asPattern(msg.pattern),\n [cstKey]: msg\n };\n }\n}\nfunction asDeclaration(decl) {\n switch (decl.type) {\n case 'input': {\n const value = asExpression(decl.value, false);\n if (value.arg?.type !== 'variable') {\n const { start, end } = decl.value;\n throw new MessageSyntaxError('parse-error', start, end);\n }\n return {\n type: 'input',\n name: value.arg.name,\n value: value,\n [cstKey]: decl\n };\n }\n case 'local':\n return {\n type: 'local',\n name: asValue(decl.target).name,\n value: asExpression(decl.value, false),\n [cstKey]: decl\n };\n default:\n throw new MessageSyntaxError('parse-error', decl.start, decl.end);\n }\n}\nconst asPattern = (pattern) => pattern.body.map(el => el.type === 'text' ? el.value : asExpression(el, true));\nfunction asExpression(exp, allowMarkup) {\n if (exp.type === 'expression') {\n if (allowMarkup && exp.markup) {\n const cm = exp.markup;\n const name = asName(cm.name);\n const kind = cm.open.value === '/' ? 'close' : cm.close ? 'standalone' : 'open';\n const markup = { type: 'markup', kind, name };\n if (cm.options.length)\n markup.options = asOptions(cm.options);\n if (exp.attributes.length) {\n markup.attributes = asAttributes(exp.attributes);\n }\n markup[cstKey] = exp;\n return markup;\n }\n const arg = exp.arg ? asValue(exp.arg) : undefined;\n let functionRef;\n const ca = exp.functionRef;\n if (ca) {\n if (ca.type === 'function') {\n functionRef = { type: 'function', name: asName(ca.name) };\n if (ca.options.length)\n functionRef.options = asOptions(ca.options);\n }\n else {\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n }\n }\n let expression = arg\n ? { type: 'expression', arg }\n : undefined;\n if (functionRef) {\n functionRef[cstKey] = ca;\n if (expression)\n expression.functionRef = functionRef;\n else\n expression = { type: 'expression', functionRef: functionRef };\n }\n if (expression) {\n if (exp.attributes.length) {\n expression.attributes = asAttributes(exp.attributes);\n }\n expression[cstKey] = exp;\n return expression;\n }\n }\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n}\nfunction asOptions(options) {\n const map = {};\n for (const opt of options) {\n const name = asName(opt.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-option-name', opt.start, opt.end);\n }\n map[name] = asValue(opt.value);\n }\n return map;\n}\nfunction asAttributes(attributes) {\n const map = {};\n for (const attr of attributes) {\n const name = asName(attr.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-attribute', attr.start, attr.end);\n }\n map[name] = attr.value ? asValue(attr.value) : true;\n }\n return map;\n}\nfunction asName(id) {\n switch (id.length) {\n case 1:\n return id[0].value;\n case 3:\n return `${id[0].value}:${id[2].value}`;\n default:\n throw new MessageSyntaxError('parse-error', id[0]?.start ?? -1, id.at(-1)?.end ?? -1);\n }\n}\nfunction asValue(value) {\n switch (value.type) {\n case 'literal':\n return { type: 'literal', value: value.value, [cstKey]: value };\n case 'variable':\n return { type: 'variable', name: value.name, [cstKey]: value };\n default:\n throw new MessageSyntaxError('parse-error', value.start, value.end);\n }\n}\n","import { cstKey } from \"./data-model/from-cst.js\";\n/**\n * Base error class used by MessageFormat\n *\n * @category Errors\n */\nexport class MessageError extends Error {\n type;\n constructor(type, message) {\n super(message);\n this.type = type;\n }\n}\n/**\n * Errors in the message syntax.\n *\n * @category Errors\n */\nexport class MessageSyntaxError extends MessageError {\n start;\n end;\n /** @private */\n constructor(type, start, end, expected) {\n let message = expected ? `Missing ${expected}` : type;\n if (start >= 0)\n message += ` at ${start}`;\n super(type, message);\n this.start = start;\n this.end = end ?? start + 1;\n }\n}\n/**\n * Errors in the message data model.\n *\n * @category Errors\n */\nexport class MessageDataModelError extends MessageSyntaxError {\n /** @private */\n constructor(type, node) {\n const { start, end } = node[cstKey] ?? { start: -1, end: -1 };\n super(type, start, end);\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageResolutionError extends MessageError {\n source;\n cause;\n constructor(type, message, source, cause) {\n super(type, message);\n this.source = source;\n if (cause !== undefined)\n this.cause = cause;\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageFunctionError extends MessageError {\n source;\n cause;\n constructor(type, message) {\n super(type, message);\n this.source = '�';\n }\n}\n","import { parseNameValue, parseUnquotedLiteralValue } from \"../cst/names.js\";\nimport { MessageSyntaxError } from \"../errors.js\";\nconst bidiChars = new Set('\\u061C\\u200E\\u200F\\u2066\\u2067\\u2068\\u2069');\nconst whitespaceChars = new Set('\\t\\n\\r \\u3000');\n//// Parser State ////\nlet pos;\nlet source;\n//// Utilities & Error Wrappers ////\n// These indirections allow for the function names to be mangled,\n// while keeping the error class name intact.\nconst MissingSyntax = (pos, expected) => new MessageSyntaxError('missing-syntax', pos, pos + expected.length, expected);\nconst SyntaxError = (...args) => new MessageSyntaxError(...args);\nfunction expect(searchString, consume) {\n if (source.startsWith(searchString, pos)) {\n if (consume)\n pos += searchString.length;\n }\n else {\n throw MissingSyntax(pos, searchString);\n }\n}\nexport function parseMessage(source_) {\n pos = 0;\n source = source_;\n const decl = declarations();\n if (source.startsWith('.match', pos))\n return selectMessage(decl);\n const quoted = decl.length > 0 || source.startsWith('{{', pos);\n if (!quoted && pos > 0)\n pos = 0;\n const pattern_ = pattern(quoted);\n if (quoted) {\n ws();\n if (pos < source.length) {\n throw SyntaxError('extra-content', pos, source.length);\n }\n }\n return { type: 'message', declarations: decl, pattern: pattern_ };\n}\nfunction selectMessage(declarations) {\n pos += 6; // '.match'\n ws(true);\n const selectors = [];\n while (source[pos] === '$') {\n selectors.push(variable());\n ws(true);\n }\n if (selectors.length === 0)\n throw SyntaxError('empty-token', pos);\n const variants = [];\n while (pos < source.length) {\n variants.push(variant());\n ws();\n }\n return { type: 'select', declarations, selectors, variants };\n}\nfunction variant() {\n const keys = [];\n while (pos < source.length) {\n ws(keys.length ? '{' : false);\n const next = source[pos];\n if (next === '{')\n break;\n if (next === '*') {\n keys.push({ type: '*' });\n pos += 1;\n }\n else {\n const key = literal(true);\n key.value = key.value.normalize();\n keys.push(key);\n }\n }\n return { keys, value: pattern(true) };\n}\nfunction pattern(quoted) {\n if (quoted) {\n if (source.startsWith('{{', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '{{');\n }\n const pattern = [];\n loop: while (pos < source.length) {\n switch (source[pos]) {\n case '{': {\n pattern.push(expression(true));\n break;\n }\n case '}':\n if (!quoted)\n throw SyntaxError('parse-error', pos);\n break loop;\n default: {\n pattern.push(text());\n }\n }\n }\n if (quoted) {\n if (source.startsWith('}}', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '}}');\n }\n return pattern;\n}\nfunction declarations() {\n const declarations = [];\n ws();\n loop: while (source[pos] === '.') {\n const keyword = source.substr(pos, 6);\n switch (keyword) {\n case '.input':\n declarations.push(inputDeclaration());\n break;\n case '.local':\n declarations.push(localDeclaration());\n break;\n case '.match':\n break loop;\n default:\n throw SyntaxError('parse-error', pos);\n }\n ws();\n }\n return declarations;\n}\nfunction inputDeclaration() {\n pos += 6; // '.input'\n ws();\n expect('{', false);\n const valueStart = pos;\n const value = expression(false);\n if (value.type === 'expression' && value.arg?.type === 'variable') {\n // @ts-expect-error TS isn't catching that value is Expression<VariableRef>\n return { type: 'input', name: value.arg.name, value };\n }\n throw SyntaxError('bad-input-expression', valueStart, pos);\n}\nfunction localDeclaration() {\n pos += 6; // '.local'\n ws(true);\n expect('$', true);\n const name_ = name();\n ws();\n expect('=', true);\n ws();\n expect('{', false);\n const value = expression(false);\n return { type: 'local', name: name_, value };\n}\nfunction expression(allowMarkup) {\n const start = pos;\n pos += 1; // '{'\n ws();\n const arg = value(false);\n if (arg)\n ws('}');\n const sigil = source[pos];\n let functionRef;\n let markup;\n switch (sigil) {\n case '@':\n case '}':\n break;\n case ':': {\n pos += 1; // ':'\n functionRef = { type: 'function', name: identifier() };\n const options_ = options();\n if (options_)\n functionRef.options = options_;\n break;\n }\n case '#':\n case '/': {\n if (arg || !allowMarkup)\n throw SyntaxError('parse-error', pos);\n pos += 1; // '#' or '/'\n const kind = sigil === '#' ? 'open' : 'close';\n markup = { type: 'markup', kind, name: identifier() };\n const options_ = options();\n if (options_)\n markup.options = options_;\n break;\n }\n default:\n throw SyntaxError('parse-error', pos);\n }\n const attributes_ = attributes();\n if (markup?.kind === 'open' && source[pos] === '/') {\n markup.kind = 'standalone';\n pos += 1; // '/'\n }\n expect('}', true);\n if (functionRef) {\n const exp = arg\n ? { type: 'expression', arg, functionRef: functionRef }\n : { type: 'expression', functionRef: functionRef };\n if (attributes_)\n exp.attributes = attributes_;\n return exp;\n }\n if (markup) {\n if (attributes_)\n markup.attributes = attributes_;\n return markup;\n }\n if (!arg)\n throw SyntaxError('empty-token', start, pos);\n return attributes_\n ? { type: 'expression', arg, attributes: attributes_ }\n : { type: 'expression', arg };\n}\n/** Requires and consumes leading and trailing whitespace. */\nfunction options() {\n ws('/}');\n const options = {};\n let isEmpty = true;\n while (pos < source.length) {\n const next = source[pos];\n if (next === '@' || next === '/' || next === '}')\n break;\n const start = pos;\n const name_ = identifier();\n if (Object.hasOwn(options, name_)) {\n throw SyntaxError('duplicate-option-name', start, pos);\n }\n ws();\n expect('=', true);\n ws();\n options[name_] = value(true);\n isEmpty = false;\n ws('/}');\n }\n return isEmpty ? null : options;\n}\nfunction attributes() {\n const attributes = {};\n let isEmpty = true;\n while (source[pos] === '@') {\n const start = pos;\n pos += 1; // '@'\n const name_ = identifier();\n if (Object.hasOwn(attributes, name_)) {\n throw SyntaxError('duplicate-attribute', start, pos);\n }\n ws('=/}');\n if (source[pos] === '=') {\n pos += 1; // '='\n ws();\n attributes[name_] = literal(true);\n ws('/}');\n }\n else {\n attributes[name_] = true;\n }\n isEmpty = false;\n }\n return isEmpty ? null : attributes;\n}\nfunction text() {\n let value = '';\n let i = pos;\n loop: for (; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '{':\n case '}':\n break loop;\n }\n }\n value += source.substring(pos, i);\n pos = i;\n return value;\n}\nfunction value(required) {\n return source[pos] === '$' ? variable() : literal(required);\n}\nfunction variable() {\n pos += 1; // '$'\n return { type: 'variable', name: name() };\n}\nfunction literal(required) {\n if (source[pos] === '|')\n return quotedLiteral();\n const value = parseUnquotedLiteralValue(source, pos);\n if (!value) {\n if (required)\n throw SyntaxError('empty-token', pos);\n else\n return undefined;\n }\n pos += value.length;\n return { type: 'literal', value };\n}\nfunction quotedLiteral() {\n pos += 1; // '|'\n let value = '';\n for (let i = pos; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '|':\n value += source.substring(pos, i);\n pos = i + 1;\n return { type: 'literal', value };\n }\n }\n throw MissingSyntax(source.length, '|');\n}\nfunction identifier() {\n const name_ = name();\n if (source[pos] === ':') {\n pos += 1;\n return name_ + ':' + name();\n }\n return name_;\n}\nfunction name() {\n const name = parseNameValue(source, pos);\n if (!name)\n throw SyntaxError('empty-token', pos);\n pos = name.end;\n return name.value;\n}\nfunction ws(req = false) {\n let next = source[pos];\n let hasWS = false;\n if (req) {\n while (bidiChars.has(next))\n next = source[++pos];\n while (whitespaceChars.has(next)) {\n next = source[++pos];\n hasWS = true;\n }\n }\n while (bidiChars.has(next) || whitespaceChars.has(next))\n next = source[++pos];\n if (req && !hasWS && (req === true || !req.includes(source[pos]))) {\n throw MissingSyntax(pos, \"' '\");\n }\n}\n","/**\n * Apply visitor functions to message nodes.\n *\n * The visitors are applied in source order, starting from the root.\n * Visitors for nodes that contain other nodes may return a callback function\n * that will be called with no arguments when exiting the node.\n *\n * If set, the `node` visitor is called for all {@link Node} values\n * for which an explicit visitor is not defined.\n *\n * Many visitors will be called with additional arguments\n * identifying some of the context for the visited node.\n *\n * @category Message Data Model\n */\nexport function visit(msg, visitors) {\n const { node, pattern } = visitors;\n const { functionRef = node, attributes = null, declaration = node, expression = node, key = node, markup = node, options = null, value = node, variant = node } = visitors;\n const handleOptions = (options_, context) => {\n if (options_) {\n const end = options?.(options_, context);\n if (value) {\n for (const value_ of Object.values(options_)) {\n value(value_, context, 'option');\n }\n }\n end?.();\n }\n };\n const handleAttributes = (attributes_, context) => {\n if (attributes_) {\n const end = attributes?.(attributes_, context);\n if (value) {\n for (const value_ of Object.values(attributes_)) {\n if (value_ !== true)\n value(value_, context, 'attribute');\n }\n }\n end?.();\n }\n };\n const handleElement = (exp, context) => {\n if (typeof exp === 'object') {\n let end;\n switch (exp.type) {\n case 'expression': {\n end = expression?.(exp, context);\n if (exp.arg)\n value?.(exp.arg, context, 'arg');\n if (exp.functionRef) {\n const endA = functionRef?.(exp.functionRef, context, exp.arg);\n handleOptions(exp.functionRef.options, context);\n endA?.();\n }\n handleAttributes(exp.attributes, context);\n break;\n }\n case 'markup': {\n end = markup?.(exp, context);\n handleOptions(exp.options, context);\n handleAttributes(exp.attributes, context);\n break;\n }\n }\n end?.();\n }\n };\n const handlePattern = (pat) => {\n const end = pattern?.(pat);\n for (const el of pat)\n handleElement(el, 'placeholder');\n end?.();\n };\n for (const decl of msg.declarations) {\n const end = declaration?.(decl);\n if (decl.value)\n handleElement(decl.value, 'declaration');\n end?.();\n }\n if (msg.type === 'message') {\n handlePattern(msg.pattern);\n }\n else {\n if (value)\n for (const sel of msg.selectors)\n value(sel, 'selector', 'arg');\n for (const vari of msg.variants) {\n const end = variant?.(vari);\n if (key)\n vari.keys.forEach(key);\n handlePattern(vari.value);\n end?.();\n }\n }\n}\n","import { MessageDataModelError } from \"../errors.js\";\nimport { visit } from \"./visit.js\";\n/**\n * Ensure that the `msg` data model is _valid_, calling `onError` on errors.\n * If `onError` is not defined, a {@link MessageDataModelError} will be thrown on error.\n *\n * Detects the following errors:\n *\n * - `'key-mismatch'`: **Variant Key Mismatch**<br>\n * The number of keys on a _variant_ does not equal the number of _selectors_.\n *\n * - `'missing-fallback'`: **Missing Fallback Variant**<br>\n * The message does not include a _variant_ with only catch-all keys.\n *\n * - `'missing-selector-annotation'`: **Missing Selector Annotation**<br>\n * A _selector_ does not contains a _variable_ that directly or indirectly\n * reference a _declaration_ with a _function_.\n *\n * - `'duplicate-declaration'`: **Duplicate Declaration**<br>\n * A _variable_ appears in two _declarations_.\n *\n * - `'duplicate-variant'`: **Duplicate Variant**<br>\n * The same list of _keys_ is used for more than one _variant_.\n *\n * @category Message Data Model\n * @returns The sets of runtime `functions` and `variables` used by the message.\n */\nexport function validate(msg, onError = (type, node) => {\n throw new MessageDataModelError(type, node);\n}) {\n let selectorCount = 0;\n let missingFallback = null;\n /** Tracks directly & indirectly annotated variables for `missing-selector-annotation` */\n const annotated = new Set();\n /** Tracks declared variables for `duplicate-declaration` */\n const declared = new Set();\n const functions = new Set();\n const localVars = new Set();\n const variables = new Set();\n const variants = new Set();\n let setArgAsDeclared = true;\n visit(msg, {\n declaration(decl) {\n // Skip all ReservedStatement\n if (!decl.name)\n return undefined;\n if (decl.value.functionRef ||\n (decl.type === 'local' &&\n decl.value.arg?.type === 'variable' &&\n annotated.has(decl.value.arg.name))) {\n annotated.add(decl.name);\n }\n if (decl.type === 'local')\n localVars.add(decl.name);\n setArgAsDeclared = decl.type === 'local';\n return () => {\n if (declared.has(decl.name))\n onError('duplicate-declaration', decl);\n else\n declared.add(decl.name);\n };\n },\n expression({ functionRef }) {\n if (functionRef)\n functions.add(functionRef.name);\n },\n value(value, context, position) {\n if (value.type !== 'variable')\n return;\n variables.add(value.name);\n switch (context) {\n case 'declaration':\n if (position !== 'arg' || setArgAsDeclared) {\n declared.add(value.name);\n }\n break;\n case 'selector':\n selectorCount += 1;\n missingFallback = value;\n if (!annotated.has(value.name)) {\n onError('missing-selector-annotation', value);\n }\n }\n },\n variant(variant) {\n const { keys } = variant;\n if (keys.length !== selectorCount)\n onError('key-mismatch', variant);\n const strKeys = JSON.stringify(keys.map(key => (key.type === 'literal' ? key.value : 0)));\n if (variants.has(strKeys))\n onError('duplicate-variant', variant);\n else\n variants.add(strKeys);\n missingFallback &&= keys.every(key => key.type === '*') ? null : variant;\n }\n });\n if (missingFallback)\n onError('missing-fallback', missingFallback);\n for (const lv of localVars)\n variables.delete(lv);\n return { functions, variables };\n}\n","export const LRI = '\\u2066';\nexport const RLI = '\\u2067';\nexport const FSI = '\\u2068';\nexport const PDI = '\\u2069';\n// Data source: RECOMMENDED and LIMITED_USE scripts from\n// https://github.com/unicode-org/cldr/blob/1a914d1/common/properties/scriptMetadata.txt\nconst RTL = 'Adlm,Arab,Hebr,Mand,Nkoo,Rohg,Syrc,Thaa';\n/** Get a default text direction for `locale`. */\nexport function getLocaleDir(locale) {\n if (locale) {\n try {\n if (typeof locale === 'string')\n locale = new Intl.Locale(locale);\n // @ts-expect-error -- New feature, API changed during Stage 3\n const info = locale.getTextInfo?.() ?? locale.textInfo;\n if (info?.direction)\n return info.direction;\n const script = locale.maximize().script;\n if (script)\n return RTL.includes(script) ? 'rtl' : 'ltr';\n }\n catch {\n // Use 'auto' on error\n }\n }\n return 'auto';\n}\n","/**\n * Utility function for custom functions.\n * Cast a value as a Boolean,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts `'true'` and `'false'`.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asBoolean(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'boolean')\n return value;\n if (value && typeof value === 'object')\n value = String(value);\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n throw new RangeError('Not a boolean');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a non-negative integer,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts JSON string reprentations of integers.\n * Throws a `RangeError` for invalid inputs.\n *\n * The default functions use this to validate _digit size options_.\n */\nexport function asPositiveInteger(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (value && typeof value === 'object')\n value = String(value);\n if (typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value)) {\n value = Number(value);\n }\n if (typeof value === 'number' && value >= 0 && Number.isInteger(value)) {\n return value;\n }\n throw new RangeError('Not a positive integer');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a string,\n * unwrapping objects using their `valueOf()` methods.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asString(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'string')\n return value;\n if (value && typeof value === 'object')\n return String(value);\n throw new RangeError('Not a string');\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\nexport function readNumericOperand(value) {\n let options = undefined;\n if (typeof value === 'object') {\n const valueOf = value?.valueOf;\n if (typeof valueOf === 'function') {\n options = value.options;\n value = valueOf.call(value);\n }\n }\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value);\n }\n catch {\n // handled below\n }\n }\n if (typeof value !== 'bigint' && typeof value !== 'number') {\n throw new MessageFunctionError('bad-operand', 'Input is not numeric');\n }\n return { value, options };\n}\nexport function getMessageNumber(ctx, value, options, canSelect) {\n let { dir, locales } = ctx;\n // @ts-expect-error We may have been a bit naughty earlier.\n if (options.useGrouping === 'never')\n options.useGrouping = false;\n if (canSelect &&\n 'select' in options &&\n !ctx.literalOptionKeys.has('select')) {\n ctx.onError('bad-option', 'The option select may only be set by a literal value');\n canSelect = false;\n }\n let locale;\n let nf;\n let cat;\n let str;\n return {\n type: 'number',\n get dir() {\n if (dir == null) {\n locale ??= Intl.NumberFormat.supportedLocalesOf(locales, options)[0];\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n selectKey: canSelect\n ? keys => {\n let numVal = value;\n if (options.style === 'percent') {\n if (typeof numVal === 'bigint')\n numVal *= 100n;\n else\n numVal *= 100;\n }\n const str = String(numVal);\n if (keys.has(str))\n return str;\n if (options.select === 'exact')\n return null;\n const pluralOpt = options.select\n ? { ...options, select: undefined, type: options.select }\n : options;\n // Intl.PluralRules needs a number, not bigint\n cat ??= new Intl.PluralRules(locales, pluralOpt).select(Number(numVal));\n return keys.has(cat) ? cat : null;\n }\n : undefined,\n toParts() {\n nf ??= new Intl.NumberFormat(locales, options);\n const parts = nf.formatToParts(value);\n locale ??= nf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'number', dir, locale, parts }]\n : [{ type: 'number', locale, parts }];\n },\n toString() {\n nf ??= new Intl.NumberFormat(locales, options);\n str ??= nf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nexport function number(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = input.value;\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'roundingMode':\n case 'roundingPriority':\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :number option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\nexport function integer(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = Number.isFinite(input.value)\n ? Math.round(input.value)\n : input.value;\n const options = Object.assign({}, input.options, {\n //localeMatcher: ctx.localeMatcher,\n maximumFractionDigits: 0,\n minimumFractionDigits: undefined,\n minimumSignificantDigits: undefined,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :integer option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `currency` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `currency` property.\n *\n * @beta\n */\nexport function currency(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'currency'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'currency':\n case 'currencySign':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'currencyDisplay': {\n const strval = asString(optval);\n if (strval === 'never') {\n ctx.onError('unsupported-operation', 'Currency display \"never\" is not yet supported');\n }\n else {\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = strval;\n }\n break;\n }\n case 'fractionDigits': {\n const strval = asString(optval);\n if (strval === 'auto') {\n options.minimumFractionDigits = undefined;\n options.maximumFractionDigits = undefined;\n }\n else {\n const numval = asPositiveInteger(strval);\n options.minimumFractionDigits = numval;\n options.maximumFractionDigits = numval;\n }\n break;\n }\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n if (!options.currency) {\n throw new MessageFunctionError('bad-operand', 'A currency code is required for :currency');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n","import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asBoolean, asString } from \"./utils.js\";\nconst dateFieldsValues = new Set([\n 'weekday',\n 'day-weekday',\n 'month-day',\n 'month-day-weekday',\n 'year-month-day',\n 'year-month-day-weekday'\n]);\nconst dateLengthValues = new Set(['long', 'medium', 'short']);\nconst timePrecisionValues = new Set(['hour', 'minute', 'second']);\nconst timeZoneStyleValues = new Set(['long', 'short']);\n/**\n * The function `:datetime` is used to format a date/time value.\n * Its formatted result will always include both the date and the time, and optionally a timezone.\n *\n * @beta\n */\nexport const datetime = (ctx, options, operand) => dateTimeImplementation('datetime', ctx, options, operand);\n/**\n * The function `:date` is used to format the date portion of date/time values.\n *\n * @beta\n */\nexport const date = (ctx, options, operand) => dateTimeImplementation('date', ctx, options, operand);\n/**\n * The function `:time` is used to format the time portion of date/time values.\n * Its formatted result will always include the time, and optionally a timezone.\n *\n * @beta\n */\nexport const time = (ctx, options, operand) => dateTimeImplementation('time', ctx, options, operand);\nfunction dateTimeImplementation(functionName, ctx, exprOpt, operand) {\n const options = {\n localeMatcher: ctx.localeMatcher\n };\n let value = operand;\n if (typeof value === 'object' && value !== null) {\n const opt = value.options;\n if (opt) {\n options.calendar = opt.calendar;\n if (functionName !== 'date')\n options.hour12 = opt.hour12;\n options.timeZone = opt.timeZone;\n }\n if (typeof value.valueOf === 'function')\n value = value.valueOf();\n }\n switch (typeof value) {\n case 'number':\n case 'string':\n value = new Date(value);\n }\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new MessageFunctionError('bad-operand', 'Input is not a valid date');\n }\n // Override options\n if (exprOpt.calendar !== undefined) {\n try {\n options.calendar = asString(exprOpt.calendar);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} calendar option value`);\n }\n }\n if (exprOpt.hour12 !== undefined && functionName !== 'date') {\n try {\n options.hour12 = asBoolean(exprOpt.hour12);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} hour12 option value`);\n }\n }\n if (exprOpt.timeZone !== undefined) {\n let tz;\n try {\n tz = asString(exprOpt.timeZone);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} timeZone option value`);\n }\n if (tz === 'input') {\n if (options.timeZone === undefined) {\n ctx.onError('bad-operand', `Missing input timeZone value for :${functionName}`);\n }\n }\n else if (tz !== undefined) {\n if (options.timeZone !== undefined && tz !== options.timeZone) {\n // Use fallback value for expression\n throw new MessageFunctionError('bad-option', 'Time zone conversion is not supported');\n }\n options.timeZone = tz;\n }\n }\n // Date formatting options\n if (functionName !== 'time') {\n const dfName = functionName === 'date' ? 'fields' : 'dateFields';\n const dlName = functionName === 'date' ? 'length' : 'dateLength';\n const dateFieldsValue = readStringOption(ctx, exprOpt, dfName, dateFieldsValues) ??\n 'year-month-day';\n const dateLength = readStringOption(ctx, exprOpt, dlName, dateLengthValues);\n const dateFields = new Set(dateFieldsValue.split('-'));\n if (dateFields.has('year'))\n options.year = 'numeric';\n if (dateFields.has('month')) {\n options.month =\n dateLength === 'long'\n ? 'long'\n : dateLength === 'short'\n ? 'numeric'\n : 'short';\n }\n if (dateFields.has('day'))\n options.day = 'numeric';\n if (dateFields.has('weekday')) {\n options.weekday = dateLength === 'long' ? 'long' : 'short';\n }\n }\n // Time formatting options\n if (functionName !== 'date') {\n const tpName = functionName === 'time' ? 'precision' : 'timePrecision';\n switch (readStringOption(ctx, exprOpt, tpName, timePrecisionValues)) {\n case 'hour':\n options.hour = 'numeric';\n break;\n case 'second':\n options.hour = 'numeric';\n options.minute = 'numeric';\n options.second = 'numeric';\n break;\n default:\n options.hour = 'numeric';\n options.minute = 'numeric';\n }\n options.timeZoneName = readStringOption(ctx, exprOpt, 'timeZoneStyle', timeZoneStyleValues);\n }\n // Resolved value\n const dtf = new Intl.DateTimeFormat(ctx.locales, options);\n let dir = ctx.dir;\n let locale;\n let str;\n return {\n type: 'datetime',\n get dir() {\n if (dir == null) {\n locale ??= dtf.resolvedOptions().locale;\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n toParts() {\n const parts = dtf.formatToParts(value);\n locale ??= dtf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'datetime', dir, locale, parts }]\n : [{ type: 'datetime', locale, parts }];\n },\n toString() {\n str ??= dtf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nfunction readStringOption(ctx, options, name, allowed) {\n const value = options[name];\n if (value !== undefined) {\n try {\n const str = asString(value);\n if (allowed && !allowed.has(str))\n throw Error();\n return str;\n }\n catch {\n ctx.onError('bad-option', `Invalid value for ${name} option`);\n }\n }\n return undefined;\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { number, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger } from \"./utils.js\";\n/**\n * `offset` accepts a numeric value as input and adds or subtracts an integer value from it\n *\n * @beta\n */\nexport function offset(ctx, exprOpt, operand) {\n let { value, options } = readNumericOperand(operand);\n let add;\n try {\n add = 'add' in exprOpt ? asPositiveInteger(exprOpt.add) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.add} is not valid for :offset option add`);\n }\n let sub;\n try {\n sub = 'subtract' in exprOpt ? asPositiveInteger(exprOpt.subtract) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.subtract} is not valid for :offset option subtract`);\n }\n if (add < 0 === sub < 0) {\n const msg = 'Exactly one of \"add\" or \"subtract\" is required as an :offset option';\n throw new MessageFunctionError('bad-option', msg);\n }\n const delta = add < 0 ? -sub : add;\n if (typeof value === 'number')\n value += delta;\n else\n value += BigInt(delta);\n return number(ctx, {}, { valueOf: () => value, options });\n}\n","import { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * The function `:percent` is a selector and formatter for percent values.\n *\n * @beta\n */\nexport function percent(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'percent'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'roundingMode':\n case 'roundingPriority':\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :percent option ${name}`);\n }\n }\n return getMessageNumber(ctx, input.value, options, true);\n}\n","export function string(ctx, _options, operand) {\n const str = operand === undefined ? '' : String(operand);\n const selStr = str.normalize();\n return {\n type: 'string',\n dir: ctx.dir ?? 'auto',\n selectKey: keys => (keys.has(selStr) ? selStr : null),\n toParts() {\n const { dir } = ctx;\n const locale = ctx.locales[0];\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'string', dir, locale, value: str }]\n : [{ type: 'string', locale, value: str }];\n },\n toString: () => str,\n valueOf: () => str\n };\n}\n","import { MessageError, MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `unit` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `unit` property.\n *\n * @beta\n */\nexport function unit(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'unit'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'signDisplay':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'unit':\n case 'unitDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch (error) {\n if (error instanceof MessageError) {\n ctx.onError(error);\n }\n else {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n }\n if (!options.unit) {\n throw new MessageFunctionError('bad-operand', 'A unit identifier is required for :unit');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n","/**\n * Implementations for :number, :string, and other default functions,\n * along with some utilities for building custom function handlers.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgSrc, { functions: DraftFunctions });\n * ```\n *\n * @module\n */\nexport { getLocaleDir } from \"../dir-utils.js\";\nexport { asBoolean, asPositiveInteger, asString } from \"./utils.js\";\nimport { currency } from \"./currency.js\";\nimport { date, datetime, time } from \"./datetime.js\";\nimport { integer, number } from \"./number.js\";\nimport { offset } from \"./offset.js\";\nimport { percent } from \"./percent.js\";\nimport { string } from \"./string.js\";\nimport { unit } from \"./unit.js\";\n/**\n * Functions classified as REQUIRED by the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat specification}.\n */\nexport let DefaultFunctions = {\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-integer-function | :integer function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n integer,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-number-function | :number function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n number,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-offset-function | :offset function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n offset,\n /**\n * Supports formatting and selection as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-string-function | :string function}.\n *\n * The `operand` must be a stringifiable value.\n * An `undefined` value is resolved as an empty string.\n */\n string\n};\nDefaultFunctions = Object.freeze(Object.assign(Object.create(null), DefaultFunctions));\n/**\n * Functions classified as DRAFT by the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat specification}.\n *\n * These are liable to change, and are **_not_** covered by any stability guarantee.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgsrc, { functions: DraftFunctions });\n * ```\n *\n * @beta\n */\nexport let DraftFunctions = {\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-currency-function | :currency function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `currency` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n currency,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-date-function | :date function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n date,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-datetime-function | :datetime function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n datetime,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-percent-function | :percent function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n percent,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-time-function | :time function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n time,\n /**\n * Supports formatting as defined in LDML 48 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#the-unit-function | :unit function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `unit` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n unit\n};\nDraftFunctions = Object.freeze(Object.assign(Object.create(null), DraftFunctions));\n","export const BIDI_ISOLATE = Symbol('bidi-isolate');\n","export const fallback = (source = '�') => ({\n type: 'fallback',\n source,\n toParts: () => [{ type: 'fallback', source }],\n toString: () => `{${source}}`\n});\n","export const unknown = (source, input) => ({\n type: 'unknown',\n source,\n dir: 'auto',\n toParts: () => [{ type: 'unknown', value: input }],\n toString: () => String(input),\n valueOf: () => input\n});\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport class MessageFunctionContext {\n #ctx;\n #litKeys;\n #source;\n dir;\n id;\n constructor(ctx, source, options) {\n this.#ctx = ctx;\n this.#source = source;\n this.dir = undefined;\n const dirOpt = options && Object.hasOwn(options, 'u:dir') ? options['u:dir'] : undefined;\n if (dirOpt) {\n const dir = String(resolveValue(ctx, dirOpt));\n if (dir === 'ltr' || dir === 'rtl' || dir === 'auto') {\n this.dir = dir;\n }\n else if (dir !== 'inherit') {\n const error = new MessageFunctionError('bad-option', 'Unsupported value for u:dir option');\n error.source = getValueSource(dirOpt);\n ctx.onError(error);\n }\n }\n const idOpt = options && Object.hasOwn(options, 'u:id') ? options['u:id'] : undefined;\n this.id = idOpt ? String(resolveValue(ctx, idOpt)) : undefined;\n if (options) {\n this.#litKeys = new Set();\n for (const [key, value] of Object.entries(options)) {\n if (value.type === 'literal')\n this.#litKeys.add(key);\n }\n }\n }\n get literalOptionKeys() {\n return new Set(this.#litKeys);\n }\n get localeMatcher() {\n return this.#ctx.localeMatcher;\n }\n get locales() {\n return this.#ctx.locales.map(String);\n }\n onError(error, message) {\n let mfError;\n if (error instanceof MessageFunctionError) {\n mfError = error;\n }\n else if (typeof error === 'string' && typeof message === 'string') {\n mfError = new MessageFunctionError(error, message);\n }\n else {\n mfError = new MessageFunctionError('function-error', String(error));\n mfError.cause = error;\n }\n mfError.source = this.#source;\n this.#ctx.onError(mfError);\n }\n}\n","import { MessageError, MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { BIDI_ISOLATE } from \"../message-value.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function resolveFunctionRef(ctx, operand, { name, options }) {\n const fnSource = `:${name}`;\n const source = getValueSource(operand) ?? fnSource;\n try {\n const fnInput = operand ? [resolveValue(ctx, operand)] : [];\n const rf = ctx.functions[name];\n if (!rf) {\n throw new MessageResolutionError('unknown-function', `Unknown function ${fnSource}`, source);\n }\n const msgCtx = new MessageFunctionContext(ctx, source, options);\n const opt = resolveOptions(ctx, options);\n const res = rf(msgCtx, opt, ...fnInput);\n if (res === null ||\n typeof res !== 'object' ||\n typeof res.type !== 'string') {\n throw new MessageResolutionError('bad-function-result', `Function ${fnSource} did not return a MessageValue`, source);\n }\n const override = { source };\n if (msgCtx.dir) {\n override.dir = msgCtx.dir;\n override[BIDI_ISOLATE] = true;\n }\n if (msgCtx.id && typeof res.toParts === 'function') {\n override.toParts = () => {\n const parts = res.toParts();\n for (const part of parts)\n part.id = msgCtx.id;\n return parts;\n };\n }\n return { ...res, ...override };\n }\n catch (error) {\n ctx.onError(error instanceof MessageError\n ? error\n : new MessageResolutionError('bad-function-result', String(error), source, error));\n return fallback(source);\n }\n}\nfunction resolveOptions(ctx, options) {\n const opt = Object.create(null);\n if (options) {\n for (const [name, value] of Object.entries(options)) {\n if (!name.startsWith('u:'))\n opt[name] = resolveValue(ctx, value);\n }\n }\n return opt;\n}\n","import { string } from \"../functions/string.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveFunctionRef } from \"./resolve-function-ref.js\";\nimport { resolveVariableRef } from \"./resolve-variable.js\";\nexport function resolveExpression(ctx, { arg, functionRef }) {\n if (functionRef) {\n return resolveFunctionRef(ctx, arg, functionRef);\n }\n switch (arg?.type) {\n case 'literal': {\n const source = `|${arg.value}|`;\n const msgCtx = new MessageFunctionContext(ctx, source);\n const msgStr = string(msgCtx, {}, arg.value);\n msgStr.source = source;\n return msgStr;\n }\n case 'variable':\n return resolveVariableRef(ctx, arg);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported expression: ${arg?.type}`);\n }\n}\n","import { MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { unknown } from \"../functions/unknown.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveExpression } from \"./resolve-expression.js\";\n/**\n * Declarations aren't resolved until they're requierd,\n * and their resolution order matters for variable resolution.\n * This internal class is used to store any required data,\n * and to allow for `instanceof` detection.\n *\n * @internal\n */\nexport class UnresolvedExpression {\n expression;\n scope;\n constructor(expression, scope) {\n this.expression = expression;\n this.scope = scope;\n }\n}\nconst isScope = (scope) => scope !== null && (typeof scope === 'object' || typeof scope === 'function');\n/**\n * Looks for the longest matching `.` delimited starting substring of name.\n * @returns `undefined` if value not found\n */\nfunction getValue(scope, name) {\n if (isScope(scope)) {\n if (name in scope)\n return scope[name];\n const parts = name.split('.');\n for (let i = parts.length - 1; i > 0; --i) {\n const head = parts.slice(0, i).join('.');\n if (head in scope) {\n const tail = parts.slice(i).join('.');\n return getValue(scope[head], tail);\n }\n }\n for (const [key, value] of Object.entries(scope)) {\n if (key.normalize() === name)\n return value;\n }\n }\n return undefined;\n}\n/**\n * Get the raw value of a variable.\n * Resolves declarations as necessary\n *\n * @internal\n * @returns `unknown` or `any` for input values;\n * `MessageValue` for `.input` and `.local` declaration values.\n */\nexport function lookupVariableRef(ctx, { name }) {\n const value = getValue(ctx.scope, name);\n if (value === undefined) {\n const source = '$' + name;\n const msg = `Variable not available: ${source}`;\n ctx.onError(new MessageResolutionError('unresolved-variable', msg, source));\n }\n else if (value instanceof UnresolvedExpression) {\n const local = resolveExpression(value.scope ? { ...ctx, scope: value.scope } : ctx, value.expression);\n ctx.scope[name] = local;\n ctx.localVars.add(local);\n return local;\n }\n return value;\n}\nexport function resolveVariableRef(ctx, ref) {\n const source = '$' + ref.name;\n const value = lookupVariableRef(ctx, ref);\n if (value === undefined)\n return fallback(source);\n let type = typeof value;\n if (type === 'object') {\n const mv = value;\n if (mv.type === 'fallback')\n return fallback(source);\n if (ctx.localVars.has(mv)) {\n mv.source = source;\n return mv;\n }\n if (value instanceof Number)\n type = 'number';\n else if (value instanceof String)\n type = 'string';\n }\n let msgFn;\n switch (type) {\n case 'bigint':\n case 'number':\n msgFn = ctx.functions.number;\n break;\n case 'string':\n msgFn = ctx.functions.string;\n break;\n default:\n return unknown(source, value);\n }\n const msgCtx = new MessageFunctionContext(ctx, source);\n const mv = msgFn(msgCtx, {}, value);\n mv.source = source;\n return mv;\n}\n","import { lookupVariableRef } from \"./resolve-variable.js\";\nexport function resolveValue(ctx, value) {\n switch (value.type) {\n case 'literal':\n return value.value;\n case 'variable':\n return lookupVariableRef(ctx, value);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported value: ${value.type}`);\n }\n}\nexport function getValueSource(value) {\n switch (value?.type) {\n case 'literal':\n return ('|' + value.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('|', '\\\\|') + '|');\n case 'variable':\n return '$' + value.name;\n default:\n return undefined;\n }\n}\n","import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function formatMarkup(ctx, { kind, name, options }) {\n const part = { type: 'markup', kind, name };\n const entries = options ? Object.entries(options) : null;\n if (entries?.length) {\n part.options = {};\n for (const [name, value] of entries) {\n if (name === 'u:dir') {\n const error = new MessageFunctionError('bad-option', `The option ${name} is not valid for markup`);\n error.source = getValueSource(value);\n ctx.onError(error);\n }\n else {\n let rv = resolveValue(ctx, value);\n if (typeof rv === 'object' && typeof rv?.valueOf === 'function') {\n rv = rv.valueOf();\n }\n if (name === 'u:id')\n part.id = String(rv);\n else\n part.options[name] = rv;\n }\n }\n }\n return part;\n}\n","import { MessageResolutionError } from \"./errors.js\";\nimport { resolveVariableRef } from \"./resolve/resolve-variable.js\";\nexport function selectPattern(context, message) {\n if (message.type === 'message')\n return message.pattern;\n // message.type === 'select'\n const ctx = message.selectors.map(sel => {\n const selector = resolveVariableRef(context, sel);\n let selectKey;\n if (typeof selector.selectKey === 'function') {\n selectKey = selector.selectKey.bind(selector);\n }\n else {\n const msg = 'Selector does not support selection';\n context.onError(new MessageResolutionError('bad-selector', msg, selector.source));\n selectKey = () => null;\n }\n return {\n selectKey,\n source: selector.source,\n best: null,\n keys: null\n };\n });\n let candidates = message.variants;\n loop: for (let i = 0; i < ctx.length; ++i) {\n const sc = ctx[i];\n if (!sc.keys) {\n sc.keys = new Set();\n for (const { keys } of candidates) {\n const key = keys[i];\n if (!key)\n break loop; // key-mismatch error\n if (key.type !== '*')\n sc.keys.add(key.value);\n }\n }\n try {\n sc.best = sc.keys.size ? sc.selectKey(sc.keys) : null;\n }\n catch (error) {\n const msg = 'Selection failed';\n context.onError(new MessageResolutionError('bad-selector', msg, sc.source, error));\n sc.selectKey = () => null;\n sc.best = null;\n }\n // Leave out all candidate variants that aren't the best,\n // or only the catchall ones, if nothing else matches.\n candidates = candidates.filter(v => {\n const k = v.keys[i];\n if (k.type === '*')\n return sc.best == null;\n return sc.best === k.value;\n });\n // If we've run out of candidates,\n // drop the previous best key of the preceding selector,\n // reset all subsequent key sets,\n // and restart the loop.\n if (candidates.length === 0) {\n if (i === 0)\n break; // No match; should not happen\n const prev = ctx[i - 1];\n if (prev.best == null)\n prev.keys?.clear();\n else\n prev.keys?.delete(prev.best);\n for (let j = i; j < ctx.length; ++j)\n ctx[j].keys = null;\n candidates = message.variants;\n i = -1;\n }\n }\n const res = candidates[0];\n if (!res) {\n // This should not be possible with a valid message.\n const msg = 'No variant was selected!?';\n context.onError(new MessageResolutionError('no-match', msg, '.match'));\n return [];\n }\n return res.value;\n}\n","import { parseMessage } from \"./data-model/parse.js\";\nimport { validate } from \"./data-model/validate.js\";\nimport { FSI, LRI, PDI, RLI, getLocaleDir } from \"./dir-utils.js\";\nimport { MessageFunctionError } from \"./errors.js\";\nimport { DefaultFunctions } from \"./functions/index.js\";\nimport { BIDI_ISOLATE } from \"./message-value.js\";\nimport { formatMarkup } from \"./resolve/format-markup.js\";\nimport { resolveExpression } from \"./resolve/resolve-expression.js\";\nimport { UnresolvedExpression } from \"./resolve/resolve-variable.js\";\nimport { selectPattern } from \"./select-pattern.js\";\n/**\n * A message formatter for that implements the\n * {@link https://www.unicode.org/reports/tr35/tr35-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat}\n * specification as well as the {@link https://github.com/tc39/proposal-intl-messageformat/ | TC39 Intl.MessageFormat proposal}.\n *\n * @category Formatting\n * @typeParam T - The `type` used by custom message functions, if any.\n * These extend the {@link DefaultFunctions | default functions}.\n * @typeParam P - The formatted-parts `type` used by any custom message values.\n */\nexport class MessageFormat {\n #bidiIsolation;\n #dir;\n #localeMatcher;\n #locales;\n #message;\n #functions;\n constructor(locales, source, options) {\n this.#bidiIsolation = options?.bidiIsolation !== 'none';\n this.#localeMatcher = options?.localeMatcher ?? 'best fit';\n this.#locales = Array.isArray(locales)\n ? locales.map(lc => new Intl.Locale(lc))\n : locales\n ? [new Intl.Locale(locales)]\n : [];\n this.#dir = options?.dir ?? getLocaleDir(this.#locales[0]);\n this.#message = typeof source === 'string' ? parseMessage(source) : source;\n validate(this.#message);\n this.#functions = options?.functions\n ? Object.assign(Object.create(null), DefaultFunctions, options.functions)\n : DefaultFunctions;\n }\n /**\n * Format a message to a string.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.format({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * 'Hello Kat, today is March 1, 2025'\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n format(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n let res = '';\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n res += elem;\n }\n else if (elem.type === 'markup') {\n // Handle errors, but discard results\n formatMarkup(ctx, elem);\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toString === 'function') {\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n res += pre + mv.toString() + PDI;\n }\n else {\n res += mv.toString();\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const errStr = `{${mv?.source ?? '�'}}`;\n res += this.#bidiIsolation ? FSI + errStr + PDI : errStr;\n }\n }\n }\n return res;\n }\n /**\n * Format a message to a sequence of parts.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.formatToParts({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * [\n * { type: 'text', value: 'Hello ' },\n * { type: 'bidiIsolation', value: '\\u2068' },\n * { type: 'string', locale: 'en', value: 'Kat' },\n * { type: 'bidiIsolation', value: '\\u2069' },\n * { type: 'text', value: ', today is ' },\n * {\n * type: 'datetime',\n * dir: 'ltr',\n * locale: 'en',\n * parts: [\n * { type: 'month', value: 'March' },\n * { type: 'literal', value: ' ' },\n * { type: 'day', value: '1' },\n * { type: 'literal', value: ', ' },\n * { type: 'year', value: '2025' }\n * ]\n * }\n * ]\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n formatToParts(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n const parts = [];\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n parts.push({ type: 'text', value: elem });\n }\n else if (elem.type === 'markup') {\n parts.push(formatMarkup(ctx, elem));\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toParts === 'function') {\n // Let's presume that parts that look like MessageNumberPart or MessageStringPart are such.\n const mp = mv.toParts();\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n parts.push({ type: 'bidiIsolation', value: pre }, ...mp, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(...mp);\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const fb = {\n type: 'fallback',\n source: mv?.source ?? '�'\n };\n if (this.#bidiIsolation) {\n parts.push({ type: 'bidiIsolation', value: FSI }, fb, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(fb);\n }\n }\n }\n }\n return parts;\n }\n #createContext(msgParams, onError = (error) => {\n // Emit warning for errors by default\n try {\n process.emitWarning(error);\n }\n catch {\n console.warn(error);\n }\n }) {\n const scope = { ...msgParams };\n for (const decl of this.#message.declarations) {\n scope[decl.name] = new UnresolvedExpression(decl.value, decl.type === 'input' ? (msgParams ?? {}) : undefined);\n }\n const ctx = {\n onError,\n localeMatcher: this.#localeMatcher,\n locales: this.#locales,\n localVars: new WeakSet(),\n functions: this.#functions,\n scope\n };\n return ctx;\n }\n}\n","import { MessageFormat } from \"messageformat\";\nimport { DraftFunctions } from \"messageformat/functions\";\nimport type { TranslateOptions } from \"./types\";\n\nconst cache = new Map<string, Map<string, MessageFormat<string, string>>>();\n\nfunction getOrCreateMessageFormat(\n\tlocale: string,\n\tkey: string,\n\tmessage: string\n): MessageFormat<string, string> {\n\tlet localeCache = cache.get(locale);\n\tif (!localeCache) {\n\t\tlocaleCache = new Map();\n\t\tcache.set(locale, localeCache);\n\t}\n\n\tlet mf = localeCache.get(key);\n\tif (mf) {\n\t\treturn mf;\n\t}\n\tmf = new MessageFormat([locale], message, { functions: DraftFunctions });\n\tlocaleCache.set(key, mf);\n\treturn mf;\n}\n\nexport function defaultTranslate(\n\tmsg: string,\n\toptions?: TranslateOptions\n): string {\n\tif (!options?.vars || Object.keys(options.vars).length === 0) {\n\t\treturn msg;\n\t}\n\n\tif (options.formatting === \"identity\") {\n\t\treturn msg;\n\t}\n\n\tconst { locale, vars } = options;\n\tconst mf = getOrCreateMessageFormat(locale, msg, msg);\n\n\treturn mf.format(vars, (error) => {\n\t\tconsole.warn(`[fanee] Failed to format message: ${error}`);\n\t});\n}\n","import type { FaneeState } from \"./types\";\nimport { defaultTranslate } from \"./translator\";\n\nexport function defaultState(): FaneeState {\n\treturn {\n\t\tresources: {},\n\t\tdefaultLocale: \"en\",\n\t\tcurrentLocale: \"en\",\n\t\tbaseNamespace: \"\",\n\t\tformatting: \"mf2\",\n\t\ttranslate: defaultTranslate,\n\t};\n}\n","import type {\n\tFaneeState,\n\tLocale,\n\tMessageKey,\n\tTranslateContext,\n\tTranslateFunction,\n\tTranslationsByLocale,\n\tNamespaceResources,\n\tBundleResources,\n} from \"./types\";\nimport { defaultState } from \"./state\";\n\n/** Sequenced runtime that processes plugin setup before translations are available. */\nexport class FaneeRuntime {\n\tprivate state: FaneeState;\n\tprivate queue: Promise<void>;\n\tprivate listeners: Set<(state: FaneeState) => void>;\n\n\tconstructor() {\n\t\tthis.state = defaultState();\n\t\tthis.queue = Promise.resolve();\n\t\tthis.listeners = new Set();\n\t}\n\n\tprivate notify() {\n\t\tconst s = this.state;\n\t\tfor (const fn of this.listeners) {\n\t\t\tfn(s);\n\t\t}\n\t}\n\n\t/**\n\t * Register a plugin function that transforms the runtime state.\n\t *\n\t * Plugins are executed sequentially (FIFO) in the order they are registered.\n\t * Each plugin receives the current {@link FaneeState} and may return a new state\n\t * (or a promise thereof). The entire chain must resolve before the runtime\n\t * is considered \"ready\" (see {@link ready}).\n\t *\n\t * @param fn - A plugin function receiving the current state.\n\t * @returns `this` for chaining.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.use((state) => ({ ...state, currentLocale: \"zh-CN\" }));\n\t * ```\n\t */\n\tuse(\n\t\tfn: (state: FaneeState) => FaneeState | Promise<FaneeState>\n\t): this {\n\t\tthis.queue = this.queue.then(async () => {\n\t\t\tthis.state = await fn(this.state);\n\t\t\tthis.notify();\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * Shallow-merge a partial state patch into the current state.\n\t *\n\t * This operation is queued and runs after all previously registered plugins.\n\t * It is equivalent to a plugin that destructures the patch over the state.\n\t *\n\t * @param patch - A partial {@link FaneeState} whose properties override the current state.\n\t * @returns `this` for chaining.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.config({ defaultLocale: \"en\", formatting: \"mf2\" });\n\t * ```\n\t */\n\tconfig(patch: Partial<FaneeState>): this {\n\t\tthis.queue = this.queue.then(async () => {\n\t\t\tthis.state = { ...this.state, ...patch };\n\t\t\tthis.notify();\n\t\t});\n\t\treturn this;\n\t}\n\n\t/**\n\t * @internal\n\t * Makes the runtime thenable so callers can `await` plugin setup before\n\t * calling translation methods.\n\t *\n\t * @param onfulfilled - Handler for successful queue resolution.\n\t * @param onrejected - Handler for queue rejection.\n\t */\n\t// biome-ignore lint/suspicious/noThenProperty: intentional thenable for await support\n\tthen<TResult1 = void, TResult2 = never>(\n\t\tonfulfilled?:\n\t\t\t// biome-ignore lint/suspicious/noConfusingVoidType: matches Promise<void> queue resolution\n\t\t\t| ((value: void) => TResult1 | PromiseLike<TResult1>)\n\t\t\t| null,\n\t\tonrejected?:\n\t\t\t| ((reason: unknown) => TResult2 | PromiseLike<TResult2>)\n\t\t\t| null\n\t): Promise<TResult1 | TResult2> {\n\t\treturn this.queue.then(onfulfilled, onrejected);\n\t}\n\n\t/** Resolve locale + namespace from an optional context, falling back to the current state. */\n\tprivate resolveContext(context?: Partial<TranslateContext>) {\n\t\tconst { currentLocale, baseNamespace } = this.state;\n\n\t\tconst locale = context?.locale ?? currentLocale;\n\t\tconst ns = context?.namespace\n\t\t\t? (baseNamespace ? `${baseNamespace}:${context.namespace}` : context.namespace)\n\t\t\t: baseNamespace;\n\n\t\treturn { locale, ns };\n\t}\n\n\t/**\n\t * Look up a message in the resource tree and (if vars are provided)\n\t * delegate to the configured formatter.\n\t */\n\tprivate localize(\n\t\tresources: NamespaceResources | undefined,\n\t\tlocale: Locale,\n\t\tkey: MessageKey,\n\t\tvars?: Record<string, unknown>\n\t): string {\n\t\tif (!resources) {\n\t\t\treturn key;\n\t\t}\n\n\t\tlet localeData = resources[locale];\n\t\tif (!localeData) {\n\t\t\tlocaleData = resources[this.state.defaultLocale];\n\t\t\tif (!localeData) {\n\t\t\t\treturn key;\n\t\t\t}\n\t\t}\n\n\t\tconst value = localeData[key];\n\t\tif (value === undefined) {\n\t\t\treturn key;\n\t\t}\n\n\t\tif (vars === undefined || Object.keys(vars).length === 0) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn this.state.translate(value, {\n\t\t\tlocale,\n\t\t\tvars,\n\t\t\tformatting: this.state.formatting,\n\t\t});\n\t}\n\n\t/**\n\t * Translate a message key in the current locale and base namespace.\n\t *\n\t * Falls back through:\n\t * 1. {@link FaneeState.currentLocale Current locale}\n\t * 2. The {@link FaneeState.defaultLocale default locale}\n\t * 3. Returns the key itself if no translation is found\n\t *\n\t * @param key - The message key to translate.\n\t * @param vars - Optional variables for interpolation.\n\t * @returns The translated string, or `key` if no translation exists.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.t(\"hello\"); // \"你好\"\n\t * runtime.t(\"greeting\", { name: \"Alice\" }); // \"Hello, Alice\"\n\t * ```\n\t */\n\tt(key: MessageKey, vars?: Record<string, unknown>): string {\n\t\tconst { locale, ns } = this.resolveContext();\n\t\treturn this.localize(this.state.resources[ns], locale, key, vars);\n\t}\n\n\t/**\n\t * Return a bound translate function pinned to a specific locale/namespace.\n\t *\n\t * Unlike {@link t}, this method captures the locale and namespace at call time\n\t * so the returned function can be passed around (e.g. as a prop to a component)\n\t * without retaining a reference to the runtime.\n\t *\n\t * @param context - Optional overrides for locale and/or namespace.\n\t * If omitted, the current runtime values are captured.\n\t * @returns A function with the signature `(key, vars?) => string`.\n\t *\n\t * @example\n\t * ```ts\n\t * const t = runtime.getT({ locale: \"ja\", namespace: \"errors\" });\n\t * t(\"not_found\"); // \"見つかりませんでした\"\n\t * ```\n\t */\n\tgetT(context?: Partial<TranslateContext>): TranslateFunction {\n\t\tconst { locale, ns } = this.resolveContext(context);\n\t\tconst nsResources = this.state.resources[ns];\n\n\t\treturn (key: MessageKey, vars?: Record<string, unknown>): string =>\n\t\t\tthis.localize(nsResources, locale, key, vars);\n\t}\n\n\t/**\n\t * Translate a message key into every available locale within the base namespace.\n\t *\n\t * Useful for generating locale-switching UIs, SEO hreflang tags, or\n\t * pre-rendering all translations on the server.\n\t *\n\t * @param key - The message key to translate.\n\t * @param vars - Optional variables for interpolation (applied to every locale).\n\t * @returns A record mapping each locale to its translated string.\n\t * Returns an empty object if the base namespace has no resources.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.tAll(\"welcome\");\n\t * // { en: \"Welcome\", \"es\": \"Bienvenido\", \"fr\": \"Bienvenue\", \"zh-CN\": \"欢迎\", ja: \"ようこそ\" }\n\t * ```\n\t */\n\ttAll(key: MessageKey, vars?: Record<string, unknown>): TranslationsByLocale {\n\t\tconst { baseNamespace, resources } = this.state;\n\t\tconst nsResources = resources[baseNamespace];\n\t\tconst result: TranslationsByLocale = {};\n\n\t\tif (!nsResources) {\n\t\t\treturn result;\n\t\t}\n\n\t\tfor (const loc of Object.keys(nsResources)) {\n\t\t\tresult[loc as Locale] = this.localize(nsResources, loc as Locale, key, vars);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get the currently active locale.\n\t *\n\t * @returns The BCP 47 tag of the active locale (e.g. `\"en\"`, `\"zh-CN\"`).\n\t */\n\tgetLocale(): Locale {\n\t\treturn this.state.currentLocale;\n\t}\n\n\t/**\n\t * Collect every unique locale present across all loaded namespaces.\n\t *\n\t * @returns A sorted array of locale tags. Returns an empty array if no\n\t * resources have been loaded.\n\t */\n\tgetLocales(): Locale[] {\n\t\tconst locales = new Set<Locale>();\n\t\tfor (const resource of Object.values(this.state.resources)) {\n\t\t\tfor (const locale of Object.keys(resource)) {\n\t\t\t\tlocales.add(locale as Locale);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(locales).sort();\n\t}\n\n\t/**\n\t * Return the complete resource tree.\n\t *\n\t * @returns The full {@link BundleResources} object (namespace → locale → messages).\n\t */\n\tgetAllTranslations(): BundleResources {\n\t\treturn this.state.resources;\n\t}\n\n\t/**\n\t * Return resources for a single namespace.\n\t *\n\t * @param ns - The namespace to look up.\n\t * @returns The locale-indexed messages for that namespace, or `undefined`\n\t * if the namespace has not been loaded.\n\t */\n\tgetTranslationsForNamespace(\n\t\tns: string\n\t): NamespaceResources | undefined {\n\t\treturn this.state.resources[ns];\n\t}\n\n\t/**\n\t * Wait for all queued plugins to finish.\n\t *\n\t * Because plugin registration and configuration are queued as a promise chain,\n\t * you must `await runtime.ready()` (or `await runtime` directly) before calling\n\t * translation methods if any plugin is asynchronous.\n\t *\n\t * @returns A promise that resolves once the plugin queue is empty.\n\t *\n\t * @example\n\t * ```ts\n\t * const runtime = new FaneeRuntime()\n\t * .use(asyncLoaderPlugin)\n\t * .config({ defaultLocale: \"en\" });\n\t *\n\t * await runtime.ready();\n\t * console.log(runtime.t(\"hello\")); // safe\n\t * ```\n\t */\n\tready(): Promise<void> {\n\t\treturn this.queue;\n\t}\n\n\t/**\n\t * Switch the active locale at runtime.\n\t *\n\t * This is a synchronous operation that updates the current locale instantly.\n\t * Subsequent calls to {@link t} and {@link getT} (without an explicit locale)\n\t * will use this new locale.\n\t *\n\t * @param locale - The BCP 47 tag of the target locale.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.setLocale(\"fr\");\n\t * runtime.t(\"hello\"); // \"Bonjour\"\n\t * ```\n\t */\n\tsetLocale(locale: Locale) {\n\t\tthis.state.currentLocale = locale;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Switch the base namespace at runtime.\n\t *\n\t * Subsequent calls to {@link t} and related methods will resolve keys against\n\t * this namespace. When a scoped namespace is set via {@link getT},\n\t * it is prefixed with the base namespace using `:` as separator.\n\t *\n\t * @param ns - The namespace to set as the base.\n\t *\n\t * @example\n\t * ```ts\n\t * runtime.setNamespace(\"admin\");\n\t * runtime.t(\"dashboard_title\"); // resolved from \"admin\" namespace\n\t * ```\n\t */\n\tsetNamespace(ns: string) {\n\t\tthis.state.baseNamespace = ns;\n\t\tthis.notify();\n\t}\n\n\t/**\n\t * Subscribe to state changes.\n\t *\n\t * The callback is invoked synchronously whenever the runtime state is mutated\n\t * (via {@link setLocale}, {@link setNamespace}, or after a queued\n\t * {@link use} / {@link config} operation resolves).\n\t *\n\t * @param callback - Called with the current {@link FaneeState} on every change.\n\t * @returns An unsubscribe function. Call it to stop receiving notifications.\n\t *\n\t * @example\n\t * ```ts\n\t * const unsub = runtime.subscribe((state) => {\n\t * console.log(\"locale changed to\", state.currentLocale);\n\t * });\n\t *\n\t * runtime.setLocale(\"fr\"); // logs \"locale changed to fr\"\n\t * unsub();\n\t * ```\n\t */\n\tsubscribe(callback: (state: FaneeState) => void): () => void {\n\t\tthis.listeners.add(callback);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(callback);\n\t\t};\n\t}\n}\n","import { FaneeRuntime } from \"./runtime\";\n\nexport const i18n = new FaneeRuntime();\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26],"mappings":"AAAA,MAAMA,EAAY,sCACZ,EAAY,8fACZ,EAAe,WACrB,SAAgB,EAAe,EAAQ,EAAO,CAC1C,IAAI,EAAM,EACJ,EAAY,EAAO,MAAM,CAAG,CAAC,CAAC,MAAMA,CAAS,EAC/C,IACA,GAAO,EAAU,EAAE,CAAC,QACxB,IAAM,EAAQ,EAAO,MAAM,CAAG,CAAC,CAAC,MAAM,CAAS,EAC/C,GAAI,CAAC,EACD,OAAO,KACX,IAAM,EAAO,EAAM,GACnB,GAAI,EAAa,KAAK,CAAI,EACtB,OAAO,KACX,GAAO,EAAK,OACZ,IAAM,EAAU,EAAO,MAAM,CAAG,CAAC,CAAC,MAAMA,CAAS,EAGjD,OAFI,IACA,GAAO,EAAQ,EAAE,CAAC,QACf,CAAE,MAAO,EAAK,UAAU,EAAG,IAAK,CAAI,CAC/C,CAKA,MAAa,GAA6B,EAAQ,IAAU,EAAO,MAAM,CAAK,CAAC,CAAC,MAAM,CAAS,CAAC,GAAG,IAAM,GCjB5F,EAAS,OAAO,IAAI,KAAK,ECDtC,IAAa,EAAb,cAAkC,KAAM,CACpC,KACA,YAAY,EAAM,EAAS,CACvB,MAAM,CAAO,EACb,KAAK,KAAO,CAChB,CACJ,EAMa,EAAb,cAAwC,CAAa,CACjD,MACA,IAEA,YAAY,EAAM,EAAO,EAAK,EAAU,CACpC,IAAI,EAAU,EAAW,WAAW,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