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