@intlify/core-base 9.3.0-beta.0 → 9.3.0-beta.3

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