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

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