@intlify/core-base 12.0.0-alpha.3 → 12.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core-base.js CHANGED
@@ -1,1909 +1,1348 @@
1
- /*!
2
- * core-base v12.0.0-alpha.3
3
- * (c) 2016-present kazuya kawaguchi and contributors
4
- * Released under the MIT License.
5
- */
6
- import { getGlobalThis, isObject, hasOwn, isNumber, create, isString, isBoolean, warn, format as format$1, isFunction, isPromise, isArray, isPlainObject, assign, isRegExp, warnOnce, deepCopy, isEmptyObject, isDate, join, toDisplayString, escapeHtml, inBrowser, mark, measure, generateCodeFrame, generateFormatCacheKey } from '@intlify/shared';
7
- import { detectHtmlTag, defaultOnError, createParser, optimize, mangle, createCompileError, COMPILE_ERROR_CODES_EXTEND_POINT } from '@intlify/message-compiler';
8
- export { createCompileError } from '@intlify/message-compiler';
9
-
10
1
  /**
11
- * This is only called in esm-bundler builds.
12
- * istanbul-ignore-next
13
- */
2
+ * @intlify/core-base v12.0.0-alpha.4
3
+ * (c) 2016-present kazuya kawaguchi and contributors
4
+ * @license MIT
5
+ **/
6
+ import { assign, create, deepCopy, escapeHtml, format, generateCodeFrame, generateFormatCacheKey, getGlobalThis, hasOwn, inBrowser, isArray, isBoolean, isDate, isFunction, isKeylessObject, isNumber, isObject, isPlainObject, isPromise, isRegExp, isString, join, mark, measure, sanitizeTranslatedHtml, toDisplayString, warn, warnOnce } from "@intlify/shared";
7
+ import { COMPILE_ERROR_CODES_EXTEND_POINT, HelperNameMap, NodeTypes, createCompileError, createCompileError as createCompileError$1, createParser, defaultOnError, detectHtmlTag, mangle, optimize } from "@intlify/message-compiler";
8
+ //#region packages/core-base/src/misc.ts
9
+ /**
10
+ * This is only called in esm-bundler builds.
11
+ * istanbul-ignore-next
12
+ */
14
13
  function initFeatureFlags() {
15
- if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
16
- getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
17
- }
18
- if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {
19
- getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;
20
- }
21
- }
22
-
14
+ if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== "boolean") getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;
15
+ }
16
+ //#endregion
17
+ //#region packages/core-base/src/ast.ts
23
18
  function isMessageAST(val) {
24
- return (isObject(val) &&
25
- resolveType(val) === 0 &&
26
- (hasOwn(val, 'b') || hasOwn(val, 'body')));
19
+ return isObject(val) && resolveType(val) === 0 && (hasOwn(val, "b") || hasOwn(val, "body"));
27
20
  }
28
- const PROPS_BODY = ['b', 'body'];
21
+ const PROPS_BODY = ["b", "body"];
29
22
  function resolveBody(node) {
30
- return resolveProps(node, PROPS_BODY);
23
+ return resolveProps(node, PROPS_BODY);
31
24
  }
32
- const PROPS_CASES = ['c', 'cases'];
25
+ const PROPS_CASES = ["c", "cases"];
33
26
  function resolveCases(node) {
34
- return resolveProps(node, PROPS_CASES, []);
27
+ return resolveProps(node, PROPS_CASES, []);
35
28
  }
36
- const PROPS_STATIC = ['s', 'static'];
29
+ const PROPS_STATIC = ["s", "static"];
37
30
  function resolveStatic(node) {
38
- return resolveProps(node, PROPS_STATIC);
31
+ return resolveProps(node, PROPS_STATIC);
39
32
  }
40
- const PROPS_ITEMS = ['i', 'items'];
33
+ const PROPS_ITEMS = ["i", "items"];
41
34
  function resolveItems(node) {
42
- return resolveProps(node, PROPS_ITEMS, []);
35
+ return resolveProps(node, PROPS_ITEMS, []);
43
36
  }
44
- const PROPS_TYPE = ['t', 'type'];
37
+ const PROPS_TYPE = ["t", "type"];
45
38
  function resolveType(node) {
46
- return resolveProps(node, PROPS_TYPE);
39
+ return resolveProps(node, PROPS_TYPE);
47
40
  }
48
- const PROPS_VALUE = ['v', 'value'];
41
+ const PROPS_VALUE = ["v", "value"];
49
42
  function resolveValue$1(node, type) {
50
- const resolved = resolveProps(node, PROPS_VALUE);
51
- if (resolved != null) {
52
- return resolved;
53
- }
54
- else {
55
- throw createUnhandleNodeError(type);
56
- }
57
- }
58
- const PROPS_MODIFIER = ['m', 'modifier'];
43
+ const resolved = resolveProps(node, PROPS_VALUE);
44
+ if (resolved != null) return resolved;
45
+ else throw createUnhandleNodeError(type);
46
+ }
47
+ const PROPS_MODIFIER = ["m", "modifier"];
59
48
  function resolveLinkedModifier(node) {
60
- return resolveProps(node, PROPS_MODIFIER);
49
+ return resolveProps(node, PROPS_MODIFIER);
61
50
  }
62
- const PROPS_KEY = ['k', 'key'];
51
+ const PROPS_KEY = ["k", "key"];
63
52
  function resolveLinkedKey(node) {
64
- const resolved = resolveProps(node, PROPS_KEY);
65
- if (resolved) {
66
- return resolved;
67
- }
68
- else {
69
- throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
70
- }
53
+ const resolved = resolveProps(node, PROPS_KEY);
54
+ if (resolved) return resolved;
55
+ else throw createUnhandleNodeError(NodeTypes.Linked);
71
56
  }
72
57
  function resolveProps(node, props, defaultValue) {
73
- for (let i = 0; i < props.length; i++) {
74
- const prop = props[i];
75
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
- if (hasOwn(node, prop) && node[prop] != null) {
77
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
- return node[prop];
79
- }
80
- }
81
- return defaultValue;
58
+ for (let i = 0; i < props.length; i++) {
59
+ const prop = props[i];
60
+ if (hasOwn(node, prop) && node[prop] != null) return node[prop];
61
+ }
62
+ return defaultValue;
82
63
  }
83
64
  const AST_NODE_PROPS_KEYS = [
84
- ...PROPS_BODY,
85
- ...PROPS_CASES,
86
- ...PROPS_STATIC,
87
- ...PROPS_ITEMS,
88
- ...PROPS_KEY,
89
- ...PROPS_MODIFIER,
90
- ...PROPS_VALUE,
91
- ...PROPS_TYPE
65
+ ...PROPS_BODY,
66
+ ...PROPS_CASES,
67
+ ...PROPS_STATIC,
68
+ ...PROPS_ITEMS,
69
+ ...PROPS_KEY,
70
+ ...PROPS_MODIFIER,
71
+ ...PROPS_VALUE,
72
+ ...PROPS_TYPE
92
73
  ];
93
74
  function createUnhandleNodeError(type) {
94
- return new Error(`unhandled node type: ${type}`);
75
+ return /* @__PURE__ */ new Error(`unhandled node type: ${type}`);
95
76
  }
96
-
97
- function format(ast) {
98
- const msg = (ctx) => formatParts(ctx, ast);
99
- return msg;
77
+ //#endregion
78
+ //#region packages/core-base/src/format.ts
79
+ function format$1(ast) {
80
+ return (ctx) => formatParts(ctx, ast);
100
81
  }
101
82
  function formatParts(ctx, ast) {
102
- const body = resolveBody(ast);
103
- if (body == null) {
104
- throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
105
- }
106
- const type = resolveType(body);
107
- if (type === 1 /* NodeTypes.Plural */) {
108
- const plural = body;
109
- const cases = resolveCases(plural);
110
- return ctx.plural(cases.reduce((messages, c) => [
111
- ...messages,
112
- formatMessageParts(ctx, c)
113
- ], []));
114
- }
115
- else {
116
- return formatMessageParts(ctx, body);
117
- }
83
+ const body = resolveBody(ast);
84
+ if (body == null) throw createUnhandleNodeError(NodeTypes.Resource);
85
+ if (resolveType(body) === NodeTypes.Plural) {
86
+ const cases = resolveCases(body);
87
+ return ctx.plural(cases.reduce((messages, c) => [...isArray(messages) ? messages : [messages], formatMessageParts(ctx, c)], []));
88
+ } else return formatMessageParts(ctx, body);
118
89
  }
119
90
  function formatMessageParts(ctx, node) {
120
- const static_ = resolveStatic(node);
121
- if (static_ != null) {
122
- return ctx.type === 'text'
123
- ? static_
124
- : ctx.normalize([static_]);
125
- }
126
- else {
127
- const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
128
- return ctx.normalize(messages);
129
- }
91
+ const static_ = resolveStatic(node);
92
+ if (static_ != null) return ctx.type === "text" ? static_ : ctx.normalize([static_]);
93
+ else {
94
+ const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
95
+ return ctx.normalize(messages);
96
+ }
130
97
  }
131
98
  function formatMessagePart(ctx, node) {
132
- const type = resolveType(node);
133
- switch (type) {
134
- case 3 /* NodeTypes.Text */: {
135
- return resolveValue$1(node, type);
136
- }
137
- case 9 /* NodeTypes.Literal */: {
138
- return resolveValue$1(node, type);
139
- }
140
- case 4 /* NodeTypes.Named */: {
141
- const named = node;
142
- if (hasOwn(named, 'k') && named.k) {
143
- return ctx.interpolate(ctx.named(named.k));
144
- }
145
- if (hasOwn(named, 'key') && named.key) {
146
- return ctx.interpolate(ctx.named(named.key));
147
- }
148
- throw createUnhandleNodeError(type);
149
- }
150
- case 5 /* NodeTypes.List */: {
151
- const list = node;
152
- if (hasOwn(list, 'i') && isNumber(list.i)) {
153
- return ctx.interpolate(ctx.list(list.i));
154
- }
155
- if (hasOwn(list, 'index') && isNumber(list.index)) {
156
- return ctx.interpolate(ctx.list(list.index));
157
- }
158
- throw createUnhandleNodeError(type);
159
- }
160
- case 6 /* NodeTypes.Linked */: {
161
- const linked = node;
162
- const modifier = resolveLinkedModifier(linked);
163
- const key = resolveLinkedKey(linked);
164
- return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
165
- }
166
- case 7 /* NodeTypes.LinkedKey */: {
167
- return resolveValue$1(node, type);
168
- }
169
- case 8 /* NodeTypes.LinkedModifier */: {
170
- return resolveValue$1(node, type);
171
- }
172
- default:
173
- throw new Error(`unhandled node on format message part: ${type}`);
174
- }
175
- }
176
-
99
+ const type = resolveType(node);
100
+ switch (type) {
101
+ case NodeTypes.Text: return resolveValue$1(node, type);
102
+ case NodeTypes.Literal: return resolveValue$1(node, type);
103
+ case NodeTypes.Named: {
104
+ const named = node;
105
+ if (hasOwn(named, "k") && named.k) return ctx.interpolate(ctx.named(named.k));
106
+ if (hasOwn(named, "key") && named.key) return ctx.interpolate(ctx.named(named.key));
107
+ throw createUnhandleNodeError(type);
108
+ }
109
+ case NodeTypes.List: {
110
+ const list = node;
111
+ if (hasOwn(list, "i") && isNumber(list.i)) return ctx.interpolate(ctx.list(list.i));
112
+ if (hasOwn(list, "index") && isNumber(list.index)) return ctx.interpolate(ctx.list(list.index));
113
+ throw createUnhandleNodeError(type);
114
+ }
115
+ case NodeTypes.Linked: {
116
+ const linked = node;
117
+ const modifier = resolveLinkedModifier(linked);
118
+ const key = resolveLinkedKey(linked);
119
+ return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : void 0, ctx.type);
120
+ }
121
+ case NodeTypes.LinkedKey: return resolveValue$1(node, type);
122
+ case NodeTypes.LinkedModifier: return resolveValue$1(node, type);
123
+ default: throw new Error(`unhandled node on format message part: ${type}`);
124
+ }
125
+ }
126
+ //#endregion
127
+ //#region packages/core-base/src/compilation.ts
177
128
  const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
178
129
  function checkHtmlMessage(source, warnHtmlMessage) {
179
- if (warnHtmlMessage && detectHtmlTag(source)) {
180
- warn(format$1(WARN_MESSAGE, { source }));
181
- }
130
+ if (warnHtmlMessage && detectHtmlTag(source)) warn(format(WARN_MESSAGE, { source }));
182
131
  }
183
132
  const defaultOnCacheKey = (message) => message;
184
133
  let compileCache = create();
185
134
  function clearCompileCache() {
186
- compileCache = create();
135
+ compileCache = create();
187
136
  }
188
137
  function baseCompile(message, options = {}) {
189
- // error detecting on compile
190
- let detectError = false;
191
- const onError = options.onError || defaultOnError;
192
- options.onError = (err) => {
193
- detectError = true;
194
- onError(err);
195
- };
196
- // parse source codes
197
- const parser = createParser(options);
198
- const ast = parser.parse(message);
199
- // optimize ASTs
200
- options.optimize && optimize(ast);
201
- // minimize ASTs
202
- options.mangle && mangle(ast);
203
- return { ast, detectError, code: '' };
204
- }
205
- /* #__NO_SIDE_EFFECTS__ */
138
+ let detectError = false;
139
+ const onError = options.onError || defaultOnError;
140
+ options.onError = (err) => {
141
+ detectError = true;
142
+ onError(err);
143
+ };
144
+ const ast = createParser(options).parse(message);
145
+ options.optimize && optimize(ast);
146
+ options.mangle && mangle(ast);
147
+ return {
148
+ ast,
149
+ detectError,
150
+ code: ""
151
+ };
152
+ }
153
+ /* @__NO_SIDE_EFFECTS__ */
206
154
  function compile(message, context) {
207
- if ((!__INTLIFY_DROP_MESSAGE_COMPILER__) &&
208
- isString(message)) {
209
- // check HTML message
210
- const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
211
- ? context.warnHtmlMessage
212
- : true;
213
- (process.env.NODE_ENV !== 'production') && checkHtmlMessage(message, warnHtmlMessage);
214
- // check caches
215
- const onCacheKey = context.onCacheKey || defaultOnCacheKey;
216
- const cacheKey = onCacheKey(message);
217
- const cached = compileCache[cacheKey];
218
- if (cached) {
219
- return cached;
220
- }
221
- // compile message
222
- const { ast, detectError } = baseCompile(message, {
223
- ...context,
224
- location: (process.env.NODE_ENV !== 'production'),
225
- mangle: !(process.env.NODE_ENV !== 'production'),
226
- optimize: !(process.env.NODE_ENV !== 'production')
227
- });
228
- // compose message function from AST
229
- const msg = format(ast);
230
- // if occurred compile error, don't cache
231
- return !detectError
232
- ? (compileCache[cacheKey] = msg)
233
- : msg;
234
- }
235
- else {
236
- if ((process.env.NODE_ENV !== 'production') && !isMessageAST(message)) {
237
- warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
238
- return (() => message);
239
- }
240
- // AST case (passed from bundler)
241
- const cacheKey = message.cacheKey;
242
- if (cacheKey) {
243
- const cached = compileCache[cacheKey];
244
- if (cached) {
245
- return cached;
246
- }
247
- // compose message function from message (AST)
248
- return (compileCache[cacheKey] =
249
- format(message));
250
- }
251
- else {
252
- return format(message);
253
- }
254
- }
255
- }
256
-
257
- let devtools = null;
258
- function setDevToolsHook(hook) {
259
- devtools = hook;
260
- }
261
- function getDevToolsHook() {
262
- return devtools;
263
- }
264
- function initI18nDevTools(i18n, version, meta) {
265
- // TODO: queue if devtools is undefined
266
- devtools &&
267
- devtools.emit('i18n:init', {
268
- timestamp: Date.now(),
269
- i18n,
270
- version,
271
- meta
272
- });
273
- }
274
- const translateDevTools =
275
- /* #__PURE__*/ createDevToolsHook('function:translate');
276
- function createDevToolsHook(hook) {
277
- return (payloads) => devtools && devtools.emit(hook, payloads);
278
- }
279
-
155
+ if (!__INTLIFY_DROP_MESSAGE_COMPILER__ && isString(message)) {
156
+ const warnHtmlMessage = isBoolean(context.warnHtmlMessage) ? context.warnHtmlMessage : true(true) && checkHtmlMessage(message, warnHtmlMessage);
157
+ const cacheKey = (context.onCacheKey || defaultOnCacheKey)(message);
158
+ const cached = compileCache[cacheKey];
159
+ if (cached) return cached;
160
+ const { ast, detectError } = baseCompile(message, {
161
+ ...context,
162
+ location: true,
163
+ mangle: false,
164
+ optimize: false
165
+ });
166
+ const msg = format$1(ast);
167
+ return !detectError ? compileCache[cacheKey] = msg : msg;
168
+ } else {
169
+ if (!isMessageAST(message)) {
170
+ warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
171
+ return (() => message);
172
+ }
173
+ const cacheKey = message.cacheKey;
174
+ if (cacheKey) {
175
+ const cached = compileCache[cacheKey];
176
+ if (cached) return cached;
177
+ return compileCache[cacheKey] = format$1(message);
178
+ } else return format$1(message);
179
+ }
180
+ }
181
+ //#endregion
182
+ //#region packages/core-base/src/errors.ts
280
183
  const CoreErrorCodes = {
281
- INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT, // 17
282
- INVALID_DATE_ARGUMENT: 18,
283
- INVALID_ISO_DATE_ARGUMENT: 19,
284
- NOT_SUPPORT_NON_STRING_MESSAGE: 20,
285
- NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
286
- NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
287
- NOT_SUPPORT_LOCALE_TYPE: 23
184
+ INVALID_ARGUMENT: COMPILE_ERROR_CODES_EXTEND_POINT,
185
+ INVALID_DATE_ARGUMENT: 18,
186
+ INVALID_ISO_DATE_ARGUMENT: 19,
187
+ NOT_SUPPORT_NON_STRING_MESSAGE: 20,
188
+ NOT_SUPPORT_LOCALE_PROMISE_VALUE: 21,
189
+ NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: 22,
190
+ NOT_SUPPORT_LOCALE_TYPE: 23
288
191
  };
289
192
  const CORE_ERROR_CODES_EXTEND_POINT = 24;
290
193
  function createCoreError(code) {
291
- return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages } : undefined);
194
+ return createCompileError$1(code, null, { messages: errorMessages });
292
195
  }
293
196
  /** @internal */
294
197
  const errorMessages = {
295
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
296
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
297
- 'Make sure your Date represents a valid date.',
298
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
299
- [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
300
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
301
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
302
- [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
198
+ [CoreErrorCodes.INVALID_ARGUMENT]: "Invalid arguments",
199
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: "The date provided is an invalid Date object.Make sure your Date represents a valid date.",
200
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: "The argument provided is not a valid ISO date string",
201
+ [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: "Not support non-string message",
202
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: "cannot support promise value",
203
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: "cannot support async function",
204
+ [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: "cannot support locale type"
303
205
  };
304
-
206
+ //#endregion
207
+ //#region packages/core-base/src/fallbacker.ts
305
208
  /** @internal */
306
209
  function getLocale(context, options) {
307
- return options.locale != null
308
- ? resolveLocale(options.locale)
309
- : resolveLocale(context.locale);
210
+ return options.locale != null ? resolveLocale(options.locale) : resolveLocale(context.locale);
310
211
  }
311
212
  let _resolveLocale;
312
213
  /** @internal */
313
214
  function resolveLocale(locale) {
314
- if (isString(locale)) {
315
- return locale;
316
- }
317
- else {
318
- if (isFunction(locale)) {
319
- if (locale.resolvedOnce && _resolveLocale != null) {
320
- return _resolveLocale;
321
- }
322
- else if (locale.constructor.name === 'Function') {
323
- const resolve = locale();
324
- if (isPromise(resolve)) {
325
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
326
- }
327
- return (_resolveLocale = resolve);
328
- }
329
- else {
330
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
331
- }
332
- }
333
- else {
334
- throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
335
- }
336
- }
215
+ if (isString(locale)) return locale;
216
+ else if (isFunction(locale)) if (locale.resolvedOnce && _resolveLocale != null) return _resolveLocale;
217
+ else if (locale.constructor.name === "Function") {
218
+ const resolve = locale();
219
+ if (isPromise(resolve)) throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
220
+ return _resolveLocale = resolve;
221
+ } else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
222
+ else throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
337
223
  }
338
224
  /**
339
- * Fallback with simple implemenation
340
- *
341
- * @remarks
342
- * A fallback locale function implemented with a simple fallback algorithm.
343
- *
344
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
345
- *
346
- * @param ctx - A {@link CoreContext | context}
347
- * @param fallback - A {@link FallbackLocale | fallback locale}
348
- * @param start - A starting {@link Locale | locale}
349
- *
350
- * @returns Fallback locales
351
- *
352
- * @VueI18nGeneral
353
- */
354
- function fallbackWithSimple(ctx, fallback, start) {
355
- // prettier-ignore
356
- return [...new Set([
357
- start,
358
- ...(isArray(fallback)
359
- ? fallback
360
- : isObject(fallback)
361
- ? Object.keys(fallback)
362
- : isString(fallback)
363
- ? [fallback]
364
- : [start])
365
- ])];
225
+ * Fallback with simple implemenation
226
+ *
227
+ * @remarks
228
+ * A fallback locale function implemented with a simple fallback algorithm.
229
+ *
230
+ * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
231
+ *
232
+ * @param ctx - A {@link CoreContext | context}
233
+ * @param fallback - A {@link FallbackLocale | fallback locale}
234
+ * @param start - A starting {@link Locale | locale}
235
+ *
236
+ * @returns Fallback locales
237
+ *
238
+ * @VueI18nGeneral
239
+ */
240
+ function fallbackWithSimple(_ctx, fallback, start) {
241
+ return [...new Set([start, ...isArray(fallback) ? fallback : isObject(fallback) ? Object.keys(fallback) : isString(fallback) ? [fallback] : [start]])];
366
242
  }
367
243
  /**
368
- * Fallback with locale chain
369
- *
370
- * @remarks
371
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
372
- *
373
- * @param ctx - A {@link CoreContext | context}
374
- * @param fallback - A {@link FallbackLocale | fallback locale}
375
- * @param start - A starting {@link Locale | locale}
376
- *
377
- * @returns Fallback locales
378
- *
379
- * @VueI18nSee [Fallbacking](../../guide/essentials/fallback)
380
- *
381
- * @VueI18nGeneral
382
- */
244
+ * Fallback with locale chain
245
+ *
246
+ * @remarks
247
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
248
+ *
249
+ * @param ctx - A {@link CoreContext | context}
250
+ * @param fallback - A {@link FallbackLocale | fallback locale}
251
+ * @param start - A starting {@link Locale | locale}
252
+ *
253
+ * @returns Fallback locales
254
+ *
255
+ * @VueI18nSee [Fallbacking](../../guide/essentials/fallback)
256
+ *
257
+ * @VueI18nGeneral
258
+ */
383
259
  function fallbackWithLocaleChain(ctx, fallback, start) {
384
- const startLocale = isString(start) ? start : DEFAULT_LOCALE;
385
- const context = ctx;
386
- if (!context.__localeChainCache) {
387
- context.__localeChainCache = new Map();
388
- }
389
- let chain = context.__localeChainCache.get(startLocale);
390
- if (!chain) {
391
- chain = [];
392
- // first block defined by start
393
- let block = [start];
394
- // while any intervening block found
395
- while (isArray(block)) {
396
- block = appendBlockToChain(chain, block, fallback);
397
- }
398
- // prettier-ignore
399
- // last block defined by default
400
- const defaults = isArray(fallback) || !isPlainObject(fallback)
401
- ? fallback
402
- : fallback['default']
403
- ? fallback['default']
404
- : null;
405
- // convert defaults to array
406
- block = isString(defaults) ? [defaults] : defaults;
407
- if (isArray(block)) {
408
- appendBlockToChain(chain, block, false);
409
- }
410
- context.__localeChainCache.set(startLocale, chain);
411
- }
412
- return chain;
260
+ const startLocale = isString(start) ? start : DEFAULT_LOCALE;
261
+ const context = ctx;
262
+ if (!context.__localeChainCache) context.__localeChainCache = /* @__PURE__ */ new Map();
263
+ let chain = context.__localeChainCache.get(startLocale);
264
+ if (!chain) {
265
+ chain = [];
266
+ let block = [start];
267
+ while (isArray(block)) block = appendBlockToChain(chain, block, fallback);
268
+ const defaults = isArray(fallback) || !isPlainObject(fallback) ? fallback : fallback["default"] ? fallback["default"] : null;
269
+ block = isString(defaults) ? [defaults] : defaults;
270
+ if (isArray(block)) appendBlockToChain(chain, block, false);
271
+ context.__localeChainCache.set(startLocale, chain);
272
+ }
273
+ return chain;
413
274
  }
414
275
  function appendBlockToChain(chain, block, blocks) {
415
- let follow = true;
416
- for (let i = 0; i < block.length && isBoolean(follow); i++) {
417
- const locale = block[i];
418
- if (isString(locale)) {
419
- follow = appendLocaleToChain(chain, block[i], blocks);
420
- }
421
- }
422
- return follow;
276
+ let follow = true;
277
+ for (let i = 0; i < block.length && isBoolean(follow); i++) {
278
+ const locale = block[i];
279
+ if (isString(locale)) follow = appendLocaleToChain(chain, block[i], blocks);
280
+ }
281
+ return follow;
423
282
  }
424
283
  function appendLocaleToChain(chain, locale, blocks) {
425
- let follow;
426
- const tokens = locale.split('-');
427
- do {
428
- const target = tokens.join('-');
429
- follow = appendItemToChain(chain, target, blocks);
430
- tokens.splice(-1, 1);
431
- } while (tokens.length && follow === true);
432
- return follow;
284
+ let follow;
285
+ const tokens = locale.split("-");
286
+ do {
287
+ follow = appendItemToChain(chain, tokens.join("-"), blocks);
288
+ tokens.splice(-1, 1);
289
+ } while (tokens.length && follow === true);
290
+ return follow;
433
291
  }
434
292
  function appendItemToChain(chain, target, blocks) {
435
- let follow = false;
436
- if (!chain.includes(target)) {
437
- follow = true;
438
- if (target) {
439
- follow = target[target.length - 1] !== '!';
440
- const locale = target.replace(/!/g, '');
441
- chain.push(locale);
442
- if ((isArray(blocks) || isPlainObject(blocks)) &&
443
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
444
- ) {
445
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
446
- follow = blocks[locale];
447
- }
448
- }
449
- }
450
- return follow;
451
- }
452
-
293
+ let follow = false;
294
+ if (!chain.includes(target)) {
295
+ follow = true;
296
+ if (target) {
297
+ follow = target[target.length - 1] !== "!";
298
+ const locale = target.replace(/!/g, "");
299
+ chain.push(locale);
300
+ if ((isArray(blocks) || isPlainObject(blocks)) && blocks[locale]) follow = blocks[locale];
301
+ }
302
+ }
303
+ return follow;
304
+ }
305
+ //#endregion
306
+ //#region packages/core-base/src/resolver.ts
453
307
  const pathStateMachine = [];
454
- pathStateMachine[0 /* States.BEFORE_PATH */] = {
455
- ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
456
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
457
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
458
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
308
+ pathStateMachine[0] = {
309
+ ["w"]: [0],
310
+ ["i"]: [3, 0],
311
+ ["["]: [4],
312
+ ["o"]: [7]
459
313
  };
460
- pathStateMachine[1 /* States.IN_PATH */] = {
461
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
462
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
463
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
464
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
314
+ pathStateMachine[1] = {
315
+ ["w"]: [1],
316
+ ["."]: [2],
317
+ ["["]: [4],
318
+ ["o"]: [7]
465
319
  };
466
- pathStateMachine[2 /* States.BEFORE_IDENT */] = {
467
- ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
468
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
469
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
320
+ pathStateMachine[2] = {
321
+ ["w"]: [2],
322
+ ["i"]: [3, 0],
323
+ ["0"]: [3, 0]
470
324
  };
471
- pathStateMachine[3 /* States.IN_IDENT */] = {
472
- ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
473
- ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
474
- ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
475
- ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
476
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
477
- ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
325
+ pathStateMachine[3] = {
326
+ ["i"]: [3, 0],
327
+ ["0"]: [3, 0],
328
+ ["w"]: [1, 1],
329
+ ["."]: [2, 1],
330
+ ["["]: [4, 1],
331
+ ["o"]: [7, 1]
478
332
  };
479
- pathStateMachine[4 /* States.IN_SUB_PATH */] = {
480
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
481
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
482
- ["[" /* PathCharTypes.LEFT_BRACKET */]: [
483
- 4 /* States.IN_SUB_PATH */,
484
- 2 /* Actions.INC_SUB_PATH_DEPTH */
485
- ],
486
- ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
487
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
488
- ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
333
+ pathStateMachine[4] = {
334
+ ["'"]: [5, 0],
335
+ ["\""]: [6, 0],
336
+ ["["]: [4, 2],
337
+ ["]"]: [1, 3],
338
+ ["o"]: 8,
339
+ ["l"]: [4, 0]
489
340
  };
490
- pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
491
- ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
492
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
493
- ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
341
+ pathStateMachine[5] = {
342
+ ["'"]: [4, 0],
343
+ ["o"]: 8,
344
+ ["l"]: [5, 0]
494
345
  };
495
- pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
496
- ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
497
- ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
498
- ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
346
+ pathStateMachine[6] = {
347
+ ["\""]: [4, 0],
348
+ ["o"]: 8,
349
+ ["l"]: [6, 0]
499
350
  };
500
351
  /**
501
- * Check if an expression is a literal value.
502
- */
352
+ * Check if an expression is a literal value.
353
+ */
503
354
  const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
504
355
  function isLiteral(exp) {
505
- return literalValueRE.test(exp);
356
+ return literalValueRE.test(exp);
506
357
  }
507
358
  /**
508
- * Strip quotes from a string
509
- */
359
+ * Strip quotes from a string
360
+ */
510
361
  function stripQuotes(str) {
511
- const a = str.charCodeAt(0);
512
- const b = str.charCodeAt(str.length - 1);
513
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
362
+ const a = str.charCodeAt(0);
363
+ return a === str.charCodeAt(str.length - 1) && (a === 34 || a === 39) ? str.slice(1, -1) : str;
514
364
  }
515
365
  /**
516
- * Determine the type of a character in a keypath.
517
- */
366
+ * Determine the type of a character in a keypath.
367
+ */
518
368
  function getPathCharType(ch) {
519
- if (ch === undefined || ch === null) {
520
- return "o" /* PathCharTypes.END_OF_FAIL */;
521
- }
522
- const code = ch.charCodeAt(0);
523
- switch (code) {
524
- case 0x5b: // [
525
- case 0x5d: // ]
526
- case 0x2e: // .
527
- case 0x22: // "
528
- case 0x27: // '
529
- return ch;
530
- case 0x5f: // _
531
- case 0x24: // $
532
- case 0x2d: // -
533
- return "i" /* PathCharTypes.IDENT */;
534
- case 0x09: // Tab (HT)
535
- case 0x0a: // Newline (LF)
536
- case 0x0d: // Return (CR)
537
- case 0xa0: // No-break space (NBSP)
538
- case 0xfeff: // Byte Order Mark (BOM)
539
- case 0x2028: // Line Separator (LS)
540
- case 0x2029: // Paragraph Separator (PS)
541
- return "w" /* PathCharTypes.WORKSPACE */;
542
- }
543
- return "i" /* PathCharTypes.IDENT */;
369
+ if (ch === void 0 || ch === null) return "o";
370
+ switch (ch.charCodeAt(0)) {
371
+ case 91:
372
+ case 93:
373
+ case 46:
374
+ case 34:
375
+ case 39: return ch;
376
+ case 95:
377
+ case 36:
378
+ case 45: return "i";
379
+ case 9:
380
+ case 10:
381
+ case 13:
382
+ case 160:
383
+ case 65279:
384
+ case 8232:
385
+ case 8233: return "w";
386
+ }
387
+ return "i";
544
388
  }
545
389
  /**
546
- * Format a subPath, return its plain form if it is
547
- * a literal string or number. Otherwise prepend the
548
- * dynamic indicator (*).
549
- */
390
+ * Format a subPath, return its plain form if it is
391
+ * a literal string or number. Otherwise prepend the
392
+ * dynamic indicator (*).
393
+ */
550
394
  function formatSubPath(path) {
551
- const trimmed = path.trim();
552
- // invalid leading 0
553
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
554
- return false;
555
- }
556
- return isLiteral(trimmed)
557
- ? stripQuotes(trimmed)
558
- : "*" /* PathCharTypes.ASTARISK */ + trimmed;
395
+ const trimmed = path.trim();
396
+ if (path.charAt(0) === "0" && isNaN(parseInt(path))) return false;
397
+ return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" + trimmed;
559
398
  }
560
399
  /**
561
- * Parse a string path into an array of segments
562
- */
400
+ * Parse a string path into an array of segments
401
+ */
563
402
  function parse(path) {
564
- const keys = [];
565
- let index = -1;
566
- let mode = 0 /* States.BEFORE_PATH */;
567
- let subPathDepth = 0;
568
- let c;
569
- let key; // eslint-disable-line
570
- let newChar;
571
- let type;
572
- let transition;
573
- let action;
574
- let typeMap;
575
- const actions = [];
576
- actions[0 /* Actions.APPEND */] = () => {
577
- if (key === undefined) {
578
- key = newChar;
579
- }
580
- else {
581
- key += newChar;
582
- }
583
- };
584
- actions[1 /* Actions.PUSH */] = () => {
585
- if (key !== undefined) {
586
- keys.push(key);
587
- key = undefined;
588
- }
589
- };
590
- actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
591
- actions[0 /* Actions.APPEND */]();
592
- subPathDepth++;
593
- };
594
- actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
595
- if (subPathDepth > 0) {
596
- subPathDepth--;
597
- mode = 4 /* States.IN_SUB_PATH */;
598
- actions[0 /* Actions.APPEND */]();
599
- }
600
- else {
601
- subPathDepth = 0;
602
- if (key === undefined) {
603
- return false;
604
- }
605
- key = formatSubPath(key);
606
- if (key === false) {
607
- return false;
608
- }
609
- else {
610
- actions[1 /* Actions.PUSH */]();
611
- }
612
- }
613
- };
614
- function maybeUnescapeQuote() {
615
- const nextChar = path[index + 1];
616
- if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
617
- nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
618
- (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
619
- nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
620
- index++;
621
- newChar = '\\' + nextChar;
622
- actions[0 /* Actions.APPEND */]();
623
- return true;
624
- }
625
- }
626
- while (mode !== null) {
627
- index++;
628
- c = path[index];
629
- if (c === '\\' && maybeUnescapeQuote()) {
630
- continue;
631
- }
632
- type = getPathCharType(c);
633
- typeMap = pathStateMachine[mode];
634
- transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
635
- // check parse error
636
- if (transition === 8 /* States.ERROR */) {
637
- return;
638
- }
639
- mode = transition[0];
640
- if (transition[1] !== undefined) {
641
- action = actions[transition[1]];
642
- if (action) {
643
- newChar = c;
644
- if (action() === false) {
645
- return;
646
- }
647
- }
648
- }
649
- // check parse finish
650
- if (mode === 7 /* States.AFTER_PATH */) {
651
- return keys;
652
- }
653
- }
654
- }
655
- // path token cache
656
- const cache = new Map();
403
+ const keys = [];
404
+ let index = -1;
405
+ let mode = 0;
406
+ let subPathDepth = 0;
407
+ let c;
408
+ let key;
409
+ let newChar;
410
+ let type;
411
+ let transition;
412
+ let action;
413
+ let typeMap;
414
+ const actions = [];
415
+ actions[0] = () => {
416
+ if (key === void 0) key = newChar;
417
+ else key += newChar;
418
+ };
419
+ actions[1] = () => {
420
+ if (key !== void 0) {
421
+ keys.push(key);
422
+ key = void 0;
423
+ }
424
+ };
425
+ actions[2] = () => {
426
+ actions[0]();
427
+ subPathDepth++;
428
+ };
429
+ actions[3] = () => {
430
+ if (subPathDepth > 0) {
431
+ subPathDepth--;
432
+ mode = 4;
433
+ actions[0]();
434
+ } else {
435
+ subPathDepth = 0;
436
+ if (key === void 0) return false;
437
+ key = formatSubPath(key);
438
+ if (key === false) return false;
439
+ else actions[1]();
440
+ }
441
+ };
442
+ function maybeUnescapeQuote() {
443
+ const nextChar = path[index + 1];
444
+ if (mode === 5 && nextChar === "'" || mode === 6 && nextChar === "\"") {
445
+ index++;
446
+ newChar = "\\" + nextChar;
447
+ actions[0]();
448
+ return true;
449
+ }
450
+ }
451
+ while (mode !== null) {
452
+ index++;
453
+ c = path[index];
454
+ if (c === "\\" && maybeUnescapeQuote()) continue;
455
+ type = getPathCharType(c);
456
+ typeMap = pathStateMachine[mode];
457
+ transition = typeMap[type] || typeMap["l"] || 8;
458
+ if (transition === 8) return;
459
+ mode = transition[0];
460
+ if (transition[1] !== void 0) {
461
+ action = actions[transition[1]];
462
+ if (action) {
463
+ newChar = c;
464
+ if (action() === false) return;
465
+ }
466
+ }
467
+ if (mode === 7) return keys;
468
+ }
469
+ }
470
+ const cache = /* @__PURE__ */ new Map();
657
471
  /**
658
- * key-value message resolver
659
- *
660
- * @remarks
661
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
662
- *
663
- * @param obj - A target object to be resolved with path
664
- * @param path - A {@link Path | path} to resolve the value of message
665
- *
666
- * @returns A resolved {@link PathValue | path value}
667
- *
668
- * @VueI18nGeneral
669
- */
472
+ * key-value message resolver
473
+ *
474
+ * @remarks
475
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
476
+ *
477
+ * @param obj - A target object to be resolved with path
478
+ * @param path - A {@link Path | path} to resolve the value of message
479
+ *
480
+ * @returns A resolved {@link PathValue | path value}
481
+ *
482
+ * @VueI18nGeneral
483
+ */
670
484
  function resolveWithKeyValue(obj, path) {
671
- return isObject(obj) ? obj[path] : null;
485
+ return isObject(obj) ? obj[path] : null;
672
486
  }
673
487
  /**
674
- * message resolver
675
- *
676
- * @remarks
677
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
678
- *
679
- * @param obj - A target object to be resolved with path
680
- * @param path - A {@link Path | path} to resolve the value of message
681
- *
682
- * @returns A resolved {@link PathValue | path value}
683
- *
684
- * @VueI18nGeneral
685
- */
488
+ * message resolver
489
+ *
490
+ * @remarks
491
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
492
+ *
493
+ * @param obj - A target object to be resolved with path
494
+ * @param path - A {@link Path | path} to resolve the value of message
495
+ *
496
+ * @returns A resolved {@link PathValue | path value}
497
+ *
498
+ * @VueI18nGeneral
499
+ */
686
500
  function resolveValue(obj, path) {
687
- // check object
688
- if (!isObject(obj)) {
689
- return null;
690
- }
691
- // parse path
692
- let hit = cache.get(path);
693
- if (!hit) {
694
- hit = parse(path);
695
- if (hit) {
696
- cache.set(path, hit);
697
- }
698
- }
699
- // check hit
700
- if (!hit) {
701
- return null;
702
- }
703
- // resolve path value
704
- const len = hit.length;
705
- let last = obj;
706
- let i = 0;
707
- while (i < len) {
708
- const key = hit[i];
709
- /**
710
- * NOTE:
711
- * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
712
- * because the AST node is not a key-value structure.
713
- */
714
- if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
715
- return null;
716
- }
717
- const val = last[key];
718
- if (val === undefined) {
719
- return null;
720
- }
721
- if (isFunction(last)) {
722
- return null;
723
- }
724
- last = val;
725
- i++;
726
- }
727
- return last;
728
- }
729
-
501
+ if (!isObject(obj)) return null;
502
+ let hit = cache.get(path);
503
+ if (!hit) {
504
+ hit = parse(path);
505
+ if (hit) cache.set(path, hit);
506
+ }
507
+ if (!hit) return null;
508
+ const len = hit.length;
509
+ let last = obj;
510
+ let i = 0;
511
+ while (i < len) {
512
+ const key = hit[i];
513
+ /**
514
+ * NOTE:
515
+ * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
516
+ * because the AST node is not a key-value structure.
517
+ */
518
+ if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) return null;
519
+ if (!isObject(last)) return null;
520
+ if (!hasOwn(last, key)) return null;
521
+ const val = last[key];
522
+ if (val === void 0) return null;
523
+ if (isFunction(last)) return null;
524
+ last = val;
525
+ i++;
526
+ }
527
+ return last;
528
+ }
529
+ //#endregion
530
+ //#region packages/core-base/src/warnings.ts
730
531
  const CoreWarnCodes = {
731
- NOT_FOUND_KEY: 1,
732
- FALLBACK_TO_TRANSLATE: 2,
733
- CANNOT_FORMAT_NUMBER: 3,
734
- FALLBACK_TO_NUMBER_FORMAT: 4,
735
- CANNOT_FORMAT_DATE: 5,
736
- FALLBACK_TO_DATE_FORMAT: 6,
737
- EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7
532
+ NOT_FOUND_KEY: 1,
533
+ FALLBACK_TO_TRANSLATE: 2,
534
+ CANNOT_FORMAT_NUMBER: 3,
535
+ FALLBACK_TO_NUMBER_FORMAT: 4,
536
+ CANNOT_FORMAT_DATE: 5,
537
+ FALLBACK_TO_DATE_FORMAT: 6,
538
+ EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
539
+ INVALID_NUMBER_ARGUMENT: 8,
540
+ INVALID_DATE_ARGUMENT: 9
738
541
  };
739
- const CORE_WARN_CODES_EXTEND_POINT = 8;
542
+ const CORE_WARN_CODES_EXTEND_POINT = 10;
740
543
  /** @internal */
741
544
  const warnMessages = {
742
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
743
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
744
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
745
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
746
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
747
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
748
- [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
545
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
546
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
547
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
548
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
549
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
550
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
551
+ [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`,
552
+ [CoreWarnCodes.INVALID_NUMBER_ARGUMENT]: `Invalid argument for number formatting: expected a number but received '{value}'.`,
553
+ [CoreWarnCodes.INVALID_DATE_ARGUMENT]: `Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'.`
749
554
  };
750
555
  function getWarnMessage(code, ...args) {
751
- return format$1(warnMessages[code], ...args);
556
+ return format(warnMessages[code], ...args);
752
557
  }
753
-
754
- /* eslint-disable @typescript-eslint/no-explicit-any */
558
+ //#endregion
559
+ //#region packages/core-base/src/context.ts
755
560
  /**
756
- * Intlify core-base version
757
- * @internal
758
- */
759
- const VERSION = '12.0.0-alpha.3';
561
+ * Intlify core-base version
562
+ * @internal
563
+ */
564
+ const VERSION = "12.0.0-alpha.4";
760
565
  const NOT_RESOLVED = -1;
761
- const DEFAULT_LOCALE = 'en-US';
762
- const MISSING_RESOLVE_VALUE = '';
566
+ const DEFAULT_LOCALE = "en-US";
567
+ const MISSING_RESOLVE_VALUE = "";
763
568
  const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
764
569
  function getDefaultLinkedModifiers() {
765
- return {
766
- upper: (val, type) => {
767
- // prettier-ignore
768
- return type === 'text' && isString(val)
769
- ? val.toUpperCase()
770
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
771
- ? val.children.toUpperCase()
772
- : val;
773
- },
774
- lower: (val, type) => {
775
- // prettier-ignore
776
- return type === 'text' && isString(val)
777
- ? val.toLowerCase()
778
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
779
- ? val.children.toLowerCase()
780
- : val;
781
- },
782
- capitalize: (val, type) => {
783
- // prettier-ignore
784
- return (type === 'text' && isString(val)
785
- ? capitalize(val)
786
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
787
- ? capitalize(val.children)
788
- : val);
789
- }
790
- };
570
+ return {
571
+ upper: (val, type) => {
572
+ return type === "text" && isString(val) ? val.toUpperCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toUpperCase() : val;
573
+ },
574
+ lower: (val, type) => {
575
+ return type === "text" && isString(val) ? val.toLowerCase() : type === "vnode" && isObject(val) && "__v_isVNode" in val ? val.children.toLowerCase() : val;
576
+ },
577
+ capitalize: (val, type) => {
578
+ return type === "text" && isString(val) ? capitalize(val) : type === "vnode" && isObject(val) && "__v_isVNode" in val ? capitalize(val.children) : val;
579
+ }
580
+ };
791
581
  }
792
582
  let _compiler;
583
+ /**
584
+ * Register the message compiler
585
+ *
586
+ * @param compiler - A {@link MessageCompiler} function
587
+ *
588
+ * @deprecated Use `messageCompiler` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
589
+ *
590
+ * @VueI18nGeneral
591
+ */
793
592
  function registerMessageCompiler(compiler) {
794
- _compiler = compiler;
593
+ warnOnce(`registerMessageCompiler is deprecated. Use 'messageCompiler' option of 'createI18n' or 'createCoreContext' instead.`);
594
+ _compiler = compiler;
795
595
  }
796
596
  let _resolver;
797
597
  /**
798
- * Register the message resolver
799
- *
800
- * @param resolver - A {@link MessageResolver} function
801
- *
802
- * @VueI18nGeneral
803
- */
598
+ * Register the message resolver
599
+ *
600
+ * @param resolver - A {@link MessageResolver} function
601
+ *
602
+ * @deprecated Use `messageResolver` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
603
+ *
604
+ * @VueI18nGeneral
605
+ */
804
606
  function registerMessageResolver(resolver) {
805
- _resolver = resolver;
607
+ warnOnce(`registerMessageResolver is deprecated. Use 'messageResolver' option of 'createI18n' or 'createCoreContext' instead.`);
608
+ _resolver = resolver;
806
609
  }
807
610
  let _fallbacker;
808
611
  /**
809
- * Register the locale fallbacker
810
- *
811
- * @param fallbacker - A {@link LocaleFallbacker} function
812
- *
813
- * @VueI18nGeneral
814
- */
612
+ * Register the locale fallbacker
613
+ *
614
+ * @param fallbacker - A {@link LocaleFallbacker} function
615
+ *
616
+ * @deprecated Use `localeFallbacker` option of `createI18n` or `createCoreContext` instead. This function will be removed in v13.
617
+ *
618
+ * @VueI18nGeneral
619
+ */
815
620
  function registerLocaleFallbacker(fallbacker) {
816
- _fallbacker = fallbacker;
621
+ warnOnce(`registerLocaleFallbacker is deprecated. Use 'localeFallbacker' option of 'createI18n' or 'createCoreContext' instead.`);
622
+ _fallbacker = fallbacker;
817
623
  }
818
- // Additional Meta for Intlify DevTools
819
- let _additionalMeta = null;
820
- /* #__NO_SIDE_EFFECTS__ */
821
- const setAdditionalMeta = (meta) => {
822
- _additionalMeta = meta;
823
- };
824
- /* #__NO_SIDE_EFFECTS__ */
825
- const getAdditionalMeta = () => _additionalMeta;
826
624
  let _fallbackContext = null;
827
625
  const setFallbackContext = (context) => {
828
- _fallbackContext = context;
626
+ _fallbackContext = context;
829
627
  };
830
628
  const getFallbackContext = () => _fallbackContext;
831
- // ID for CoreContext
832
629
  let _cid = 0;
833
630
  function createCoreContext(options = {}) {
834
- // setup options
835
- const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
836
- const version = isString(options.version) ? options.version : VERSION;
837
- const locale = isString(options.locale) || isFunction(options.locale)
838
- ? options.locale
839
- : DEFAULT_LOCALE;
840
- const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
841
- const fallbackLocale = isArray(options.fallbackLocale) ||
842
- isPlainObject(options.fallbackLocale) ||
843
- isString(options.fallbackLocale) ||
844
- options.fallbackLocale === false
845
- ? options.fallbackLocale
846
- : _locale;
847
- const messages = isPlainObject(options.messages)
848
- ? options.messages
849
- : createResources(_locale);
850
- const datetimeFormats = isPlainObject(options.datetimeFormats)
851
- ? options.datetimeFormats
852
- : createResources(_locale)
853
- ;
854
- const numberFormats = isPlainObject(options.numberFormats)
855
- ? options.numberFormats
856
- : createResources(_locale)
857
- ;
858
- const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
859
- const pluralRules = options.pluralRules || create();
860
- const missing = isFunction(options.missing) ? options.missing : null;
861
- const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
862
- ? options.missingWarn
863
- : true;
864
- const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
865
- ? options.fallbackWarn
866
- : true;
867
- const fallbackFormat = !!options.fallbackFormat;
868
- const unresolving = !!options.unresolving;
869
- const postTranslation = isFunction(options.postTranslation)
870
- ? options.postTranslation
871
- : null;
872
- const processor = isPlainObject(options.processor) ? options.processor : null;
873
- const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
874
- ? options.warnHtmlMessage
875
- : true;
876
- const escapeParameter = !!options.escapeParameter;
877
- const messageCompiler = isFunction(options.messageCompiler)
878
- ? options.messageCompiler
879
- : _compiler;
880
- if ((process.env.NODE_ENV !== 'production') &&
881
- !false &&
882
- !false &&
883
- isFunction(options.messageCompiler)) {
884
- warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
885
- }
886
- const messageResolver = isFunction(options.messageResolver)
887
- ? options.messageResolver
888
- : _resolver || resolveWithKeyValue;
889
- const localeFallbacker = isFunction(options.localeFallbacker)
890
- ? options.localeFallbacker
891
- : _fallbacker || fallbackWithSimple;
892
- const fallbackContext = isObject(options.fallbackContext)
893
- ? options.fallbackContext
894
- : undefined;
895
- // setup internal options
896
- const internalOptions = options;
897
- const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
898
- ? internalOptions.__datetimeFormatters
899
- : new Map()
900
- ;
901
- const __numberFormatters = isObject(internalOptions.__numberFormatters)
902
- ? internalOptions.__numberFormatters
903
- : new Map()
904
- ;
905
- const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
906
- _cid++;
907
- const context = {
908
- version,
909
- cid: _cid,
910
- locale,
911
- fallbackLocale,
912
- messages,
913
- modifiers,
914
- pluralRules,
915
- missing,
916
- missingWarn,
917
- fallbackWarn,
918
- fallbackFormat,
919
- unresolving,
920
- postTranslation,
921
- processor,
922
- warnHtmlMessage,
923
- escapeParameter,
924
- messageCompiler,
925
- messageResolver,
926
- localeFallbacker,
927
- fallbackContext,
928
- onWarn,
929
- __meta
930
- };
931
- {
932
- context.datetimeFormats = datetimeFormats;
933
- context.numberFormats = numberFormats;
934
- context.__datetimeFormatters = __datetimeFormatters;
935
- context.__numberFormatters = __numberFormatters;
936
- }
937
- // for vue-devtools timeline event
938
- if ((process.env.NODE_ENV !== 'production')) {
939
- context.__v_emitter =
940
- internalOptions.__v_emitter != null
941
- ? internalOptions.__v_emitter
942
- : undefined;
943
- }
944
- // NOTE: experimental !!
945
- if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
946
- initI18nDevTools(context, version, __meta);
947
- }
948
- return context;
631
+ const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
632
+ const version = isString(options.version) ? options.version : VERSION;
633
+ const locale = isString(options.locale) || isFunction(options.locale) ? options.locale : DEFAULT_LOCALE;
634
+ const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
635
+ const fallbackLocale = isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || isString(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : _locale;
636
+ const messages = isPlainObject(options.messages) ? options.messages : createResources(_locale);
637
+ const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : createResources(_locale);
638
+ const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : createResources(_locale);
639
+ const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
640
+ const pluralRules = options.pluralRules || create();
641
+ const missing = isFunction(options.missing) ? options.missing : null;
642
+ const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true;
643
+ const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true;
644
+ const fallbackFormat = !!options.fallbackFormat;
645
+ const unresolving = !!options.unresolving;
646
+ const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null;
647
+ const processor = isPlainObject(options.processor) ? options.processor : null;
648
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true;
649
+ const escapeParameter = !!options.escapeParameter;
650
+ const messageCompiler = isFunction(options.messageCompiler) ? options.messageCompiler : _compiler || null;
651
+ if (isFunction(options.messageCompiler)) warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
652
+ const messageResolver = isFunction(options.messageResolver) ? options.messageResolver : _resolver || resolveWithKeyValue;
653
+ const localeFallbacker = isFunction(options.localeFallbacker) ? options.localeFallbacker : _fallbacker || fallbackWithSimple;
654
+ const fallbackContext = isObject(options.fallbackContext) ? options.fallbackContext : void 0;
655
+ const internalOptions = options;
656
+ const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters) ? internalOptions.__datetimeFormatters : /* @__PURE__ */ new Map();
657
+ const __numberFormatters = isObject(internalOptions.__numberFormatters) ? internalOptions.__numberFormatters : /* @__PURE__ */ new Map();
658
+ _cid++;
659
+ const context = {
660
+ version,
661
+ cid: _cid,
662
+ locale,
663
+ fallbackLocale,
664
+ messages,
665
+ modifiers,
666
+ pluralRules,
667
+ missing,
668
+ missingWarn,
669
+ fallbackWarn,
670
+ fallbackFormat,
671
+ unresolving,
672
+ postTranslation,
673
+ processor,
674
+ warnHtmlMessage,
675
+ escapeParameter,
676
+ messageCompiler,
677
+ messageResolver,
678
+ localeFallbacker,
679
+ fallbackContext,
680
+ onWarn
681
+ };
682
+ context.datetimeFormats = datetimeFormats;
683
+ context.numberFormats = numberFormats;
684
+ context.__datetimeFormatters = __datetimeFormatters;
685
+ context.__numberFormatters = __numberFormatters;
686
+ context.__v_emitter = internalOptions.__v_emitter != null ? internalOptions.__v_emitter : void 0;
687
+ return context;
949
688
  }
950
689
  const createResources = (locale) => ({ [locale]: create() });
951
- // TODO: API documentation, if `@intlify/core` will be documented as a separate package
952
690
  /**
953
- * @version 12.0.0
954
- */
691
+ * @version 12.0.0
692
+ */
955
693
  function getLocaleMessage(ctx, locale) {
956
- const src = ctx.messages[locale];
957
- if (src == null) {
958
- return undefined;
959
- }
960
- const dest = create();
961
- deepCopy(src, dest);
962
- return dest;
963
- }
964
- // TODO: API documentation, if `@intlify/core` will be documented as a separate package
694
+ const src = ctx.messages[locale];
695
+ if (src == null) return;
696
+ const dest = create();
697
+ deepCopy(src, dest);
698
+ return dest;
699
+ }
965
700
  /**
966
- * @version 12.0.0
967
- */
701
+ * @version 12.0.0
702
+ */
968
703
  function setLocaleMessage(ctx, locale, messages) {
969
- ctx.messages[locale] = messages;
704
+ ctx.messages[locale] = messages;
970
705
  }
971
706
  /** @internal */
972
707
  function isTranslateFallbackWarn(fallback, key) {
973
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
708
+ return isRegExp(fallback) ? fallback.test(key) : fallback;
974
709
  }
975
710
  /** @internal */
976
711
  function isTranslateMissingWarn(missing, key) {
977
- return missing instanceof RegExp ? missing.test(key) : missing;
712
+ return isRegExp(missing) ? missing.test(key) : missing;
978
713
  }
979
714
  /** @internal */
980
715
  function handleMissing(context, key, locale, missingWarn, type) {
981
- const { missing, onWarn } = context;
982
- // for vue-devtools timeline event
983
- if ((process.env.NODE_ENV !== 'production')) {
984
- const emitter = context.__v_emitter;
985
- if (emitter) {
986
- emitter.emit('missing', {
987
- locale,
988
- key,
989
- type,
990
- groupId: `${type}:${key}`
991
- });
992
- }
993
- }
994
- if (missing !== null) {
995
- const ret = missing(context, locale, key, type);
996
- return isString(ret) ? ret : key;
997
- }
998
- else {
999
- if ((process.env.NODE_ENV !== 'production') && isTranslateMissingWarn(missingWarn, key)) {
1000
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
1001
- }
1002
- return key;
1003
- }
716
+ const { missing, onWarn } = context;
717
+ {
718
+ const emitter = context.__v_emitter;
719
+ if (emitter) emitter.emit("missing", {
720
+ locale,
721
+ key,
722
+ type,
723
+ groupId: `${type}:${key}`
724
+ });
725
+ }
726
+ if (missing !== null) {
727
+ const ret = missing(context, locale, key, type);
728
+ return isString(ret) ? ret : key;
729
+ } else {
730
+ if (isTranslateMissingWarn(missingWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, {
731
+ key,
732
+ locale
733
+ }));
734
+ return key;
735
+ }
1004
736
  }
1005
737
  /** @internal */
1006
738
  function updateFallbackLocale(ctx, locale, fallback) {
1007
- const context = ctx;
1008
- context.__localeChainCache = new Map();
1009
- ctx.localeFallbacker(ctx, fallback, locale);
739
+ const context = ctx;
740
+ context.__localeChainCache = /* @__PURE__ */ new Map();
741
+ ctx.localeFallbacker(ctx, fallback, locale);
1010
742
  }
1011
743
  /** @internal */
1012
744
  function isAlmostSameLocale(locale, compareLocale) {
1013
- if (locale === compareLocale)
1014
- return false;
1015
- return locale.split('-')[0] === compareLocale.split('-')[0];
745
+ if (locale === compareLocale) return false;
746
+ return locale.split("-")[0] === compareLocale.split("-")[0];
1016
747
  }
1017
748
  /** @internal */
1018
749
  function isImplicitFallback(targetLocale, locales) {
1019
- const index = locales.indexOf(targetLocale);
1020
- if (index === -1) {
1021
- return false;
1022
- }
1023
- for (let i = index + 1; i < locales.length; i++) {
1024
- if (isAlmostSameLocale(targetLocale, locales[i])) {
1025
- return true;
1026
- }
1027
- }
1028
- return false;
1029
- }
1030
- /* eslint-enable @typescript-eslint/no-explicit-any */
1031
-
1032
- const intlDefined = typeof Intl !== 'undefined';
750
+ const index = locales.indexOf(targetLocale);
751
+ if (index === -1) return false;
752
+ for (let i = index + 1; i < locales.length; i++) if (isAlmostSameLocale(targetLocale, locales[i])) return true;
753
+ return false;
754
+ }
755
+ //#endregion
756
+ //#region packages/core-base/src/intl.ts
757
+ const intlDefined = typeof Intl !== "undefined";
1033
758
  const Availabilities = {
1034
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1035
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
759
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== "undefined",
760
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== "undefined"
1036
761
  };
1037
-
1038
- // implementation of `datetime` function
762
+ //#endregion
763
+ //#region packages/core-base/src/datetime.ts
1039
764
  function datetime(context, ...args) {
1040
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1041
- const { __datetimeFormatters } = context;
1042
- if ((process.env.NODE_ENV !== 'production') && !Availabilities.dateTimeFormat) {
1043
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1044
- return MISSING_RESOLVE_VALUE;
1045
- }
1046
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1047
- const missingWarn = isBoolean(options.missingWarn)
1048
- ? options.missingWarn
1049
- : context.missingWarn;
1050
- const fallbackWarn = isBoolean(options.fallbackWarn)
1051
- ? options.fallbackWarn
1052
- : context.fallbackWarn;
1053
- const part = !!options.part;
1054
- const locale = getLocale(context, options);
1055
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1056
- fallbackLocale, locale);
1057
- if (!isString(key) || key === '') {
1058
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1059
- }
1060
- // resolve format
1061
- let datetimeFormat = {};
1062
- let targetLocale;
1063
- let format = null;
1064
- let from = locale;
1065
- let to = null;
1066
- const type = 'datetime format';
1067
- for (let i = 0; i < locales.length; i++) {
1068
- targetLocale = to = locales[i];
1069
- if ((process.env.NODE_ENV !== 'production') &&
1070
- locale !== targetLocale &&
1071
- isTranslateFallbackWarn(fallbackWarn, key)) {
1072
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1073
- key,
1074
- target: targetLocale
1075
- }));
1076
- }
1077
- // for vue-devtools timeline event
1078
- if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
1079
- const emitter = context.__v_emitter;
1080
- if (emitter) {
1081
- emitter.emit('fallback', {
1082
- type,
1083
- key,
1084
- from,
1085
- to,
1086
- groupId: `${type}:${key}`
1087
- });
1088
- }
1089
- }
1090
- datetimeFormat =
1091
- datetimeFormats[targetLocale] || {};
1092
- format = datetimeFormat[key];
1093
- if (isPlainObject(format))
1094
- break;
1095
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1096
- from = to;
1097
- }
1098
- // checking format and target locale
1099
- if (!isPlainObject(format) || !isString(targetLocale)) {
1100
- return unresolving ? NOT_RESOLVED : key;
1101
- }
1102
- let id = `${targetLocale}__${key}`;
1103
- if (!isEmptyObject(overrides)) {
1104
- id = `${id}__${JSON.stringify(overrides)}`;
1105
- }
1106
- let formatter = __datetimeFormatters.get(id);
1107
- if (!formatter) {
1108
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1109
- __datetimeFormatters.set(id, formatter);
1110
- }
1111
- return !part ? formatter.format(value) : formatter.formatToParts(value);
765
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
766
+ const { __datetimeFormatters } = context;
767
+ if (!Availabilities.dateTimeFormat) {
768
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
769
+ return "";
770
+ }
771
+ if (!isString(args[0]) && !isDate(args[0]) && !isNumber(args[0])) {
772
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_DATE_ARGUMENT, { value: String(args[0]) }));
773
+ return "";
774
+ }
775
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
776
+ const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn;
777
+ const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
778
+ const part = !!options.part;
779
+ const locale = getLocale(context, options);
780
+ const locales = localeFallbacker(context, fallbackLocale, locale);
781
+ if (!isString(key) || key === "") return new Intl.DateTimeFormat(locale.replace(/!/g, ""), overrides).format(value);
782
+ let datetimeFormat = {};
783
+ let targetLocale;
784
+ let format = null;
785
+ let from = locale;
786
+ let to = null;
787
+ const type = "datetime format";
788
+ for (let i = 0; i < locales.length; i++) {
789
+ targetLocale = to = locales[i];
790
+ if (locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
791
+ key,
792
+ target: targetLocale
793
+ }));
794
+ if (locale !== targetLocale) {
795
+ const emitter = context.__v_emitter;
796
+ if (emitter) emitter.emit("fallback", {
797
+ type,
798
+ key,
799
+ from,
800
+ to,
801
+ groupId: `${type}:${key}`
802
+ });
803
+ }
804
+ datetimeFormat = datetimeFormats[targetLocale] || {};
805
+ format = datetimeFormat[key];
806
+ if (isPlainObject(format)) break;
807
+ handleMissing(context, key, targetLocale, missingWarn, type);
808
+ from = to;
809
+ }
810
+ if (!isPlainObject(format) || !isString(targetLocale)) return unresolving ? -1 : key;
811
+ let id = `${targetLocale}__${key}`;
812
+ if (isPlainObject(overrides) && !isKeylessObject(overrides)) id = `${id}__${JSON.stringify(overrides)}`;
813
+ let formatter = __datetimeFormatters.get(id);
814
+ if (!formatter) {
815
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
816
+ __datetimeFormatters.set(id, formatter);
817
+ }
818
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1112
819
  }
1113
820
  /** @internal */
1114
821
  const DATETIME_FORMAT_OPTIONS_KEYS = [
1115
- 'localeMatcher',
1116
- 'weekday',
1117
- 'era',
1118
- 'year',
1119
- 'month',
1120
- 'day',
1121
- 'hour',
1122
- 'minute',
1123
- 'second',
1124
- 'timeZoneName',
1125
- 'formatMatcher',
1126
- 'hour12',
1127
- 'timeZone',
1128
- 'dateStyle',
1129
- 'timeStyle',
1130
- 'calendar',
1131
- 'dayPeriod',
1132
- 'numberingSystem',
1133
- 'hourCycle',
1134
- 'fractionalSecondDigits'
822
+ "localeMatcher",
823
+ "weekday",
824
+ "era",
825
+ "year",
826
+ "month",
827
+ "day",
828
+ "hour",
829
+ "minute",
830
+ "second",
831
+ "timeZoneName",
832
+ "formatMatcher",
833
+ "hour12",
834
+ "timeZone",
835
+ "dateStyle",
836
+ "timeStyle",
837
+ "calendar",
838
+ "dayPeriod",
839
+ "numberingSystem",
840
+ "hourCycle",
841
+ "fractionalSecondDigits"
1135
842
  ];
1136
843
  /** @internal */
1137
844
  function parseDateTimeArgs(...args) {
1138
- const [arg1, arg2, arg3, arg4] = args;
1139
- const options = create();
1140
- let overrides = create();
1141
- let value;
1142
- if (isString(arg1)) {
1143
- // Only allow ISO strings - other date formats are often supported,
1144
- // but may cause different results in different browsers.
1145
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1146
- if (!matches) {
1147
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1148
- }
1149
- // Some browsers can not parse the iso datetime separated by space,
1150
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1151
- const dateTime = matches[3]
1152
- ? matches[3].trim().startsWith('T')
1153
- ? `${matches[1].trim()}${matches[3].trim()}`
1154
- : `${matches[1].trim()}T${matches[3].trim()}`
1155
- : matches[1].trim();
1156
- value = new Date(dateTime);
1157
- try {
1158
- // This will fail if the date is not valid
1159
- value.toISOString();
1160
- }
1161
- catch {
1162
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1163
- }
1164
- }
1165
- else if (isDate(arg1)) {
1166
- if (isNaN(arg1.getTime())) {
1167
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1168
- }
1169
- value = arg1;
1170
- }
1171
- else if (isNumber(arg1)) {
1172
- value = arg1;
1173
- }
1174
- else {
1175
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1176
- }
1177
- if (isString(arg2)) {
1178
- options.key = arg2;
1179
- }
1180
- else if (isPlainObject(arg2)) {
1181
- Object.keys(arg2).forEach(key => {
1182
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1183
- overrides[key] = arg2[key];
1184
- }
1185
- else {
1186
- options[key] = arg2[key];
1187
- }
1188
- });
1189
- }
1190
- if (isString(arg3)) {
1191
- options.locale = arg3;
1192
- }
1193
- else if (isPlainObject(arg3)) {
1194
- overrides = arg3;
1195
- }
1196
- if (isPlainObject(arg4)) {
1197
- overrides = arg4;
1198
- }
1199
- return [options.key || '', value, options, overrides];
845
+ const [arg1, arg2, arg3, arg4] = args;
846
+ const options = create();
847
+ let overrides = create();
848
+ let value;
849
+ if (isString(arg1)) {
850
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
851
+ if (!matches) throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
852
+ const dateTime = matches[3] ? matches[3].trim().startsWith("T") ? `${matches[1].trim()}${matches[3].trim()}` : `${matches[1].trim()}T${matches[3].trim()}` : matches[1].trim();
853
+ value = new Date(dateTime);
854
+ try {
855
+ value.toISOString();
856
+ } catch {
857
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
858
+ }
859
+ } else if (isDate(arg1)) {
860
+ if (isNaN(arg1.getTime())) throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
861
+ value = arg1;
862
+ } else if (isNumber(arg1)) value = arg1;
863
+ else throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
864
+ if (isString(arg2)) options.key = arg2;
865
+ else if (isPlainObject(arg2)) Object.keys(arg2).forEach((key) => {
866
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) overrides[key] = arg2[key];
867
+ else options[key] = arg2[key];
868
+ });
869
+ if (isString(arg3)) options.locale = arg3;
870
+ else if (isPlainObject(arg3)) overrides = arg3;
871
+ if (isPlainObject(arg4)) overrides = arg4;
872
+ return [
873
+ options.key || "",
874
+ value,
875
+ options,
876
+ overrides
877
+ ];
1200
878
  }
1201
879
  /** @internal */
1202
880
  function clearDateTimeFormat(ctx, locale, format) {
1203
- const context = ctx;
1204
- for (const key in format) {
1205
- const id = `${locale}__${key}`;
1206
- if (!context.__datetimeFormatters.has(id)) {
1207
- continue;
1208
- }
1209
- context.__datetimeFormatters.delete(id);
1210
- }
1211
- }
1212
-
1213
- // implementation of `number` function
881
+ const context = ctx;
882
+ for (const key in format) {
883
+ const id = `${locale}__${key}`;
884
+ if (!context.__datetimeFormatters.has(id)) continue;
885
+ context.__datetimeFormatters.delete(id);
886
+ }
887
+ }
888
+ //#endregion
889
+ //#region packages/core-base/src/number.ts
1214
890
  function number(context, ...args) {
1215
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1216
- const { __numberFormatters } = context;
1217
- if ((process.env.NODE_ENV !== 'production') && !Availabilities.numberFormat) {
1218
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1219
- return MISSING_RESOLVE_VALUE;
1220
- }
1221
- const [key, value, options, overrides] = parseNumberArgs(...args);
1222
- const missingWarn = isBoolean(options.missingWarn)
1223
- ? options.missingWarn
1224
- : context.missingWarn;
1225
- const fallbackWarn = isBoolean(options.fallbackWarn)
1226
- ? options.fallbackWarn
1227
- : context.fallbackWarn;
1228
- const part = !!options.part;
1229
- const locale = getLocale(context, options);
1230
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1231
- fallbackLocale, locale);
1232
- if (!isString(key) || key === '') {
1233
- return new Intl.NumberFormat(locale, overrides).format(value);
1234
- }
1235
- // resolve format
1236
- let numberFormat = {};
1237
- let targetLocale;
1238
- let format = null;
1239
- let from = locale;
1240
- let to = null;
1241
- const type = 'number format';
1242
- for (let i = 0; i < locales.length; i++) {
1243
- targetLocale = to = locales[i];
1244
- if ((process.env.NODE_ENV !== 'production') &&
1245
- locale !== targetLocale &&
1246
- isTranslateFallbackWarn(fallbackWarn, key)) {
1247
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1248
- key,
1249
- target: targetLocale
1250
- }));
1251
- }
1252
- // for vue-devtools timeline event
1253
- if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
1254
- const emitter = context.__v_emitter;
1255
- if (emitter) {
1256
- emitter.emit('fallback', {
1257
- type,
1258
- key,
1259
- from,
1260
- to,
1261
- groupId: `${type}:${key}`
1262
- });
1263
- }
1264
- }
1265
- numberFormat =
1266
- numberFormats[targetLocale] || {};
1267
- format = numberFormat[key];
1268
- if (isPlainObject(format))
1269
- break;
1270
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1271
- from = to;
1272
- }
1273
- // checking format and target locale
1274
- if (!isPlainObject(format) || !isString(targetLocale)) {
1275
- return unresolving ? NOT_RESOLVED : key;
1276
- }
1277
- let id = `${targetLocale}__${key}`;
1278
- if (!isEmptyObject(overrides)) {
1279
- id = `${id}__${JSON.stringify(overrides)}`;
1280
- }
1281
- let formatter = __numberFormatters.get(id);
1282
- if (!formatter) {
1283
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1284
- __numberFormatters.set(id, formatter);
1285
- }
1286
- return !part ? formatter.format(value) : formatter.formatToParts(value);
891
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
892
+ const { __numberFormatters } = context;
893
+ if (!Availabilities.numberFormat) {
894
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
895
+ return "";
896
+ }
897
+ if (!isNumber(args[0])) {
898
+ onWarn(getWarnMessage(CoreWarnCodes.INVALID_NUMBER_ARGUMENT, { value: String(args[0]) }));
899
+ return "";
900
+ }
901
+ const [key, value, options, overrides] = parseNumberArgs(...args);
902
+ const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn;
903
+ const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn;
904
+ const part = !!options.part;
905
+ const locale = getLocale(context, options);
906
+ const locales = localeFallbacker(context, fallbackLocale, locale);
907
+ if (!isString(key) || key === "") return new Intl.NumberFormat(locale.replace(/!/g, ""), overrides).format(value);
908
+ let numberFormat = {};
909
+ let targetLocale;
910
+ let format = null;
911
+ let from = locale;
912
+ let to = null;
913
+ const type = "number format";
914
+ for (let i = 0; i < locales.length; i++) {
915
+ targetLocale = to = locales[i];
916
+ if (locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
917
+ key,
918
+ target: targetLocale
919
+ }));
920
+ if (locale !== targetLocale) {
921
+ const emitter = context.__v_emitter;
922
+ if (emitter) emitter.emit("fallback", {
923
+ type,
924
+ key,
925
+ from,
926
+ to,
927
+ groupId: `${type}:${key}`
928
+ });
929
+ }
930
+ numberFormat = numberFormats[targetLocale] || {};
931
+ format = numberFormat[key];
932
+ if (isPlainObject(format)) break;
933
+ handleMissing(context, key, targetLocale, missingWarn, type);
934
+ from = to;
935
+ }
936
+ if (!isPlainObject(format) || !isString(targetLocale)) return unresolving ? -1 : key;
937
+ let id = `${targetLocale}__${key}`;
938
+ if (isPlainObject(overrides) && !isKeylessObject(overrides)) id = `${id}__${JSON.stringify(overrides)}`;
939
+ let formatter = __numberFormatters.get(id);
940
+ if (!formatter) {
941
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
942
+ __numberFormatters.set(id, formatter);
943
+ }
944
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
1287
945
  }
1288
946
  /** @internal */
1289
947
  const NUMBER_FORMAT_OPTIONS_KEYS = [
1290
- 'localeMatcher',
1291
- 'style',
1292
- 'currency',
1293
- 'currencyDisplay',
1294
- 'currencySign',
1295
- 'useGrouping',
1296
- 'minimumIntegerDigits',
1297
- 'minimumFractionDigits',
1298
- 'maximumFractionDigits',
1299
- 'minimumSignificantDigits',
1300
- 'maximumSignificantDigits',
1301
- 'compactDisplay',
1302
- 'notation',
1303
- 'signDisplay',
1304
- 'unit',
1305
- 'unitDisplay',
1306
- 'roundingMode',
1307
- 'roundingPriority',
1308
- 'roundingIncrement',
1309
- 'trailingZeroDisplay'
948
+ "localeMatcher",
949
+ "style",
950
+ "currency",
951
+ "currencyDisplay",
952
+ "currencySign",
953
+ "useGrouping",
954
+ "minimumIntegerDigits",
955
+ "minimumFractionDigits",
956
+ "maximumFractionDigits",
957
+ "minimumSignificantDigits",
958
+ "maximumSignificantDigits",
959
+ "compactDisplay",
960
+ "notation",
961
+ "signDisplay",
962
+ "unit",
963
+ "unitDisplay",
964
+ "roundingMode",
965
+ "roundingPriority",
966
+ "roundingIncrement",
967
+ "trailingZeroDisplay"
1310
968
  ];
1311
969
  /** @internal */
1312
970
  function parseNumberArgs(...args) {
1313
- const [arg1, arg2, arg3, arg4] = args;
1314
- const options = create();
1315
- let overrides = create();
1316
- if (!isNumber(arg1)) {
1317
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1318
- }
1319
- const value = arg1;
1320
- if (isString(arg2)) {
1321
- options.key = arg2;
1322
- }
1323
- else if (isPlainObject(arg2)) {
1324
- Object.keys(arg2).forEach(key => {
1325
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1326
- overrides[key] = arg2[key];
1327
- }
1328
- else {
1329
- options[key] = arg2[key];
1330
- }
1331
- });
1332
- }
1333
- if (isString(arg3)) {
1334
- options.locale = arg3;
1335
- }
1336
- else if (isPlainObject(arg3)) {
1337
- overrides = arg3;
1338
- }
1339
- if (isPlainObject(arg4)) {
1340
- overrides = arg4;
1341
- }
1342
- return [options.key || '', value, options, overrides];
971
+ const [arg1, arg2, arg3, arg4] = args;
972
+ const options = create();
973
+ let overrides = create();
974
+ if (!isNumber(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
975
+ const value = arg1;
976
+ if (isString(arg2)) options.key = arg2;
977
+ else if (isPlainObject(arg2)) Object.keys(arg2).forEach((key) => {
978
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) overrides[key] = arg2[key];
979
+ else options[key] = arg2[key];
980
+ });
981
+ if (isString(arg3)) options.locale = arg3;
982
+ else if (isPlainObject(arg3)) overrides = arg3;
983
+ if (isPlainObject(arg4)) overrides = arg4;
984
+ return [
985
+ options.key || "",
986
+ value,
987
+ options,
988
+ overrides
989
+ ];
1343
990
  }
1344
991
  /** @internal */
1345
992
  function clearNumberFormat(ctx, locale, format) {
1346
- const context = ctx;
1347
- for (const key in format) {
1348
- const id = `${locale}__${key}`;
1349
- if (!context.__numberFormatters.has(id)) {
1350
- continue;
1351
- }
1352
- context.__numberFormatters.delete(id);
1353
- }
1354
- }
1355
-
993
+ const context = ctx;
994
+ for (const key in format) {
995
+ const id = `${locale}__${key}`;
996
+ if (!context.__numberFormatters.has(id)) continue;
997
+ context.__numberFormatters.delete(id);
998
+ }
999
+ }
1000
+ //#endregion
1001
+ //#region packages/core-base/src/runtime.ts
1356
1002
  const DEFAULT_MODIFIER = (str) => str;
1357
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1358
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1359
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1003
+ const DEFAULT_MESSAGE = (_ctx) => "";
1004
+ const DEFAULT_MESSAGE_DATA_TYPE = "text";
1005
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? "" : join(values);
1360
1006
  const DEFAULT_INTERPOLATE = toDisplayString;
1361
1007
  function pluralDefault(choice, choicesLength) {
1362
- choice = Math.abs(choice);
1363
- if (choicesLength === 2) {
1364
- // prettier-ignore
1365
- return choice
1366
- ? choice > 1
1367
- ? 1
1368
- : 0
1369
- : 1;
1370
- }
1371
- return choice ? Math.min(choice, 2) : 0;
1008
+ choice = Math.abs(choice);
1009
+ if (choicesLength === 2) return choice === 1 ? 0 : 1;
1010
+ return Math.min(choice, 2);
1011
+ }
1012
+ const PLURAL_CATEGORY_ORDER = [
1013
+ "zero",
1014
+ "one",
1015
+ "two",
1016
+ "few",
1017
+ "many",
1018
+ "other"
1019
+ ];
1020
+ const intlPluralRulesCache = /* @__PURE__ */ new Map();
1021
+ function getIntlPluralRules(locale) {
1022
+ let cached = intlPluralRulesCache.get(locale);
1023
+ if (!cached) {
1024
+ const rules = new Intl.PluralRules(locale);
1025
+ cached = {
1026
+ rules,
1027
+ categories: rules.resolvedOptions().pluralCategories.slice().sort((a, b) => PLURAL_CATEGORY_ORDER.indexOf(a) - PLURAL_CATEGORY_ORDER.indexOf(b))
1028
+ };
1029
+ intlPluralRulesCache.set(locale, cached);
1030
+ }
1031
+ return cached;
1372
1032
  }
1373
1033
  function getPluralIndex(options) {
1374
- // prettier-ignore
1375
- const index = isNumber(options.pluralIndex)
1376
- ? options.pluralIndex
1377
- : -1;
1378
- // prettier-ignore
1379
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1380
- ? isNumber(options.named.count)
1381
- ? options.named.count
1382
- : isNumber(options.named.n)
1383
- ? options.named.n
1384
- : index
1385
- : index;
1386
- }
1387
- function normalizeNamed(pluralIndex, props) {
1388
- if (!props.count) {
1389
- props.count = pluralIndex;
1390
- }
1391
- if (!props.n) {
1392
- props.n = pluralIndex;
1393
- }
1034
+ if (isNumber(options.pluralIndex)) return options.pluralIndex;
1035
+ return isNumber(options.named?.count) ? options.named.count : isNumber(options.named?.n) ? options.named.n : -1;
1394
1036
  }
1395
1037
  function createMessageContext(options = {}) {
1396
- const locale = options.locale;
1397
- const pluralIndex = getPluralIndex(options);
1398
- const pluralRule = isObject(options.pluralRules) &&
1399
- isString(locale) &&
1400
- isFunction(options.pluralRules[locale])
1401
- ? options.pluralRules[locale]
1402
- : pluralDefault;
1403
- const orgPluralRule = isObject(options.pluralRules) &&
1404
- isString(locale) &&
1405
- isFunction(options.pluralRules[locale])
1406
- ? pluralDefault
1407
- : undefined;
1408
- const plural = (messages) => {
1409
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1410
- };
1411
- const _list = options.list || [];
1412
- const list = (index) => _list[index];
1413
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1414
- const _named = options.named || create();
1415
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1416
- const named = (key) => _named[key];
1417
- function message(key, useLinked) {
1418
- // prettier-ignore
1419
- const msg = isFunction(options.messages)
1420
- ? options.messages(key, !!useLinked)
1421
- : isObject(options.messages)
1422
- ? options.messages[key]
1423
- : false;
1424
- return !msg
1425
- ? options.parent
1426
- ? options.parent.message(key) // resolve from parent messages
1427
- : DEFAULT_MESSAGE
1428
- : msg;
1429
- }
1430
- const _modifier = (name) => options.modifiers
1431
- ? options.modifiers[name]
1432
- : DEFAULT_MODIFIER;
1433
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1434
- ? options.processor.normalize
1435
- : DEFAULT_NORMALIZE;
1436
- const interpolate = isPlainObject(options.processor) &&
1437
- isFunction(options.processor.interpolate)
1438
- ? options.processor.interpolate
1439
- : DEFAULT_INTERPOLATE;
1440
- const type = isPlainObject(options.processor) && isString(options.processor.type)
1441
- ? options.processor.type
1442
- : DEFAULT_MESSAGE_DATA_TYPE;
1443
- const linked = (key, ...args) => {
1444
- const [arg1, arg2] = args;
1445
- let type = 'text';
1446
- let modifier = '';
1447
- if (args.length === 1) {
1448
- if (isObject(arg1)) {
1449
- modifier = arg1.modifier || modifier;
1450
- type = arg1.type || type;
1451
- }
1452
- else if (isString(arg1)) {
1453
- modifier = arg1 || modifier;
1454
- }
1455
- }
1456
- else if (args.length === 2) {
1457
- if (isString(arg1)) {
1458
- modifier = arg1 || modifier;
1459
- }
1460
- if (isString(arg2)) {
1461
- type = arg2 || type;
1462
- }
1463
- }
1464
- const ret = message(key, true)(ctx);
1465
- const msg =
1466
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
1467
- type === 'vnode' && isArray(ret) && modifier
1468
- ? ret[0]
1469
- : ret;
1470
- return modifier ? _modifier(modifier)(msg, type) : msg;
1471
- };
1472
- const ctx = {
1473
- ["list" /* HelperNameMap.LIST */]: list,
1474
- ["named" /* HelperNameMap.NAMED */]: named,
1475
- ["plural" /* HelperNameMap.PLURAL */]: plural,
1476
- ["linked" /* HelperNameMap.LINKED */]: linked,
1477
- ["message" /* HelperNameMap.MESSAGE */]: message,
1478
- ["type" /* HelperNameMap.TYPE */]: type,
1479
- ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1480
- ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
1481
- ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named)
1482
- };
1483
- return ctx;
1484
- }
1485
-
1486
- const NOOP_MESSAGE_FUNCTION = () => '';
1038
+ const locale = options.locale;
1039
+ const pluralIndex = getPluralIndex(options);
1040
+ let resolvedPluralRule;
1041
+ if (isString(locale) && isFunction(options.pluralRules?.[locale])) resolvedPluralRule = options.pluralRules[locale];
1042
+ else if (isString(locale) && typeof Intl !== "undefined" && typeof Intl.PluralRules !== "undefined") resolvedPluralRule = (choice, choicesLength) => {
1043
+ const { rules, categories } = getIntlPluralRules(locale);
1044
+ if (choicesLength > categories.length) return pluralDefault(choice, choicesLength);
1045
+ const category = rules.select(Math.abs(choice));
1046
+ const index = categories.indexOf(category);
1047
+ return Math.min(index === -1 ? choicesLength - 1 : index, choicesLength - 1);
1048
+ };
1049
+ else resolvedPluralRule = pluralDefault;
1050
+ const orgPluralRule = resolvedPluralRule === pluralDefault ? void 0 : pluralDefault;
1051
+ const plural = (messages) => messages[resolvedPluralRule(pluralIndex, messages.length, orgPluralRule)];
1052
+ const _list = options.list || [];
1053
+ const list = (index) => _list[index];
1054
+ const _named = options.named || create();
1055
+ if (isNumber(options.pluralIndex)) {
1056
+ _named.count ??= options.pluralIndex;
1057
+ _named.n ??= options.pluralIndex;
1058
+ }
1059
+ const named = (key) => _named[key];
1060
+ function message(key, useLinked) {
1061
+ const msg = isFunction(options.messages) ? options.messages(key, !!useLinked) : isObject(options.messages) ? options.messages[key] : false;
1062
+ return !msg ? options.parent ? options.parent.message(key) : DEFAULT_MESSAGE : msg;
1063
+ }
1064
+ const _modifier = (name) => options.modifiers ? options.modifiers[name] : DEFAULT_MODIFIER;
1065
+ const normalize = isFunction(options.processor?.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE;
1066
+ const interpolate = isFunction(options.processor?.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE;
1067
+ const type = isString(options.processor?.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE;
1068
+ const linked = (key, ...args) => {
1069
+ const [arg1, arg2] = args;
1070
+ let type = "text";
1071
+ let modifier = "";
1072
+ if (args.length === 1) {
1073
+ if (isObject(arg1)) {
1074
+ modifier = arg1.modifier || modifier;
1075
+ type = arg1.type || type;
1076
+ } else if (isString(arg1)) modifier = arg1 || modifier;
1077
+ } else if (args.length === 2) {
1078
+ if (isString(arg1)) modifier = arg1 || modifier;
1079
+ if (isString(arg2)) type = arg2 || type;
1080
+ }
1081
+ const ret = message(key, true)(ctx);
1082
+ const resolved = ret === "" || ret === void 0 ? key : ret;
1083
+ const msg = type === "vnode" && isArray(resolved) && modifier ? resolved[0] : resolved;
1084
+ return modifier ? _modifier(modifier)(msg, type) : msg;
1085
+ };
1086
+ const ctx = {
1087
+ [HelperNameMap.LIST]: list,
1088
+ [HelperNameMap.NAMED]: named,
1089
+ [HelperNameMap.PLURAL]: plural,
1090
+ [HelperNameMap.LINKED]: linked,
1091
+ [HelperNameMap.MESSAGE]: message,
1092
+ [HelperNameMap.TYPE]: type,
1093
+ [HelperNameMap.INTERPOLATE]: interpolate,
1094
+ [HelperNameMap.NORMALIZE]: normalize,
1095
+ [HelperNameMap.VALUES]: assign(create(), _list, _named)
1096
+ };
1097
+ return ctx;
1098
+ }
1099
+ //#endregion
1100
+ //#region packages/core-base/src/translate.ts
1101
+ const NOOP_MESSAGE_FUNCTION = () => "";
1487
1102
  const isMessageFunction = (val) => isFunction(val);
1488
- // implementation of `translate` function
1489
1103
  function translate(context, ...args) {
1490
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
1491
- const [key, options] = parseTranslateArgs(...args);
1492
- const missingWarn = isBoolean(options.missingWarn)
1493
- ? options.missingWarn
1494
- : context.missingWarn;
1495
- const fallbackWarn = isBoolean(options.fallbackWarn)
1496
- ? options.fallbackWarn
1497
- : context.fallbackWarn;
1498
- const escapeParameter = isBoolean(options.escapeParameter)
1499
- ? options.escapeParameter
1500
- : context.escapeParameter;
1501
- const resolvedMessage = !!options.resolvedMessage;
1502
- // prettier-ignore
1503
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1504
- ? !isBoolean(options.default)
1505
- ? options.default
1506
- : (!messageCompiler ? () => key : key)
1507
- : fallbackFormat // default by `fallbackFormat` option
1508
- ? (!messageCompiler ? () => key : key)
1509
- : null;
1510
- const enableDefaultMsg = fallbackFormat ||
1511
- (defaultMsgOrKey != null &&
1512
- (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey)));
1513
- const locale = getLocale(context, options);
1514
- // escape params
1515
- escapeParameter && escapeParams(options);
1516
- // resolve message format
1517
- // eslint-disable-next-line prefer-const
1518
- let [formatScope, targetLocale, message] = !resolvedMessage
1519
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1520
- : [
1521
- key,
1522
- locale,
1523
- messages[locale] || create()
1524
- ];
1525
- // NOTE:
1526
- // Fix to work around `ssrTransfrom` bug in Vite.
1527
- // https://github.com/vitejs/vite/issues/4306
1528
- // To get around this, use temporary variables.
1529
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1530
- let format = formatScope;
1531
- // if you use default message, set it as message format!
1532
- let cacheBaseKey = key;
1533
- if (!resolvedMessage &&
1534
- !(isString(format) ||
1535
- isMessageAST(format) ||
1536
- isMessageFunction(format))) {
1537
- if (enableDefaultMsg) {
1538
- format = defaultMsgOrKey;
1539
- cacheBaseKey = format;
1540
- }
1541
- }
1542
- // checking message format and target locale
1543
- if (!resolvedMessage &&
1544
- (!(isString(format) ||
1545
- isMessageAST(format) ||
1546
- isMessageFunction(format)) ||
1547
- !isString(targetLocale))) {
1548
- return unresolving ? NOT_RESOLVED : key;
1549
- }
1550
- // TODO: refactor
1551
- if ((process.env.NODE_ENV !== 'production') && isString(format) && context.messageCompiler == null) {
1552
- warn(`The message format compilation is not supported in this build. ` +
1553
- `Because message compiler isn't included. ` +
1554
- `You need to pre-compilation all message format. ` +
1555
- `So translate function return '${key}'.`);
1556
- return key;
1557
- }
1558
- // setup compile error detecting
1559
- let occurred = false;
1560
- const onError = () => {
1561
- occurred = true;
1562
- };
1563
- // compile message format
1564
- const msg = !isMessageFunction(format)
1565
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
1566
- : format;
1567
- // if occurred compile error, return the message format
1568
- if (occurred) {
1569
- return format;
1570
- }
1571
- // evaluate message with context
1572
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1573
- const msgContext = createMessageContext(ctxOptions);
1574
- const messaged = evaluateMessage(context, msg, msgContext);
1575
- // if use post translation option, proceed it with handler
1576
- const ret = postTranslation
1577
- ? postTranslation(messaged, key)
1578
- : messaged;
1579
- // NOTE: experimental !!
1580
- if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
1581
- // prettier-ignore
1582
- const payloads = {
1583
- timestamp: Date.now(),
1584
- key: isString(key)
1585
- ? key
1586
- : isMessageFunction(format)
1587
- ? format.key
1588
- : '',
1589
- locale: targetLocale || (isMessageFunction(format)
1590
- ? format.locale
1591
- : ''),
1592
- format: isString(format)
1593
- ? format
1594
- : isMessageFunction(format)
1595
- ? format.source
1596
- : '',
1597
- message: ret
1598
- };
1599
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1600
- translateDevTools(payloads);
1601
- }
1602
- return ret;
1104
+ const [key, options] = parseTranslateArgs(...args);
1105
+ const locale = getLocale(context, options);
1106
+ const escapeParameter = isBoolean(options.escapeParameter) ? options.escapeParameter : context.escapeParameter;
1107
+ escapeParameter && escapeParams(options);
1108
+ const resolvedMessage = !!options.resolvedMessage;
1109
+ let [format, targetLocale, message] = !resolvedMessage ? resolveMessageFormat(context, key, locale, context.fallbackLocale, isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn, isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn) : [
1110
+ key,
1111
+ locale,
1112
+ context.messages[locale] || create()
1113
+ ];
1114
+ let cacheBaseKey = key;
1115
+ if (!resolvedMessage && !(isString(format) || isMessageAST(format) || isMessageFunction(format))) {
1116
+ const defaultMsgOrKey = isString(options.default) ? options.default : isBoolean(options.default) || context.fallbackFormat ? !context.messageCompiler ? () => key : key : null;
1117
+ if (context.fallbackFormat || defaultMsgOrKey != null && (isString(defaultMsgOrKey) || isFunction(defaultMsgOrKey))) {
1118
+ format = defaultMsgOrKey;
1119
+ cacheBaseKey = format;
1120
+ }
1121
+ }
1122
+ if (!resolvedMessage && (!(isString(format) || isMessageAST(format) || isMessageFunction(format)) || !isString(targetLocale))) return context.unresolving ? -1 : key;
1123
+ if (isString(format) && context.messageCompiler == null) {
1124
+ warn(`The message format compilation is not supported in this build. Because message compiler isn't included. You need to pre-compilation all message format. So translate function return '${isString(key) ? key : isObject(key) ? JSON.stringify(key) : isFunction(key) ? key.name || "function" : ""}'.`);
1125
+ return key;
1126
+ }
1127
+ let occurred = false;
1128
+ const onError = () => {
1129
+ occurred = true;
1130
+ };
1131
+ const msg = !isMessageFunction(format) ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) : format;
1132
+ if (occurred) return format;
1133
+ const msgContext = createMessageContext(getMessageContextOptions(context, targetLocale, message, options));
1134
+ const messaged = inBrowser ? measureEvaluateMessage(context, msg, msgContext) : msg(msgContext);
1135
+ let ret = context.postTranslation ? context.postTranslation(messaged, key) : messaged;
1136
+ if (escapeParameter && isString(ret)) ret = sanitizeTranslatedHtml(ret);
1137
+ return ret;
1603
1138
  }
1604
1139
  function escapeParams(options) {
1605
- if (isArray(options.list)) {
1606
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1607
- }
1608
- else if (isObject(options.named)) {
1609
- Object.keys(options.named).forEach(key => {
1610
- if (isString(options.named[key])) {
1611
- options.named[key] = escapeHtml(options.named[key]);
1612
- }
1613
- });
1614
- }
1140
+ if (isArray(options.list)) options.list = options.list.map((item) => isString(item) ? escapeHtml(item) : item);
1141
+ else if (isObject(options.named)) Object.keys(options.named).forEach((key) => {
1142
+ if (isString(options.named[key])) options.named[key] = escapeHtml(options.named[key]);
1143
+ });
1615
1144
  }
1616
1145
  function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1617
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1618
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1619
- let message = create();
1620
- let targetLocale;
1621
- let format = null;
1622
- let from = locale;
1623
- let to = null;
1624
- const type = 'translate';
1625
- for (let i = 0; i < locales.length; i++) {
1626
- targetLocale = to = locales[i];
1627
- if ((process.env.NODE_ENV !== 'production') &&
1628
- locale !== targetLocale &&
1629
- !isAlmostSameLocale(locale, targetLocale) &&
1630
- isTranslateFallbackWarn(fallbackWarn, key)) {
1631
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1632
- key,
1633
- target: targetLocale
1634
- }));
1635
- }
1636
- // for vue-devtools timeline event
1637
- if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
1638
- const emitter = context.__v_emitter;
1639
- if (emitter) {
1640
- emitter.emit('fallback', {
1641
- type,
1642
- key,
1643
- from,
1644
- to,
1645
- groupId: `${type}:${key}`
1646
- });
1647
- }
1648
- }
1649
- message =
1650
- messages[targetLocale] || create();
1651
- // for vue-devtools timeline event
1652
- let start = null;
1653
- let startTag;
1654
- let endTag;
1655
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1656
- start = window.performance.now();
1657
- startTag = 'intlify-message-resolve-start';
1658
- endTag = 'intlify-message-resolve-end';
1659
- mark && mark(startTag);
1660
- }
1661
- if ((format = resolveValue(message, key)) === null) {
1662
- // if null, resolve with object key path
1663
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1664
- }
1665
- // for vue-devtools timeline event
1666
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1667
- const end = window.performance.now();
1668
- const emitter = context.__v_emitter;
1669
- if (emitter && start && format) {
1670
- emitter.emit('message-resolve', {
1671
- type: 'message-resolve',
1672
- key,
1673
- message: format,
1674
- time: end - start,
1675
- groupId: `${type}:${key}`
1676
- });
1677
- }
1678
- if (startTag && endTag && mark && measure) {
1679
- mark(endTag);
1680
- measure('intlify message resolve', startTag, endTag);
1681
- }
1682
- }
1683
- if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
1684
- break;
1685
- }
1686
- if (!isImplicitFallback(targetLocale, locales)) {
1687
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1688
- key, targetLocale, missingWarn, type);
1689
- if (missingRet !== key) {
1690
- format = missingRet;
1691
- }
1692
- }
1693
- from = to;
1694
- }
1695
- return [format, targetLocale, message];
1146
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1147
+ const locales = localeFallbacker(context, fallbackLocale, locale);
1148
+ let message = create();
1149
+ let targetLocale;
1150
+ let format = null;
1151
+ let from = locale;
1152
+ const type = "translate";
1153
+ for (let i = 0; i < locales.length; i++) {
1154
+ targetLocale = locales[i];
1155
+ if (locale !== targetLocale && !isAlmostSameLocale(locale, targetLocale) && isTranslateFallbackWarn(fallbackWarn, key)) onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1156
+ key,
1157
+ target: targetLocale
1158
+ }));
1159
+ if (locale !== targetLocale) {
1160
+ const emitter = context.__v_emitter;
1161
+ if (emitter) emitter.emit("fallback", {
1162
+ type,
1163
+ key,
1164
+ from,
1165
+ to: targetLocale,
1166
+ groupId: `${type}:${key}`
1167
+ });
1168
+ }
1169
+ message = messages[targetLocale] || create();
1170
+ let start = null;
1171
+ let startTag;
1172
+ let endTag;
1173
+ if (inBrowser) {
1174
+ start = window.performance.now();
1175
+ startTag = "intlify-message-resolve-start";
1176
+ endTag = "intlify-message-resolve-end";
1177
+ mark?.(startTag);
1178
+ }
1179
+ if ((format = resolveValue(message, key)) === null) format = message[key];
1180
+ if (inBrowser) {
1181
+ const end = window.performance.now();
1182
+ const emitter = context.__v_emitter;
1183
+ if (emitter && start && format) emitter.emit("message-resolve", {
1184
+ type: "message-resolve",
1185
+ key,
1186
+ message: format,
1187
+ time: end - start,
1188
+ groupId: `${type}:${key}`
1189
+ });
1190
+ if (startTag && endTag && mark && measure) {
1191
+ mark(endTag);
1192
+ measure("intlify message resolve", startTag, endTag);
1193
+ }
1194
+ }
1195
+ if (isString(format) || isMessageAST(format) || isMessageFunction(format)) break;
1196
+ if (!isImplicitFallback(targetLocale, locales)) {
1197
+ const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
1198
+ if (missingRet !== key) format = missingRet;
1199
+ }
1200
+ from = targetLocale;
1201
+ }
1202
+ return [
1203
+ format,
1204
+ targetLocale,
1205
+ message
1206
+ ];
1696
1207
  }
1697
1208
  function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
1698
- const { messageCompiler, warnHtmlMessage } = context;
1699
- if (isMessageFunction(format)) {
1700
- const msg = format;
1701
- msg.locale = msg.locale || targetLocale;
1702
- msg.key = msg.key || key;
1703
- return msg;
1704
- }
1705
- if (messageCompiler == null) {
1706
- const msg = (() => format);
1707
- msg.locale = targetLocale;
1708
- msg.key = key;
1709
- return msg;
1710
- }
1711
- // for vue-devtools timeline event
1712
- let start = null;
1713
- let startTag;
1714
- let endTag;
1715
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1716
- start = window.performance.now();
1717
- startTag = 'intlify-message-compilation-start';
1718
- endTag = 'intlify-message-compilation-end';
1719
- mark && mark(startTag);
1720
- }
1721
- const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
1722
- // for vue-devtools timeline event
1723
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1724
- const end = window.performance.now();
1725
- const emitter = context.__v_emitter;
1726
- if (emitter && start) {
1727
- emitter.emit('message-compilation', {
1728
- type: 'message-compilation',
1729
- message: format,
1730
- time: end - start,
1731
- groupId: `${'translate'}:${key}`
1732
- });
1733
- }
1734
- if (startTag && endTag && mark && measure) {
1735
- mark(endTag);
1736
- measure('intlify message compilation', startTag, endTag);
1737
- }
1738
- }
1739
- msg.locale = targetLocale;
1740
- msg.key = key;
1741
- msg.source = format;
1742
- return msg;
1743
- }
1744
- function evaluateMessage(context, msg, msgCtx) {
1745
- // for vue-devtools timeline event
1746
- let start = null;
1747
- let startTag;
1748
- let endTag;
1749
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1750
- start = window.performance.now();
1751
- startTag = 'intlify-message-evaluation-start';
1752
- endTag = 'intlify-message-evaluation-end';
1753
- mark && mark(startTag);
1754
- }
1755
- const messaged = msg(msgCtx);
1756
- // for vue-devtools timeline event
1757
- if ((process.env.NODE_ENV !== 'production') && inBrowser) {
1758
- const end = window.performance.now();
1759
- const emitter = context.__v_emitter;
1760
- if (emitter && start) {
1761
- emitter.emit('message-evaluation', {
1762
- type: 'message-evaluation',
1763
- value: messaged,
1764
- time: end - start,
1765
- groupId: `${'translate'}:${msg.key}`
1766
- });
1767
- }
1768
- if (startTag && endTag && mark && measure) {
1769
- mark(endTag);
1770
- measure('intlify message evaluation', startTag, endTag);
1771
- }
1772
- }
1773
- return messaged;
1209
+ if (isMessageFunction(format)) {
1210
+ const msg = format;
1211
+ msg.locale = msg.locale || targetLocale;
1212
+ msg.key = msg.key || key;
1213
+ return msg;
1214
+ }
1215
+ if (context.messageCompiler == null) {
1216
+ const msg = (() => format);
1217
+ msg.locale = targetLocale;
1218
+ msg.key = key;
1219
+ return msg;
1220
+ }
1221
+ let start = null;
1222
+ let startTag;
1223
+ let endTag;
1224
+ if (inBrowser && mark) {
1225
+ start = window.performance.now();
1226
+ startTag = "intlify-message-compilation-start";
1227
+ endTag = "intlify-message-compilation-end";
1228
+ mark?.(startTag);
1229
+ }
1230
+ const msg = context.messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, context.warnHtmlMessage, onError));
1231
+ if (inBrowser) {
1232
+ const end = window.performance.now();
1233
+ const emitter = context.__v_emitter;
1234
+ if (emitter && start) emitter.emit("message-compilation", {
1235
+ type: "message-compilation",
1236
+ message: format,
1237
+ time: end - start,
1238
+ groupId: `translate:${key}`
1239
+ });
1240
+ if (startTag && endTag && mark && measure) {
1241
+ mark(endTag);
1242
+ measure("intlify message compilation", startTag, endTag);
1243
+ }
1244
+ }
1245
+ msg.locale = targetLocale;
1246
+ msg.key = key;
1247
+ msg.source = format;
1248
+ return msg;
1249
+ }
1250
+ let measureEvaluateMessage;
1251
+ if (inBrowser) {
1252
+ const startTag = "intlify-message-evaluation-start";
1253
+ const endTag = "intlify-message-evaluation-end";
1254
+ measureEvaluateMessage = (context, msg, msgCtx) => {
1255
+ const start = window.performance.now();
1256
+ mark(startTag);
1257
+ const messaged = msg(msgCtx);
1258
+ const end = window.performance.now();
1259
+ context.__v_emitter?.emit("message-evaluation", {
1260
+ type: "message-evaluation",
1261
+ value: messaged,
1262
+ time: end - start,
1263
+ groupId: `translate:${msg.key}`
1264
+ });
1265
+ mark(endTag);
1266
+ measure("intlify message evaluation", startTag, endTag);
1267
+ return messaged;
1268
+ };
1774
1269
  }
1775
1270
  /** @internal */
1776
1271
  function parseTranslateArgs(...args) {
1777
- const [arg1, arg2, arg3] = args;
1778
- const options = create();
1779
- if (!isString(arg1) &&
1780
- !isNumber(arg1) &&
1781
- !isMessageFunction(arg1) &&
1782
- !isMessageAST(arg1)) {
1783
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1784
- }
1785
- // prettier-ignore
1786
- const key = isNumber(arg1)
1787
- ? String(arg1)
1788
- : isMessageFunction(arg1)
1789
- ? arg1
1790
- : arg1;
1791
- if (isNumber(arg2)) {
1792
- options.plural = arg2;
1793
- }
1794
- else if (isString(arg2)) {
1795
- options.default = arg2;
1796
- }
1797
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1798
- options.named = arg2;
1799
- }
1800
- else if (isArray(arg2)) {
1801
- options.list = arg2;
1802
- }
1803
- if (isNumber(arg3)) {
1804
- options.plural = arg3;
1805
- }
1806
- else if (isString(arg3)) {
1807
- options.default = arg3;
1808
- }
1809
- else if (isPlainObject(arg3)) {
1810
- assign(options, arg3);
1811
- }
1812
- return [key, options];
1272
+ const [arg1, arg2, arg3] = args;
1273
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1) && !isMessageAST(arg1)) throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1274
+ const key = isNumber(arg1) ? String(arg1) : isMessageFunction(arg1) ? arg1 : arg1;
1275
+ const options = create();
1276
+ if (isNumber(arg2)) options.plural = arg2;
1277
+ else if (isString(arg2)) options.default = arg2;
1278
+ else if (isPlainObject(arg2) && !isKeylessObject(arg2)) options.named = arg2;
1279
+ else if (isArray(arg2)) options.list = arg2;
1280
+ if (isNumber(arg3)) options.plural = arg3;
1281
+ else if (isString(arg3)) options.default = arg3;
1282
+ else if (isPlainObject(arg3)) assign(options, arg3);
1283
+ return [key, options];
1813
1284
  }
1814
1285
  function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
1815
- return {
1816
- locale,
1817
- key,
1818
- warnHtmlMessage,
1819
- onError: (err) => {
1820
- onError && onError(err);
1821
- if ((process.env.NODE_ENV !== 'production')) {
1822
- const _source = getSourceForCodeFrame(source);
1823
- const message = `Message compilation error: ${err.message}`;
1824
- const codeFrame = err.location &&
1825
- _source &&
1826
- generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1827
- const emitter = context.__v_emitter;
1828
- if (emitter && _source) {
1829
- emitter.emit('compile-error', {
1830
- message: _source,
1831
- error: err.message,
1832
- start: err.location && err.location.start.offset,
1833
- end: err.location && err.location.end.offset,
1834
- groupId: `${'translate'}:${key}`
1835
- });
1836
- }
1837
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1838
- }
1839
- else {
1840
- throw err;
1841
- }
1842
- },
1843
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1844
- };
1286
+ return {
1287
+ locale,
1288
+ key,
1289
+ warnHtmlMessage,
1290
+ onError: (err) => {
1291
+ onError?.(err);
1292
+ {
1293
+ const _source = getSourceForCodeFrame(source);
1294
+ const codeFrame = err.location && _source && generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
1295
+ const emitter = context.__v_emitter;
1296
+ if (emitter && _source) emitter.emit("compile-error", {
1297
+ message: _source,
1298
+ error: err.message,
1299
+ start: err.location && err.location.start.offset,
1300
+ end: err.location && err.location.end.offset,
1301
+ groupId: `translate:${key}`
1302
+ });
1303
+ const message = `Message compilation error: ${err.message}`;
1304
+ throw new SyntaxError(codeFrame ? `${message}\n${codeFrame}` : message);
1305
+ }
1306
+ throw err;
1307
+ },
1308
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1309
+ };
1845
1310
  }
1846
1311
  function getSourceForCodeFrame(source) {
1847
- if (isString(source)) {
1848
- return source;
1849
- }
1850
- else {
1851
- if (source.loc && source.loc.source) {
1852
- return source.loc.source;
1853
- }
1854
- }
1312
+ if (isString(source)) return source;
1313
+ else if (source.loc?.source) return source.loc.source;
1855
1314
  }
1856
1315
  function getMessageContextOptions(context, locale, message, options) {
1857
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1858
- const resolveMessage = (key, useLinked) => {
1859
- let val = resolveValue(message, key);
1860
- // fallback
1861
- if (val == null && (fallbackContext || useLinked)) {
1862
- const [, , message] = resolveMessageFormat(fallbackContext || context, // NOTE: if has fallbackContext, fallback to root, else if use linked, fallback to local context
1863
- key, locale, fallbackLocale, fallbackWarn, missingWarn);
1864
- val = resolveValue(message, key);
1865
- }
1866
- if (isString(val) || isMessageAST(val)) {
1867
- let occurred = false;
1868
- const onError = () => {
1869
- occurred = true;
1870
- };
1871
- const msg = compileMessageFormat(context, key, locale, val, key, onError);
1872
- return !occurred
1873
- ? msg
1874
- : NOOP_MESSAGE_FUNCTION;
1875
- }
1876
- else if (isMessageFunction(val)) {
1877
- return val;
1878
- }
1879
- else {
1880
- // TODO: should be implemented warning message
1881
- return NOOP_MESSAGE_FUNCTION;
1882
- }
1883
- };
1884
- const ctxOptions = {
1885
- locale,
1886
- modifiers,
1887
- pluralRules,
1888
- messages: resolveMessage
1889
- };
1890
- if (context.processor) {
1891
- ctxOptions.processor = context.processor;
1892
- }
1893
- if (options.list) {
1894
- ctxOptions.list = options.list;
1895
- }
1896
- if (options.named) {
1897
- ctxOptions.named = options.named;
1898
- }
1899
- if (isNumber(options.plural)) {
1900
- ctxOptions.pluralIndex = options.plural;
1901
- }
1902
- return ctxOptions;
1903
- }
1904
-
1905
- {
1906
- initFeatureFlags();
1907
- }
1908
-
1909
- export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_RESOLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getLocaleMessage, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, setLocaleMessage, translate, translateDevTools, updateFallbackLocale };
1316
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1317
+ const resolveMessage = (key, useLinked) => {
1318
+ let val = resolveValue(message, key);
1319
+ if (val == null && (fallbackContext || useLinked)) {
1320
+ const [format, , message] = resolveMessageFormat(fallbackContext || context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1321
+ val = format ?? resolveValue(message, key);
1322
+ }
1323
+ if (isString(val) || isMessageAST(val)) {
1324
+ let occurred = false;
1325
+ const onError = () => {
1326
+ occurred = true;
1327
+ };
1328
+ const msg = compileMessageFormat(context, key, locale, val, key, onError);
1329
+ return !occurred ? msg : NOOP_MESSAGE_FUNCTION;
1330
+ } else if (isMessageFunction(val)) return val;
1331
+ else return NOOP_MESSAGE_FUNCTION;
1332
+ };
1333
+ return {
1334
+ locale,
1335
+ modifiers,
1336
+ pluralRules,
1337
+ messages: resolveMessage,
1338
+ processor: context.processor ?? void 0,
1339
+ list: options.list ?? void 0,
1340
+ named: options.named ?? void 0,
1341
+ pluralIndex: isNumber(options.plural) ? options.plural : void 0
1342
+ };
1343
+ }
1344
+ //#endregion
1345
+ //#region packages/core-base/src/index.ts
1346
+ initFeatureFlags();
1347
+ //#endregion
1348
+ export { AST_NODE_PROPS_KEYS, CORE_ERROR_CODES_EXTEND_POINT, CORE_WARN_CODES_EXTEND_POINT, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_RESOLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getFallbackContext, getLocale, getLocaleMessage, getWarnMessage, handleMissing, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setFallbackContext, setLocaleMessage, translate, updateFallbackLocale };