first commit

This commit is contained in:
2026-09-08 20:28:54 +08:00
commit 2ada8d3d5a
37380 changed files with 4886169 additions and 0 deletions
@@ -0,0 +1,27 @@
{
"systemParams": "darwin-x64-83",
"modulesFolders": [
"node_modules"
],
"flags": [],
"linkedModules": [
"vite"
],
"topLevelPatterns": [
"vue-i18n@^9.1.7"
],
"lockfileEntries": {
"@intlify/core-base@9.1.7": "https://registry.yarnpkg.com/@intlify/core-base/-/core-base-9.1.7.tgz#a454a492683690bc3d0abab82605ab5a23645bd0",
"@intlify/devtools-if@9.1.7": "https://registry.yarnpkg.com/@intlify/devtools-if/-/devtools-if-9.1.7.tgz#a5df0f33e06c3ead3e53b7f4d4b10a2d52309361",
"@intlify/message-compiler@9.1.7": "https://registry.yarnpkg.com/@intlify/message-compiler/-/message-compiler-9.1.7.tgz#4663fcc2a190f3cc6970e12565c8d6f22beeb719",
"@intlify/message-resolver@9.1.7": "https://registry.yarnpkg.com/@intlify/message-resolver/-/message-resolver-9.1.7.tgz#a95d13866c8de85784358039c8845668152e4162",
"@intlify/runtime@9.1.7": "https://registry.yarnpkg.com/@intlify/runtime/-/runtime-9.1.7.tgz#67e0d6b2fd85a5b0b301a151c2f436f93154c3c6",
"@intlify/shared@9.1.7": "https://registry.yarnpkg.com/@intlify/shared/-/shared-9.1.7.tgz#e7d8bc90cb59dc17dd7b4c85a73db16fcb7891fc",
"@intlify/vue-devtools@9.1.7": "https://registry.yarnpkg.com/@intlify/vue-devtools/-/vue-devtools-9.1.7.tgz#b08d39bb5f21ba9b1954eab9466e9408129425a7",
"@vue/devtools-api@^6.0.0-beta.7": "https://registry.yarnpkg.com/@vue/devtools-api/-/devtools-api-6.0.0-beta.15.tgz#ad7cb384e062f165bcf9c83732125bffbc2ad83d",
"source-map@0.6.1": "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263",
"vue-i18n@^9.1.7": "https://registry.yarnpkg.com/vue-i18n/-/vue-i18n-9.1.7.tgz#6f28dd2135197066508e2e65ab204a019750d773"
},
"files": [],
"artifacts": {}
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2020 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
# @intlify/core-base
The intlify core base module
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,989 @@
/*!
* @intlify/core-base v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var messageResolver = require('@intlify/message-resolver');
var runtime = require('@intlify/runtime');
var messageCompiler = require('@intlify/message-compiler');
var shared = require('@intlify/shared');
var devtoolsIf = require('@intlify/devtools-if');
let devtools = null;
function setDevToolsHook(hook) {
devtools = hook;
}
function getDevToolsHook() {
return devtools;
}
function initI18nDevTools(i18n, version, meta) {
// TODO: queue if devtools is undefined
devtools &&
devtools.emit(devtoolsIf.IntlifyDevToolsHooks.I18nInit, {
timestamp: Date.now(),
i18n,
version,
meta
});
}
const translateDevTools = /* #__PURE__*/ createDevToolsHook(devtoolsIf.IntlifyDevToolsHooks.FunctionTranslate);
function createDevToolsHook(hook) {
return (payloads) => devtools && devtools.emit(hook, payloads);
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
function getWarnMessage(code, ...args) {
return shared.format(warnMessages[code], ...args);
}
/**
* Intlify core-base version
* @internal
*/
const VERSION = '9.1.7';
const NOT_REOSLVED = -1;
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (shared.isString(val) ? val.toUpperCase() : val),
lower: (val) => (shared.isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (shared.isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
// Additional Meta for Intlify DevTools
let _additionalMeta = null;
const setAdditionalMeta = /* #__PURE__*/ (meta) => {
_additionalMeta = meta;
};
const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
// ID for CoreContext
let _cid = 0;
function createCoreContext(options = {}) {
// setup options
const version = shared.isString(options.version) ? options.version : VERSION;
const locale = shared.isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = shared.isArray(options.fallbackLocale) ||
shared.isPlainObject(options.fallbackLocale) ||
shared.isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = shared.isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = shared.isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = shared.isFunction(options.missing) ? options.missing : null;
const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = shared.isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = shared.isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = shared.isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
_cid++;
const context = {
version,
cid: _cid,
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters,
__meta
};
// for vue-devtools timeline event
{
context.__v_emitter =
internalOptions.__v_emitter != null
? internalOptions.__v_emitter
: undefined;
}
// NOTE: experimental !!
{
initI18nDevTools(context, version, __meta);
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
{
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type,
groupId: `${type}:${key}`
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return shared.isString(ret) ? ret : key;
}
else {
if (isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
}
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start) {
const context = ctx;
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (shared.isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = shared.isArray(fallback)
? fallback
: shared.isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = shared.isString(defaults) ? [defaults] : defaults;
if (shared.isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
const locale = block[i];
if (shared.isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
shared.warn(shared.format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
function clearCompileCache() {
compileCache = Object.create(null);
}
function compileToFunction(source, options = {}) {
{
// check HTML message
checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occurred = false;
const onError = options.onError || messageCompiler.defaultOnError;
options.onError = (err) => {
occurred = true;
onError(err);
};
// compile
const { code } = messageCompiler.baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occurred compile error, don't cache
return !occurred ? (compileCache[key] = msg) : msg;
}
}
function createCoreError(code) {
return messageCompiler.createCompileError(code, null, { messages: errorMessages } );
}
/** @internal */
const errorMessages = {
[14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
[15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => shared.isFunction(val);
// implementation of `translate` function
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = shared.isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
const resolvedMessage = !!options.resolvedMessage;
// prettier-ignore
const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
? !shared.isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = shared.isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = !resolvedMessage
? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
: [
key,
locale,
messages[locale] || {}
];
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!resolvedMessage &&
!(shared.isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!resolvedMessage &&
(!(shared.isString(format) || isMessageFunction(format)) ||
!shared.isString(targetLocale))) {
return unresolving ? NOT_REOSLVED : key;
}
if (shared.isString(format) && context.messageCompiler == null) {
shared.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 '${key}'.`);
return key;
}
// setup compile error detecting
let occurred = false;
const errorDetector = () => {
occurred = true;
};
// compile message format
const msg = !isMessageFunction(format)
? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
: format;
// if occurred compile error, return the message format
if (occurred) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = runtime.createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, proceed it with handler
const ret = postTranslation ? postTranslation(messaged) : messaged;
// NOTE: experimental !!
{
// prettier-ignore
const payloads = {
timestamp: Date.now(),
key: shared.isString(key)
? key
: isMessageFunction(format)
? format.key
: '',
locale: targetLocale || (isMessageFunction(format)
? format.locale
: ''),
format: shared.isString(format)
? format
: isMessageFunction(format)
? format.source
: '',
message: ret
};
payloads.meta = shared.assign({}, context.__meta, getAdditionalMeta() || {});
translateDevTools(payloads);
}
return ret;
}
function escapeParams(options) {
if (shared.isArray(options.list)) {
options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
}
else if (shared.isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (shared.isString(options.named[key])) {
options.named[key] = shared.escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (shared.inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
shared.mark && shared.mark(startTag);
}
if ((format = messageResolver.resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if (shared.inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start,
groupId: `${type}:${key}`
});
}
if (startTag && endTag && shared.mark && shared.measure) {
shared.mark(endTag);
shared.measure('intlify message resolve', startTag, endTag);
}
}
if (shared.isString(format) || shared.isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (shared.inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
shared.mark && shared.mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if (shared.inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start,
groupId: `${'translate'}:${key}`
});
}
if (startTag && endTag && shared.mark && shared.measure) {
shared.mark(endTag);
shared.measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (shared.inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
shared.mark && shared.mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if (shared.inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start,
groupId: `${'translate'}:${msg.key}`
});
}
if (startTag && endTag && shared.mark && shared.measure) {
shared.mark(endTag);
shared.measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!shared.isString(arg1) && !shared.isNumber(arg1) && !isMessageFunction(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
// prettier-ignore
const key = shared.isNumber(arg1)
? String(arg1)
: isMessageFunction(arg1)
? arg1
: arg1;
if (shared.isNumber(arg2)) {
options.plural = arg2;
}
else if (shared.isString(arg2)) {
options.default = arg2;
}
else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
options.named = arg2;
}
else if (shared.isArray(arg2)) {
options.list = arg2;
}
if (shared.isNumber(arg3)) {
options.plural = arg3;
}
else if (shared.isString(arg3)) {
options.default = arg3;
}
else if (shared.isPlainObject(arg3)) {
shared.assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
shared.generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context
.__v_emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset,
groupId: `${'translate'}:${key}`
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
},
onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = messageResolver.resolveValue(message, key);
if (shared.isString(val)) {
let occurred = false;
const errorDetector = () => {
occurred = true;
};
const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
return !occurred
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (shared.isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
if (!Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseDateTimeArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = shared.isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!shared.isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (shared.isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!shared.isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
let value;
if (shared.isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (shared.isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (shared.isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
if (shared.isString(arg2)) {
options.key = arg2;
}
else if (shared.isPlainObject(arg2)) {
options = arg2;
}
if (shared.isString(arg3)) {
options.locale = arg3;
}
else if (shared.isPlainObject(arg3)) {
overrides = arg3;
}
if (shared.isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
if (!Availabilities.numberFormat) {
onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseNumberArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = shared.isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!shared.isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (shared.isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!shared.isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
if (!shared.isNumber(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (shared.isString(arg2)) {
options.key = arg2;
}
else if (shared.isPlainObject(arg2)) {
options = arg2;
}
if (shared.isString(arg3)) {
options.locale = arg3;
}
else if (shared.isPlainObject(arg3)) {
overrides = arg3;
}
if (shared.isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
exports.createCompileError = messageCompiler.createCompileError;
exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
exports.NOT_REOSLVED = NOT_REOSLVED;
exports.VERSION = VERSION;
exports.clearCompileCache = clearCompileCache;
exports.clearDateTimeFormat = clearDateTimeFormat;
exports.clearNumberFormat = clearNumberFormat;
exports.compileToFunction = compileToFunction;
exports.createCoreContext = createCoreContext;
exports.createCoreError = createCoreError;
exports.datetime = datetime;
exports.getAdditionalMeta = getAdditionalMeta;
exports.getDevToolsHook = getDevToolsHook;
exports.getLocaleChain = getLocaleChain;
exports.getWarnMessage = getWarnMessage;
exports.handleMissing = handleMissing;
exports.initI18nDevTools = initI18nDevTools;
exports.isMessageFunction = isMessageFunction;
exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
exports.isTranslateMissingWarn = isTranslateMissingWarn;
exports.number = number;
exports.parseDateTimeArgs = parseDateTimeArgs;
exports.parseNumberArgs = parseNumberArgs;
exports.parseTranslateArgs = parseTranslateArgs;
exports.registerMessageCompiler = registerMessageCompiler;
exports.setAdditionalMeta = setAdditionalMeta;
exports.setDevToolsHook = setDevToolsHook;
exports.translate = translate;
exports.translateDevTools = translateDevTools;
exports.updateFallbackLocale = updateFallbackLocale;
Object.keys(messageResolver).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = messageResolver[k];
});
Object.keys(runtime).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = runtime[k];
});
@@ -0,0 +1,735 @@
/*!
* @intlify/core-base v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var messageResolver = require('@intlify/message-resolver');
var runtime = require('@intlify/runtime');
var messageCompiler = require('@intlify/message-compiler');
var shared = require('@intlify/shared');
var devtoolsIf = require('@intlify/devtools-if');
let devtools = null;
function setDevToolsHook(hook) {
devtools = hook;
}
function getDevToolsHook() {
return devtools;
}
function initI18nDevTools(i18n, version, meta) {
// TODO: queue if devtools is undefined
devtools &&
devtools.emit(devtoolsIf.IntlifyDevToolsHooks.I18nInit, {
timestamp: Date.now(),
i18n,
version,
meta
});
}
const translateDevTools = /* #__PURE__*/ createDevToolsHook(devtoolsIf.IntlifyDevToolsHooks.FunctionTranslate);
function createDevToolsHook(hook) {
return (payloads) => devtools && devtools.emit(hook, payloads);
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
function getWarnMessage(code, ...args) {
return shared.format(warnMessages[code], ...args);
}
/**
* Intlify core-base version
* @internal
*/
const VERSION = '9.1.7';
const NOT_REOSLVED = -1;
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (shared.isString(val) ? val.toUpperCase() : val),
lower: (val) => (shared.isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (shared.isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
// Additional Meta for Intlify DevTools
let _additionalMeta = null;
const setAdditionalMeta = /* #__PURE__*/ (meta) => {
_additionalMeta = meta;
};
const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
// ID for CoreContext
let _cid = 0;
function createCoreContext(options = {}) {
// setup options
const version = shared.isString(options.version) ? options.version : VERSION;
const locale = shared.isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = shared.isArray(options.fallbackLocale) ||
shared.isPlainObject(options.fallbackLocale) ||
shared.isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = shared.isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = shared.isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = shared.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = shared.isFunction(options.missing) ? options.missing : null;
const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = shared.isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = shared.isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = shared.isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
_cid++;
const context = {
version,
cid: _cid,
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters,
__meta
};
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
if (missing !== null) {
const ret = missing(context, locale, key, type);
return shared.isString(ret) ? ret : key;
}
else {
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start) {
const context = ctx;
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (shared.isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = shared.isArray(fallback)
? fallback
: shared.isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = shared.isString(defaults) ? [defaults] : defaults;
if (shared.isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
const locale = block[i];
if (shared.isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
function clearCompileCache() {
compileCache = Object.create(null);
}
function compileToFunction(source, options = {}) {
{
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occurred = false;
const onError = options.onError || messageCompiler.defaultOnError;
options.onError = (err) => {
occurred = true;
onError(err);
};
// compile
const { code } = messageCompiler.baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occurred compile error, don't cache
return !occurred ? (compileCache[key] = msg) : msg;
}
}
function createCoreError(code) {
return messageCompiler.createCompileError(code, null, undefined);
}
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => shared.isFunction(val);
// implementation of `translate` function
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = shared.isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
const resolvedMessage = !!options.resolvedMessage;
// prettier-ignore
const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
? !shared.isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = shared.isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = !resolvedMessage
? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
: [
key,
locale,
messages[locale] || {}
];
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!resolvedMessage &&
!(shared.isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!resolvedMessage &&
(!(shared.isString(format) || isMessageFunction(format)) ||
!shared.isString(targetLocale))) {
return unresolving ? NOT_REOSLVED : key;
}
// setup compile error detecting
let occurred = false;
const errorDetector = () => {
occurred = true;
};
// compile message format
const msg = !isMessageFunction(format)
? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
: format;
// if occurred compile error, return the message format
if (occurred) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = runtime.createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, proceed it with handler
const ret = postTranslation ? postTranslation(messaged) : messaged;
return ret;
}
function escapeParams(options) {
if (shared.isArray(options.list)) {
options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
}
else if (shared.isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (shared.isString(options.named[key])) {
options.named[key] = shared.escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = locales[i];
message =
messages[targetLocale] || {};
if ((format = messageResolver.resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
if (shared.isString(format) || shared.isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
}
return [format, targetLocale, message];
}
function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
const messaged = msg(msgCtx);
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!shared.isString(arg1) && !shared.isNumber(arg1) && !isMessageFunction(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
// prettier-ignore
const key = shared.isNumber(arg1)
? String(arg1)
: isMessageFunction(arg1)
? arg1
: arg1;
if (shared.isNumber(arg2)) {
options.plural = arg2;
}
else if (shared.isString(arg2)) {
options.default = arg2;
}
else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
options.named = arg2;
}
else if (shared.isArray(arg2)) {
options.list = arg2;
}
if (shared.isNumber(arg3)) {
options.plural = arg3;
}
else if (shared.isString(arg3)) {
options.default = arg3;
}
else if (shared.isPlainObject(arg3)) {
shared.assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
throw err;
}
},
onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = messageResolver.resolveValue(message, key);
if (shared.isString(val)) {
let occurred = false;
const errorDetector = () => {
occurred = true;
};
const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
return !occurred
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (shared.isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
// implementation of `datetime` function
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
const [key, value, options, overrides] = parseDateTimeArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = shared.isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!shared.isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = locales[i];
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (shared.isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
}
// checking format and target locale
if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!shared.isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
let value;
if (shared.isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (shared.isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (shared.isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
if (shared.isString(arg2)) {
options.key = arg2;
}
else if (shared.isPlainObject(arg2)) {
options = arg2;
}
if (shared.isString(arg3)) {
options.locale = arg3;
}
else if (shared.isPlainObject(arg3)) {
overrides = arg3;
}
if (shared.isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
const [key, value, options, overrides] = parseNumberArgs(...args);
const missingWarn = shared.isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
shared.isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = shared.isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!shared.isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = locales[i];
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (shared.isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
}
// checking format and target locale
if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!shared.isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
if (!shared.isNumber(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (shared.isString(arg2)) {
options.key = arg2;
}
else if (shared.isPlainObject(arg2)) {
options = arg2;
}
if (shared.isString(arg3)) {
options.locale = arg3;
}
else if (shared.isPlainObject(arg3)) {
overrides = arg3;
}
if (shared.isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
exports.createCompileError = messageCompiler.createCompileError;
exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
exports.NOT_REOSLVED = NOT_REOSLVED;
exports.VERSION = VERSION;
exports.clearCompileCache = clearCompileCache;
exports.clearDateTimeFormat = clearDateTimeFormat;
exports.clearNumberFormat = clearNumberFormat;
exports.compileToFunction = compileToFunction;
exports.createCoreContext = createCoreContext;
exports.createCoreError = createCoreError;
exports.datetime = datetime;
exports.getAdditionalMeta = getAdditionalMeta;
exports.getDevToolsHook = getDevToolsHook;
exports.getLocaleChain = getLocaleChain;
exports.getWarnMessage = getWarnMessage;
exports.handleMissing = handleMissing;
exports.initI18nDevTools = initI18nDevTools;
exports.isMessageFunction = isMessageFunction;
exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
exports.isTranslateMissingWarn = isTranslateMissingWarn;
exports.number = number;
exports.parseDateTimeArgs = parseDateTimeArgs;
exports.parseNumberArgs = parseNumberArgs;
exports.parseTranslateArgs = parseTranslateArgs;
exports.registerMessageCompiler = registerMessageCompiler;
exports.setAdditionalMeta = setAdditionalMeta;
exports.setDevToolsHook = setDevToolsHook;
exports.translate = translate;
exports.translateDevTools = translateDevTools;
exports.updateFallbackLocale = updateFallbackLocale;
Object.keys(messageResolver).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = messageResolver[k];
});
Object.keys(runtime).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = runtime[k];
});
@@ -0,0 +1,576 @@
import { CompileError } from '@intlify/message-compiler';
import { CompileErrorCodes } from '@intlify/message-compiler';
import type { CompileOptions } from '@intlify/message-compiler';
import type { CoreMissingType } from '@intlify/runtime';
import { createCompileError } from '@intlify/message-compiler';
import type { FallbackLocale } from '@intlify/runtime';
import type { IntlifyDevToolsEmitter } from '@intlify/devtools-if';
import type { IntlifyDevToolsHookPayloads } from '@intlify/devtools-if';
import { IntlifyDevToolsHooks } from '@intlify/devtools-if';
import type { LinkedModifiers } from '@intlify/runtime';
import type { Locale } from '@intlify/runtime';
import type { MessageFunction } from '@intlify/runtime';
import type { MessageProcessor } from '@intlify/runtime';
import type { MessageType } from '@intlify/runtime';
import type { NamedValue } from '@intlify/runtime';
import type { Path } from '@intlify/message-resolver';
import type { PluralizationRules } from '@intlify/runtime';
import type { VueDevToolsEmitter } from '@intlify/vue-devtools';
export declare function clearCompileCache(): void;
/* Excluded from this release type: clearDateTimeFormat */
/* Excluded from this release type: clearNumberFormat */
export { CompileError }
export { CompileErrorCodes }
export declare function compileToFunction<T = string>(source: string, options?: CompileOptions): MessageFunction<T>;
export declare interface CoreCommonContext<Message = string> {
cid: number;
version: string;
locale: Locale;
fallbackLocale: FallbackLocale;
missing: CoreMissingHandler<Message> | null;
missingWarn: boolean | RegExp;
fallbackWarn: boolean | RegExp;
fallbackFormat: boolean;
unresolving: boolean;
onWarn(msg: string, err?: Error): void;
}
export declare interface CoreContext<Messages = {}, DateTimeFormats = {}, NumberFormats = {}, Message = string> extends CoreTranslationContext<Messages, Message>, CoreDateTimeContext<DateTimeFormats, Message>, CoreNumberContext<NumberFormats, Message> {
}
export declare interface CoreDateTimeContext<DateTimeFormats = {}, Message = string> extends CoreCommonContext<Message> {
datetimeFormats: DateTimeFormats;
}
export declare interface CoreError extends CompileError {
code: CoreErrorCodes;
}
export declare const enum CoreErrorCodes {
INVALID_ARGUMENT = 14,
INVALID_DATE_ARGUMENT = 15,
INVALID_ISO_DATE_ARGUMENT = 16,
__EXTEND_POINT__ = 17
}
export declare interface CoreInternalContext {
__datetimeFormatters: Map<string, Intl.DateTimeFormat>;
__numberFormatters: Map<string, Intl.NumberFormat>;
__localeChainCache?: Map<Locale, Locale[]>;
__v_emitter?: VueDevToolsEmitter;
__meta: MetaInfo;
}
export declare interface CoreInternalOptions {
__datetimeFormatters?: Map<string, Intl.DateTimeFormat>;
__numberFormatters?: Map<string, Intl.NumberFormat>;
__v_emitter?: VueDevToolsEmitter;
__meta?: MetaInfo;
}
export declare type CoreMissingHandler<Message = string> = (context: CoreCommonContext<Message>, locale: Locale, key: Path, type: CoreMissingType, ...values: unknown[]) => string | void;
export declare interface CoreNumberContext<NumberFormats = {}, Message = string> extends CoreCommonContext<Message> {
numberFormats: NumberFormats;
}
export declare interface CoreOptions<Message = string> {
version?: string;
locale?: Locale;
fallbackLocale?: FallbackLocale;
messages?: LocaleMessages<Message>;
datetimeFormats?: DateTimeFormats;
numberFormats?: NumberFormats;
modifiers?: LinkedModifiers<Message>;
pluralRules?: PluralizationRules;
missing?: CoreMissingHandler<Message>;
missingWarn?: boolean | RegExp;
fallbackWarn?: boolean | RegExp;
fallbackFormat?: boolean;
unresolving?: boolean;
postTranslation?: PostTranslationHandler<Message>;
processor?: MessageProcessor<Message>;
warnHtmlMessage?: boolean;
escapeParameter?: boolean;
messageCompiler?: MessageCompiler<Message>;
onWarn?: (msg: string, err?: Error) => void;
}
export declare interface CoreTranslationContext<Messages = {}, Message = string> extends CoreCommonContext<Message> {
messages: Messages;
modifiers: LinkedModifiers<Message>;
pluralRules?: PluralizationRules;
postTranslation: PostTranslationHandler<Message> | null;
processor: MessageProcessor<Message> | null;
warnHtmlMessage: boolean;
escapeParameter: boolean;
messageCompiler: MessageCompiler<Message> | null;
}
export declare const enum CoreWarnCodes {
NOT_FOUND_KEY = 0,
FALLBACK_TO_TRANSLATE = 1,
CANNOT_FORMAT_NUMBER = 2,
FALLBACK_TO_NUMBER_FORMAT = 3,
CANNOT_FORMAT_DATE = 4,
FALLBACK_TO_DATE_FORMAT = 5,
__EXTEND_POINT__ = 6
}
export { createCompileError }
export declare function createCoreContext<Message = string, Options extends CoreOptions<Message> = object, Messages extends Record<keyof Options['messages'], LocaleMessageDictionary<Message>> = Record<keyof Options['messages'], LocaleMessageDictionary<Message>>, DateTimeFormats extends Record<keyof Options['datetimeFormats'], DateTimeFormat> = Record<keyof Options['datetimeFormats'], DateTimeFormat>, NumberFormats extends Record<keyof Options['numberFormats'], NumberFormat> = Record<keyof Options['numberFormats'], NumberFormat>>(options?: Options): CoreContext<Options['messages'], Options['datetimeFormats'], Options['numberFormats'], Message>;
export declare function createCoreError(code: CoreErrorCodes): CoreError;
/**
* number
*/
export declare type CurrencyDisplay = 'symbol' | 'code' | 'name';
export declare interface CurrencyNumberFormatOptions extends Intl.NumberFormatOptions {
style: 'currency';
currency: string;
currencyDisplay?: CurrencyDisplay;
localeMatcher?: LocaleMatcher;
formatMatcher?: FormatMatcher;
}
export declare function datetime<DateTimeFormats, Message = string>(context: CoreDateTimeContext<DateTimeFormats, Message>, value: number | Date): string | number | Intl.DateTimeFormatPart[];
export declare function datetime<DateTimeFormats, Message = string>(context: CoreDateTimeContext<DateTimeFormats, Message>, value: number | Date, key: string): string | number | Intl.DateTimeFormatPart[];
export declare function datetime<DateTimeFormats, Message = string>(context: CoreDateTimeContext<DateTimeFormats, Message>, value: number | Date, key: string, locale: Locale): string | number | Intl.DateTimeFormatPart[];
export declare function datetime<DateTimeFormats, Message = string>(context: CoreDateTimeContext<DateTimeFormats, Message>, value: number | Date, options: DateTimeOptions): string | number | Intl.DateTimeFormatPart[];
export declare function datetime<DateTimeFormats, Message = string>(context: CoreDateTimeContext<DateTimeFormats, Message>, ...args: unknown[]): string | number | Intl.DateTimeFormatPart[];
export declare type DateTimeDigital = 'numeric' | '2-digit';
export declare type DateTimeFormat = {
[key: string]: DateTimeFormatOptions;
};
export declare type DateTimeFormatOptions = Intl.DateTimeFormatOptions | SpecificDateTimeFormatOptions;
export declare type DateTimeFormats = {
[locale: string]: DateTimeFormat;
};
/**
* datetime
*/
export declare type DateTimeHumanReadable = 'long' | 'short' | 'narrow';
/**
* # datetime
*
* ## usages:
* // for example `context.datetimeFormats` below
* 'en-US': {
* short: {
* year: 'numeric', month: '2-digit', day: '2-digit',
* hour: '2-digit', minute: '2-digit'
* }
* },
* 'ja-JP': { ... }
*
* // datetimeable value only
* datetime(context, value)
*
* // key argument
* datetime(context, value, 'short')
*
* // key & locale argument
* datetime(context, value, 'short', 'ja-JP')
*
* // object sytle argument
* datetime(context, value, { key: 'short', locale: 'ja-JP' })
*
* // suppress localize miss warning option, override context.missingWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', missingWarn: false })
*
* // suppress localize fallback warning option, override context.fallbackWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', fallbackWarn: false })
*
* // if you specify `part` options, you can get an array of objects containing the formatted datetime in parts
* datetime(context, value, { key: 'short', part: true })
*
* // orverride context.datetimeFormats[locale] options with functino options
* datetime(cnotext, value, 'short', { currency: 'EUR' })
* datetime(cnotext, value, 'short', 'ja-JP', { currency: 'EUR' })
* datetime(context, value, { key: 'short', part: true }, { currency: 'EUR'})
*/
/**
* DateTime options
*
* @remarks
* Options for Datetime formatting API
*
* @VueI18nGeneral
*/
export declare interface DateTimeOptions {
/**
* @remarks
* The target format key
*/
key?: string;
/**
* @remarks
* The locale of localization
*/
locale?: Locale;
/**
* @remarks
* Whether suppress warnings outputted when localization fails
*/
missingWarn?: boolean;
/**
* @remarks
* Whether do resolve on format keys when your language lacks a formatting for a key
*/
fallbackWarn?: boolean;
/**
* @remarks
* Whether to use [Intel.DateTimeFormat#formatToParts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*/
part?: boolean;
}
export declare type FormatMatcher = 'basic' | 'best fit';
export declare type FormattedNumberPart = {
type: FormattedNumberPartType;
value: string;
};
export declare type FormattedNumberPartType = 'currency' | 'decimal' | 'fraction' | 'group' | 'infinity' | 'integer' | 'literal' | 'minusSign' | 'nan' | 'plusSign' | 'percentSign';
export declare const getAdditionalMeta: () => MetaInfo | null;
export declare function getDevToolsHook(): IntlifyDevToolsEmitter | null;
/* Excluded from this release type: getLocaleChain */
export declare function getWarnMessage(code: CoreWarnCodes, ...args: unknown[]): string;
/* Excluded from this release type: handleMissing */
export declare function initI18nDevTools(i18n: unknown, version: string, meta?: Record<string, unknown>): void;
export declare const isMessageFunction: <T>(val: unknown) => val is MessageFunction<T>;
/* Excluded from this release type: isTranslateFallbackWarn */
/* Excluded from this release type: isTranslateMissingWarn */
export declare type LocaleMatcher = 'lookup' | 'best fit';
/** @VueI18nGeneral */
export declare interface LocaleMessageArray<Message = string> extends Array<LocaleMessageValue<Message>> {
}
/** @VueI18nGeneral */
export declare type LocaleMessageDictionary<Message = string> = {
[property: string]: LocaleMessageValue<Message>;
};
/** @VueI18nGeneral */
export declare type LocaleMessages<Message = string> = Record<Locale, LocaleMessageDictionary<Message>>;
/** @VueI18nGeneral */
export declare type LocaleMessageValue<Message = string> = string | MessageFunction<Message> | LocaleMessageDictionary<Message> | LocaleMessageArray<Message>;
export declare type MessageCompiler<Message = string> = (source: string, options?: CompileOptions) => MessageFunction<Message>;
export declare interface MetaInfo {
[field: string]: unknown;
}
export declare const MISSING_RESOLVE_VALUE = "";
export declare const NOT_REOSLVED = -1;
export declare function number<NumberFormats, Message = string>(context: CoreNumberContext<NumberFormats, Message>, value: number): string | number | Intl.NumberFormatPart[];
export declare function number<NumberFormats, Message = string>(context: CoreNumberContext<NumberFormats, Message>, value: number, key: string): string | number | Intl.NumberFormatPart[];
export declare function number<NumberFormats, Message = string>(context: CoreNumberContext<NumberFormats, Message>, value: number, key: string, locale: Locale): string | number | Intl.NumberFormatPart[];
export declare function number<NumberFormats, Message = string>(context: CoreNumberContext<NumberFormats, Message>, value: number, options: NumberOptions): string | number | Intl.NumberFormatPart[];
export declare function number<NumberFormats, Message = string>(context: CoreNumberContext<NumberFormats, Message>, ...args: unknown[]): string | number | Intl.NumberFormatPart[];
export declare type NumberFormat = {
[key: string]: NumberFormatOptions;
};
export declare type NumberFormatOptions = Intl.NumberFormatOptions | SpecificNumberFormatOptions | CurrencyNumberFormatOptions;
export declare type NumberFormats = {
[locale: string]: NumberFormat;
};
export declare type NumberFormatToPartsResult = {
[index: number]: FormattedNumberPart;
};
/**
* # number
*
* ## usages
* // for example `context.numberFormats` below
* 'en-US': {
* 'currency': {
* style: 'currency', currency: 'USD', currencyDisplay: 'symbol'
* }
* },
* 'ja-JP: { ... }
*
* // value only
* number(context, value)
*
* // key argument
* number(context, value, 'currency')
*
* // key & locale argument
* number(context, value, 'currency', 'ja-JP')
*
* // object sytle argument
* number(context, value, { key: 'currency', locale: 'ja-JP' })
*
* // suppress localize miss warning option, override context.missingWarn
* number(context, value, { key: 'currency', locale: 'ja-JP', missingWarn: false })
*
* // suppress localize fallback warning option, override context.fallbackWarn
* number(context, value, { key: 'currency', locale: 'ja-JP', fallbackWarn: false })
*
* // if you specify `part` options, you can get an array of objects containing the formatted number in parts
* number(context, value, { key: 'currenty', part: true })
*
* // orverride context.numberFormats[locale] options with functino options
* number(cnotext, value, 'currency', { year: '2-digit' })
* number(cnotext, value, 'currency', 'ja-JP', { year: '2-digit' })
* number(context, value, { key: 'currenty', part: true }, { year: '2-digit'})
*/
/**
* Number Options
*
* @remarks
* Options for Number formatting API
*
* @VueI18nGeneral
*/
export declare interface NumberOptions {
/**
* @remarks
* The target format key
*/
key?: string;
/**
* @remarks
* The locale of localization
*/
locale?: Locale;
/**
* @remarks
* Whether suppress warnings outputted when localization fails
*/
missingWarn?: boolean;
/**
* @remarks
* Whether do resolve on format keys when your language lacks a formatting for a key
*/
fallbackWarn?: boolean;
/**
* @remarks
* Whether to use [Intel.NumberFormat#formatToParts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*/
part?: boolean;
}
/* Excluded from this release type: parseDateTimeArgs */
/* Excluded from this release type: parseNumberArgs */
/* Excluded from this release type: parseTranslateArgs */
/** @VueI18nGeneral */
export declare type PostTranslationHandler<Message = string> = (translated: MessageType<Message>) => MessageType<Message>;
export declare function registerMessageCompiler<Message>(compiler: MessageCompiler<Message>): void;
export declare const setAdditionalMeta: (meta: MetaInfo | null) => void;
export declare function setDevToolsHook(hook: IntlifyDevToolsEmitter | null): void;
export declare interface SpecificDateTimeFormatOptions extends Intl.DateTimeFormatOptions {
year?: DateTimeDigital;
month?: DateTimeDigital | DateTimeHumanReadable;
day?: DateTimeDigital;
hour?: DateTimeDigital;
minute?: DateTimeDigital;
second?: DateTimeDigital;
weekday?: DateTimeHumanReadable;
era?: DateTimeHumanReadable;
timeZoneName?: 'long' | 'short';
localeMatcher?: LocaleMatcher;
formatMatcher?: FormatMatcher;
}
export declare interface SpecificNumberFormatOptions extends Intl.NumberFormatOptions {
style?: 'decimal' | 'percent';
currency?: string;
currencyDisplay?: CurrencyDisplay;
localeMatcher?: LocaleMatcher;
formatMatcher?: FormatMatcher;
}
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, plural: number): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, plural: number, options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, message: MessageFunction<Message> | string, plural: number, options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, defaultMsg: string): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, defaultMsg: string, options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, list: unknown[]): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, list: unknown[], plural: number): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, list: unknown[], defaultMsg: string): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, list: unknown[], options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, message: MessageFunction<Message> | string, list: unknown[], options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, named: NamedValue): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, named: NamedValue, plural: number): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, named: NamedValue, defaultMsg: string): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, key: Path | number, named: NamedValue, options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, message: MessageFunction<Message> | string, named: NamedValue, options: TranslateOptions): MessageType<Message> | number;
export declare function translate<Messages, Message = string>(context: CoreTranslationContext<Messages, Message>, ...args: unknown[]): MessageType<Message> | number;
export declare const translateDevTools: (payloads: IntlifyDevToolsHookPayloads[IntlifyDevToolsHooks]) => void | null;
/**
* # translate
*
* ## usages:
* // for example, locale messages key
* { 'foo.bar': 'hi {0} !' or 'hi {name} !' }
*
* // no argument, context & path only
* translate(context, 'foo.bar')
*
* // list argument
* translate(context, 'foo.bar', ['kazupon'])
*
* // named argument
* translate(context, 'foo.bar', { name: 'kazupon' })
*
* // plural choice number
* translate(context, 'foo.bar', 2)
*
* // plural choice number with name argument
* translate(context, 'foo.bar', { name: 'kazupon' }, 2)
*
* // default message argument
* translate(context, 'foo.bar', 'this is default message')
*
* // default message with named argument
* translate(context, 'foo.bar', { name: 'kazupon' }, 'Hello {name} !')
*
* // use key as default message
* translate(context, 'hi {0} !', ['kazupon'], { default: true })
*
* // locale option, override context.locale
* translate(context, 'foo.bar', { name: 'kazupon' }, { locale: 'ja' })
*
* // suppress localize miss warning option, override context.missingWarn
* translate(context, 'foo.bar', { name: 'kazupon' }, { missingWarn: false })
*
* // suppress localize fallback warning option, override context.fallbackWarn
* translate(context, 'foo.bar', { name: 'kazupon' }, { fallbackWarn: false })
*
* // escape parameter option, override context.escapeParameter
* translate(context, 'foo.bar', { name: 'kazupon' }, { escapeParameter: true })
*/
/**
* Translate Options
*
* @remarks
* Options for Translation API
*
* @VueI18nGeneral
*/
export declare interface TranslateOptions {
/**
* @remarks
* List interpolation
*/
list?: unknown[];
/**
* @remarks
* Named interpolation
*/
named?: NamedValue;
/**
* @remarks
* Plulralzation choice number
*/
plural?: number;
/**
* @remarks
* Default message when is occurred translation missing
*/
default?: string | boolean;
/**
* @remarks
* The locale of localization
*/
locale?: Locale;
/**
* @remarks
* Whether suppress warnings outputted when localization fails
*/
missingWarn?: boolean;
/**
* @remarks
* Whether do template interpolation on translation keys when your language lacks a translation for a key
*/
fallbackWarn?: boolean;
/**
* @remarks
* Whether do escape parameter for list or named interpolation values
*/
escapeParameter?: boolean;
/**
* @remarks
* Whether the message has been resolved
*/
resolvedMessage?: boolean;
}
/* Excluded from this release type: updateFallbackLocale */
/* Excluded from this release type: VERSION */
export * from "@intlify/message-resolver";
export * from "@intlify/runtime";
export { }
File diff suppressed because one or more lines are too long
@@ -0,0 +1,965 @@
/*!
* @intlify/core-base v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
import { format, isString, isArray, isPlainObject, assign, isFunction, isBoolean, isRegExp, warn, isObject, escapeHtml, inBrowser, mark, measure, generateCodeFrame, generateFormatCacheKey, isNumber, isEmptyObject, isDate, getGlobalThis } from '@intlify/shared';
import { resolveValue } from '@intlify/message-resolver';
export * from '@intlify/message-resolver';
import { createMessageContext } from '@intlify/runtime';
export * from '@intlify/runtime';
import { defaultOnError, baseCompile, createCompileError } from '@intlify/message-compiler';
export { createCompileError } from '@intlify/message-compiler';
import { IntlifyDevToolsHooks } from '@intlify/devtools-if';
let devtools = null;
function setDevToolsHook(hook) {
devtools = hook;
}
function getDevToolsHook() {
return devtools;
}
function initI18nDevTools(i18n, version, meta) {
// TODO: queue if devtools is undefined
devtools &&
devtools.emit(IntlifyDevToolsHooks.I18nInit, {
timestamp: Date.now(),
i18n,
version,
meta
});
}
const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
function createDevToolsHook(hook) {
return (payloads) => devtools && devtools.emit(hook, payloads);
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
/**
* Intlify core-base version
* @internal
*/
const VERSION = '9.1.7';
const NOT_REOSLVED = -1;
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (isString(val) ? val.toUpperCase() : val),
lower: (val) => (isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
// Additional Meta for Intlify DevTools
let _additionalMeta = null;
const setAdditionalMeta = /* #__PURE__*/ (meta) => {
_additionalMeta = meta;
};
const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
// ID for CoreContext
let _cid = 0;
function createCoreContext(options = {}) {
// setup options
const version = isString(options.version) ? options.version : VERSION;
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = isFunction(options.missing) ? options.missing : null;
const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
_cid++;
const context = {
version,
cid: _cid,
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters,
__meta
};
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
context.__v_emitter =
internalOptions.__v_emitter != null
? internalOptions.__v_emitter
: undefined;
}
// NOTE: experimental !!
if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
initI18nDevTools(context, version, __meta);
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type,
groupId: `${type}:${key}`
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return isString(ret) ? ret : key;
}
else {
if ((process.env.NODE_ENV !== 'production') && isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
}
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start) {
const context = ctx;
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = isArray(fallback)
? fallback
: isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = isString(defaults) ? [defaults] : defaults;
if (isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && isBoolean(follow); i++) {
const locale = block[i];
if (isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((isArray(blocks) || isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
warn(format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
function clearCompileCache() {
compileCache = Object.create(null);
}
function compileToFunction(source, options = {}) {
{
// check HTML message
(process.env.NODE_ENV !== 'production') && checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occurred = false;
const onError = options.onError || defaultOnError;
options.onError = (err) => {
occurred = true;
onError(err);
};
// compile
const { code } = baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occurred compile error, don't cache
return !occurred ? (compileCache[key] = msg) : msg;
}
}
function createCoreError(code) {
return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages } : undefined);
}
/** @internal */
const errorMessages = {
[14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
[15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => isFunction(val);
// implementation of `translate` function
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
const resolvedMessage = !!options.resolvedMessage;
// prettier-ignore
const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
? !isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = !resolvedMessage
? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
: [
key,
locale,
messages[locale] || {}
];
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!resolvedMessage &&
!(isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!resolvedMessage &&
(!(isString(format) || isMessageFunction(format)) ||
!isString(targetLocale))) {
return unresolving ? NOT_REOSLVED : key;
}
if ((process.env.NODE_ENV !== 'production') && isString(format) && context.messageCompiler == null) {
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 '${key}'.`);
return key;
}
// setup compile error detecting
let occurred = false;
const errorDetector = () => {
occurred = true;
};
// compile message format
const msg = !isMessageFunction(format)
? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
: format;
// if occurred compile error, return the message format
if (occurred) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, proceed it with handler
const ret = postTranslation ? postTranslation(messaged) : messaged;
// NOTE: experimental !!
if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
// prettier-ignore
const payloads = {
timestamp: Date.now(),
key: isString(key)
? key
: isMessageFunction(format)
? format.key
: '',
locale: targetLocale || (isMessageFunction(format)
? format.locale
: ''),
format: isString(format)
? format
: isMessageFunction(format)
? format.source
: '',
message: ret
};
payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
translateDevTools(payloads);
}
return ret;
}
function escapeParams(options) {
if (isArray(options.list)) {
options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
}
else if (isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (isString(options.named[key])) {
options.named[key] = escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if ((process.env.NODE_ENV !== 'production') &&
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
mark && mark(startTag);
}
if ((format = resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start,
groupId: `${type}:${key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message resolve', startTag, endTag);
}
}
if (isString(format) || isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
mark && mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start,
groupId: `${'translate'}:${key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
mark && mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start,
groupId: `${'translate'}:${msg.key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
// prettier-ignore
const key = isNumber(arg1)
? String(arg1)
: isMessageFunction(arg1)
? arg1
: arg1;
if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isString(arg2)) {
options.default = arg2;
}
else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
options.named = arg2;
}
else if (isArray(arg2)) {
options.list = arg2;
}
if (isNumber(arg3)) {
options.plural = arg3;
}
else if (isString(arg3)) {
options.default = arg3;
}
else if (isPlainObject(arg3)) {
assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
if ((process.env.NODE_ENV !== 'production')) {
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context
.__v_emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset,
groupId: `${'translate'}:${key}`
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
else {
throw err;
}
},
onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = resolveValue(message, key);
if (isString(val)) {
let occurred = false;
const errorDetector = () => {
occurred = true;
};
const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
return !occurred
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
if ((process.env.NODE_ENV !== 'production') && !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseDateTimeArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if ((process.env.NODE_ENV !== 'production') &&
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
let value;
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
overrides = arg3;
}
if (isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
if ((process.env.NODE_ENV !== 'production') && !Availabilities.numberFormat) {
onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseNumberArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if ((process.env.NODE_ENV !== 'production') &&
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
if (!isNumber(arg1)) {
throw createCoreError(14 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
overrides = arg3;
}
if (isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
{
if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
}
}
export { MISSING_RESOLVE_VALUE, NOT_REOSLVED, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compileToFunction, createCoreContext, createCoreError, datetime, getAdditionalMeta, getDevToolsHook, getLocaleChain, getWarnMessage, handleMissing, initI18nDevTools, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerMessageCompiler, setAdditionalMeta, setDevToolsHook, translate, translateDevTools, updateFallbackLocale };
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/core-base.cjs.prod.js')
} else {
module.exports = require('./dist/core-base.cjs.js')
}
@@ -0,0 +1,59 @@
{
"name": "@intlify/core-base",
"version": "9.1.7",
"description": "@intlify/core-base",
"keywords": [
"core",
"fundamental",
"i18n",
"internationalization",
"intlify"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/core-base#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/core"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/core-base.esm-bundler.js",
"unpkg": "dist/core-base.global.js",
"jsdelivr": "dist/core-base.global.js",
"types": "dist/core-base.d.ts",
"dependencies": {
"@intlify/devtools-if": "9.1.7",
"@intlify/message-compiler": "9.1.7",
"@intlify/message-resolver": "9.1.7",
"@intlify/runtime": "9.1.7",
"@intlify/shared": "9.1.7",
"@intlify/vue-devtools": "9.1.7"
},
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyCoreBase",
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2021 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,13 @@
# @intlify/devtools-if
The [`@intlify/devtools`](https://github.com/intlify/devtools) interface(I/F:if) for intlify projects
## :warning: NOTE:
This is experimental.
Dont use in production yet.
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,15 @@
/*!
* @intlify/devtools-if v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const IntlifyDevToolsHooks = {
I18nInit: 'i18n:init',
FunctionTranslate: 'function:translate'
};
exports.IntlifyDevToolsHooks = IntlifyDevToolsHooks;
@@ -0,0 +1,15 @@
/*!
* @intlify/devtools-if v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const IntlifyDevToolsHooks = {
I18nInit: 'i18n:init',
FunctionTranslate: 'function:translate'
};
exports.IntlifyDevToolsHooks = IntlifyDevToolsHooks;
@@ -0,0 +1,43 @@
import type { Emittable } from '@intlify/shared';
export declare type AdditionalPayloads = {
meta?: Record<string, unknown>;
};
export declare type IntlifyDevToolsEmitter = Emittable<IntlifyDevToolsEmitterHooks>;
export declare type IntlifyDevToolsEmitterHooks = {
[IntlifyDevToolsHooks.I18nInit]: IntlifyDevToolsHookPayloads[typeof IntlifyDevToolsHooks.I18nInit];
[IntlifyDevToolsHooks.FunctionTranslate]: IntlifyDevToolsHookPayloads[typeof IntlifyDevToolsHooks.FunctionTranslate];
};
export declare type IntlifyDevToolsHookPayloads = {
[IntlifyDevToolsHooks.I18nInit]: {
timestamp: number;
i18n: unknown;
version: string;
} & AdditionalPayloads;
[IntlifyDevToolsHooks.FunctionTranslate]: {
timestamp: number;
message: string | number;
key: string;
locale: string;
format?: string;
} & AdditionalPayloads;
};
export declare const IntlifyDevToolsHooks: {
readonly I18nInit: "i18n:init";
readonly FunctionTranslate: "function:translate";
};
export declare type IntlifyDevToolsHooks = typeof IntlifyDevToolsHooks[keyof typeof IntlifyDevToolsHooks];
export declare interface IntlifyRecord {
id: number;
i18n: unknown;
version: string;
types: Record<string, string | Symbol>;
}
export { }
@@ -0,0 +1,11 @@
/*!
* @intlify/devtools-if v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
const IntlifyDevToolsHooks = {
I18nInit: 'i18n:init',
FunctionTranslate: 'function:translate'
};
export { IntlifyDevToolsHooks };
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/devtools-if.cjs.prod.js')
} else {
module.exports = require('./dist/devtools-if.cjs.js')
}
@@ -0,0 +1,49 @@
{
"name": "@intlify/devtools-if",
"version": "9.1.7",
"description": "@intlify/devtools-if",
"keywords": [
"devtools",
"i18n",
"internationalization",
"intlify"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/devtools-if#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/devtools-if"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/devtools-if.esm-bundler.js",
"types": "dist/devtools-if.d.ts",
"dependencies": {
"@intlify/shared": "9.1.7"
},
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyDevToolsIf",
"formats": [
"esm-bundler",
"cjs"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2020 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
# @intlify/message-compiler
The message compiler for intlify project
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,197 @@
import { RawSourceMap } from 'source-map';
export declare function baseCompile(source: string, options?: CompileOptions): CodeGenResult;
export declare interface CodeGenOptions {
mode?: 'normal' | 'arrow';
breakLineCode?: '\n' | ';';
needIndent?: boolean;
onError?: CompileErrorHandler;
sourceMap?: boolean;
filename?: string;
}
declare interface CodeGenResult {
code: string;
ast: ResourceNode;
map?: RawSourceMap;
}
export declare type CompileCacheKeyHandler = (source: string) => string;
export declare type CompileDomain = 'tokenizer' | 'parser' | 'generator' | 'transformer' | 'compiler';
export declare interface CompileError extends SyntaxError {
code: number;
domain?: CompileDomain;
location?: SourceLocation;
}
export declare const enum CompileErrorCodes {
EXPECTED_TOKEN = 0,
INVALID_TOKEN_IN_PLACEHOLDER = 1,
UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER = 2,
UNKNOWN_ESCAPE_SEQUENCE = 3,
INVALID_UNICODE_ESCAPE_SEQUENCE = 4,
UNBALANCED_CLOSING_BRACE = 5,
UNTERMINATED_CLOSING_BRACE = 6,
EMPTY_PLACEHOLDER = 7,
NOT_ALLOW_NEST_PLACEHOLDER = 8,
INVALID_LINKED_FORMAT = 9,
MUST_HAVE_MESSAGES_IN_PLURAL = 10,
UNEXPECTED_EMPTY_LINKED_MODIFIER = 11,
UNEXPECTED_EMPTY_LINKED_KEY = 12,
UNEXPECTED_LEXICAL_ANALYSIS = 13,
__EXTEND_POINT__ = 14
}
export declare type CompileErrorHandler = (error: CompileError) => void;
export declare type CompileOptions = {
warnHtmlMessage?: boolean;
onCacheKey?: CompileCacheKeyHandler;
} & TransformOptions & CodeGenOptions & ParserOptions & TokenizeOptions;
export declare function createCompileError<T extends number>(code: T, loc: SourceLocation | null, options?: CreateCompileErrorOptions): CompileError;
export declare interface CreateCompileErrorOptions {
domain?: CompileDomain;
messages?: {
[code: number]: string;
};
args?: unknown[];
}
export declare function createLocation(start: Position, end: Position, source?: string): SourceLocation;
export declare function createParser(options?: ParserOptions): Parser;
export declare function createPosition(line: number, column: number, offset: number): Position;
/* Excluded from this release type: defaultOnError */
export declare const ERROR_DOMAIN = "parser";
/* Excluded from this release type: errorMessages */
export declare const enum HelperNameMap {
LIST = "list",
NAMED = "named",
PLURAL = "plural",
LINKED = "linked",
MESSAGE = "message",
TYPE = "type",
INTERPOLATE = "interpolate",
NORMALIZE = "normalize"
}
export declare type Identifier = string;
export declare interface LinkedKeyNode extends Node_2 {
type: NodeTypes.LinkedKey;
value: string;
}
export declare interface LinkedModifierNode extends Node_2 {
type: NodeTypes.LinkedModifier;
value: Identifier;
}
export declare interface LinkedNode extends Node_2 {
type: NodeTypes.Linked;
modifier?: LinkedModifierNode;
key: LinkedKeyNode | NamedNode | ListNode | LiteralNode;
}
export declare interface ListNode extends Node_2 {
type: NodeTypes.List;
index: number;
}
export declare interface LiteralNode extends Node_2 {
type: NodeTypes.Literal;
value: string;
}
export declare const LocationStub: SourceLocation;
declare type MessageElementNode = TextNode | NamedNode | ListNode | LiteralNode | LinkedNode;
export declare interface MessageNode extends Node_2 {
type: NodeTypes.Message;
items: MessageElementNode[];
}
export declare interface NamedNode extends Node_2 {
type: NodeTypes.Named;
key: Identifier;
}
declare interface Node_2 {
type: NodeTypes;
start: number;
end: number;
loc?: SourceLocation;
}
export { Node_2 as Node }
export declare const enum NodeTypes {
Resource = 0,
Plural = 1,
Message = 2,
Text = 3,
Named = 4,
List = 5,
Linked = 6,
LinkedKey = 7,
LinkedModifier = 8,
Literal = 9
}
export declare interface Parser {
parse(source: string): ResourceNode;
}
export declare interface ParserOptions {
location?: boolean;
onError?: CompileErrorHandler;
}
export declare interface PluralNode extends Node_2 {
type: NodeTypes.Plural;
cases: MessageNode[];
}
export declare interface Position {
offset: number;
line: number;
column: number;
}
export declare interface ResourceNode extends Node_2 {
type: NodeTypes.Resource;
body: MessageNode | PluralNode;
helpers?: string[];
}
export declare interface SourceLocation {
start: Position;
end: Position;
source?: string;
}
export declare interface TextNode extends Node_2 {
type: NodeTypes.Text;
value: string;
}
export declare interface TokenizeOptions {
location?: boolean;
onError?: CompileErrorHandler;
}
export declare interface TransformOptions {
onError?: CompileErrorHandler;
}
export { }
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/message-compiler.cjs.prod.js')
} else {
module.exports = require('./dist/message-compiler.cjs.js')
}
@@ -0,0 +1,56 @@
{
"name": "@intlify/message-compiler",
"version": "9.1.7",
"description": "@intlify/message-compiler",
"keywords": [
"compiler",
"i18n",
"internationalization",
"intlify",
"message-format"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/message-compiler#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/message-compiler"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/message-compiler.esm-bundler.js",
"unpkg": "dist/message-compiler.global.js",
"jsdelivr": "dist/message-compiler.global.js",
"types": "dist/message-compiler.d.ts",
"dependencies": {
"@intlify/message-resolver": "9.1.7",
"@intlify/shared": "9.1.7",
"source-map": "0.6.1"
},
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyMessageCompiler",
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2020 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
# @intlify/message-resolver
The locale message resolver for intlify project
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,302 @@
/*!
* @intlify/message-resolver v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
/**
* Transform flat json in obj to normal json in obj
*/
function handleFlatJson(obj) {
// check obj
if (!isObject(obj)) {
return obj;
}
for (const key in obj) {
// check key
if (!hasOwn(obj, key)) {
continue;
}
// handle for normal json
if (!key.includes("." /* DOT */)) {
// recursive process value if value is also a object
if (isObject(obj[key])) {
handleFlatJson(obj[key]);
}
}
// handle for flat json, transform to normal json
else {
// go to the last object
const subKeys = key.split("." /* DOT */);
const lastIndex = subKeys.length - 1;
let currentObj = obj;
for (let i = 0; i < lastIndex; i++) {
if (!(subKeys[i] in currentObj)) {
currentObj[subKeys[i]] = {};
}
currentObj = currentObj[subKeys[i]];
}
// update last object value, delete old property
currentObj[subKeys[lastIndex]] = obj[key];
delete obj[key];
// recursive process value if value is also a object
if (isObject(currentObj[subKeys[lastIndex]])) {
handleFlatJson(currentObj[subKeys[lastIndex]]);
}
}
}
return obj;
}
exports.handleFlatJson = handleFlatJson;
exports.parse = parse;
exports.resolveValue = resolveValue;
@@ -0,0 +1,302 @@
/*!
* @intlify/message-resolver v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
/**
* Transform flat json in obj to normal json in obj
*/
function handleFlatJson(obj) {
// check obj
if (!isObject(obj)) {
return obj;
}
for (const key in obj) {
// check key
if (!hasOwn(obj, key)) {
continue;
}
// handle for normal json
if (!key.includes("." /* DOT */)) {
// recursive process value if value is also a object
if (isObject(obj[key])) {
handleFlatJson(obj[key]);
}
}
// handle for flat json, transform to normal json
else {
// go to the last object
const subKeys = key.split("." /* DOT */);
const lastIndex = subKeys.length - 1;
let currentObj = obj;
for (let i = 0; i < lastIndex; i++) {
if (!(subKeys[i] in currentObj)) {
currentObj[subKeys[i]] = {};
}
currentObj = currentObj[subKeys[i]];
}
// update last object value, delete old property
currentObj[subKeys[lastIndex]] = obj[key];
delete obj[key];
// recursive process value if value is also a object
if (isObject(currentObj[subKeys[lastIndex]])) {
handleFlatJson(currentObj[subKeys[lastIndex]]);
}
}
}
return obj;
}
exports.handleFlatJson = handleFlatJson;
exports.parse = parse;
exports.resolveValue = resolveValue;
@@ -0,0 +1,21 @@
/**
* Transform flat json in obj to normal json in obj
*/
export declare function handleFlatJson(obj: unknown): unknown;
/**
* Parse a string path into an array of segments
*/
export declare function parse(path: Path): string[] | undefined;
/** @VueI18nGeneral */
export declare type Path = string;
export declare type PathValue = string | number | boolean | Function | null | {
[key: string]: PathValue;
} | PathValue[];
export declare function resolveValue(obj: unknown, path: Path): PathValue;
export { }
@@ -0,0 +1,297 @@
/*!
* @intlify/message-resolver v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
/**
* Original Utilities
* written by kazuya kawaguchi
*/
if ((process.env.NODE_ENV !== 'production')) ;
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
/**
* Transform flat json in obj to normal json in obj
*/
function handleFlatJson(obj) {
// check obj
if (!isObject(obj)) {
return obj;
}
for (const key in obj) {
// check key
if (!hasOwn(obj, key)) {
continue;
}
// handle for normal json
if (!key.includes("." /* DOT */)) {
// recursive process value if value is also a object
if (isObject(obj[key])) {
handleFlatJson(obj[key]);
}
}
// handle for flat json, transform to normal json
else {
// go to the last object
const subKeys = key.split("." /* DOT */);
const lastIndex = subKeys.length - 1;
let currentObj = obj;
for (let i = 0; i < lastIndex; i++) {
if (!(subKeys[i] in currentObj)) {
currentObj[subKeys[i]] = {};
}
currentObj = currentObj[subKeys[i]];
}
// update last object value, delete old property
currentObj[subKeys[lastIndex]] = obj[key];
delete obj[key];
// recursive process value if value is also a object
if (isObject(currentObj[subKeys[lastIndex]])) {
handleFlatJson(currentObj[subKeys[lastIndex]]);
}
}
}
return obj;
}
export { handleFlatJson, parse, resolveValue };
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/message-resolver.cjs.prod.js')
} else {
module.exports = require('./dist/message-resolver.cjs.js')
}
@@ -0,0 +1,46 @@
{
"name": "@intlify/message-resolver",
"version": "9.1.7",
"description": "@intlify/message-resolver",
"keywords": [
"i18n",
"internationalization",
"intlify",
"resolver"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/message-resolver#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/message-resolver"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/message-resolver.esm-bundler.js",
"types": "dist/message-resolver.d.ts",
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyMessageResolver",
"formats": [
"esm-bundler",
"cjs"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2020 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
# @intlify/runtime
The runtime for intlify project
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,116 @@
/*!
* @intlify/runtime v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var shared = require('@intlify/shared');
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = shared.toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = shared.isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
? shared.isNumber(options.named.count)
? options.named.count
: shared.isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = shared.isObject(options.pluralRules) &&
shared.isString(locale) &&
shared.isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = shared.isObject(options.pluralRules) &&
shared.isString(locale) &&
shared.isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = shared.isFunction(options.messages)
? options.messages(key)
: shared.isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = shared.isPlainObject(options.processor) &&
shared.isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return shared.isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
exports.createMessageContext = createMessageContext;
@@ -0,0 +1,116 @@
/*!
* @intlify/runtime v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var shared = require('@intlify/shared');
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = shared.toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = shared.isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
? shared.isNumber(options.named.count)
? options.named.count
: shared.isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = shared.isObject(options.pluralRules) &&
shared.isString(locale) &&
shared.isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = shared.isObject(options.pluralRules) &&
shared.isString(locale) &&
shared.isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = shared.isFunction(options.messages)
? options.messages(key)
: shared.isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = shared.isPlainObject(options.processor) &&
shared.isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return shared.isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
exports.createMessageContext = createMessageContext;
@@ -0,0 +1,95 @@
import { Path } from '@intlify/message-resolver';
export declare type CoreMissingType = 'translate' | 'datetime format' | 'number format';
export declare function createMessageContext<T = string, N = {}>(options?: MessageContextOptions<T, N>): MessageContext<T>;
export declare const DEFAULT_MESSAGE_DATA_TYPE = "text";
declare type ExtractToStringFunction<T> = T[ExtractToStringKey<T>];
declare type ExtractToStringKey<T> = Extract<keyof T, 'toString'>;
/** @VueI18nGeneral */
export declare type FallbackLocale = Locale | Locale[] | {
[locale in string]: Locale[];
} | false;
/** @VueI18nGeneral */
export declare type LinkedModifiers<T = string> = {
[key: string]: LinkedModify<T>;
};
export declare type LinkedModify<T = string> = (value: T) => MessageType<T>;
/** @VueI18nGeneral */
export declare type Locale = string;
export declare interface MessageContext<T = string> {
list(index: number): unknown;
named(key: string): unknown;
plural(messages: T[]): T;
linked(key: Path, modifier?: string): MessageType<T>;
message(key: Path): MessageFunction<T>;
type: string;
interpolate: MessageInterpolate<T>;
normalize: MessageNormalize<T>;
}
export declare interface MessageContextOptions<T = string, N = {}> {
parent?: MessageContext<T>;
locale?: string;
list?: unknown[];
named?: NamedValue<N>;
modifiers?: LinkedModifiers<T>;
pluralIndex?: number;
pluralRules?: PluralizationRules;
messages?: MessageFunctions<T> | MessageResolveFunction<T>;
processor?: MessageProcessor<T>;
}
export declare type MessageFunction<T = string> = MessageFunctionCallable | MessageFunctionInternal<T>;
export declare type MessageFunctionCallable = <T = string>(ctx: MessageContext<T>) => MessageType<T>;
export declare type MessageFunctionInternal<T = string> = {
(ctx: MessageContext<T>): MessageType<T>;
key?: string;
locale?: string;
source?: string;
};
export declare type MessageFunctions<T = string> = Record<string, MessageFunction<T>>;
export declare type MessageInterpolate<T = string> = (val: unknown) => MessageType<T>;
export declare type MessageNormalize<T = string> = (values: MessageType<string | T>[]) => MessageType<T | T[]>;
export declare interface MessageProcessor<T = string> {
type?: string;
interpolate?: MessageInterpolate<T>;
normalize?: MessageNormalize<T>;
}
export declare type MessageResolveFunction<T = string> = (key: string) => MessageFunction<T>;
export declare type MessageType<T = string> = T extends string ? string : StringConvertable<T>;
/** @VueI18nGeneral */
export declare type NamedValue<T = {}> = T & Record<string, unknown>;
export declare type PluralizationProps = {
n?: number;
count?: number;
};
export declare type PluralizationRule = (choice: number, choicesLength: number, orgRule?: PluralizationRule) => number;
/** @VueI18nGeneral */
export declare type PluralizationRules = {
[locale: string]: PluralizationRule;
};
declare type StringConvertable<T> = ExtractToStringKey<T> extends never ? unknown : ExtractToStringFunction<T> extends (...args: any) => string ? T : unknown;
export { }
@@ -0,0 +1,111 @@
/*!
* @intlify/runtime v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
import { isNumber, isObject, isString, isFunction, isPlainObject, toDisplayString } from '@intlify/shared';
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
? isNumber(options.named.count)
? options.named.count
: isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = isFunction(options.messages)
? options.messages(key)
: isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = isPlainObject(options.processor) &&
isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = isPlainObject(options.processor) && isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
export { DEFAULT_MESSAGE_DATA_TYPE, createMessageContext };
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/runtime.cjs.prod.js')
} else {
module.exports = require('./dist/runtime.cjs.js')
}
@@ -0,0 +1,51 @@
{
"name": "@intlify/runtime",
"version": "9.1.7",
"description": "@intlify/runtime",
"keywords": [
"i18n",
"internationalization",
"intlify",
"runtime"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/runtime#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/runtime"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/runtime.esm-bundler.js",
"types": "dist/runtime.d.ts",
"dependencies": {
"@intlify/message-compiler": "9.1.7",
"@intlify/message-resolver": "9.1.7",
"@intlify/shared": "9.1.7"
},
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyRuntime",
"formats": [
"esm-bundler",
"cjs"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2020 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
# @intlify/shared
The shared utility package for intlify project
## Forks
The implementation of this module is contains code forked from other packages or projects:
- [@vue/shared](https://github.com/vuejs/vue-next/tree/master/packages/shared)
- Useful Utilities at `utils.ts`
- Author: Evan You
- License: MIT
- Event Emitter at `emitter.ts` and `emittable.ts`
- Author: Jason Miller
- License: MIT
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,222 @@
/*!
* @intlify/shared v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
exports.mark = void 0;
exports.measure = void 0;
{
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
exports.mark = (tag) => perf.mark(tag);
exports.measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
console.warn(`[intlify] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
const assign = Object.assign;
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/* eslint-enable */
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isSymbol = (val) => typeof val === 'symbol';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const isPromise = (val) => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
exports.assign = assign;
exports.createEmitter = createEmitter;
exports.escapeHtml = escapeHtml;
exports.format = format;
exports.friendlyJSONstringify = friendlyJSONstringify;
exports.generateCodeFrame = generateCodeFrame;
exports.generateFormatCacheKey = generateFormatCacheKey;
exports.getGlobalThis = getGlobalThis;
exports.hasOwn = hasOwn;
exports.inBrowser = inBrowser;
exports.isArray = isArray;
exports.isBoolean = isBoolean;
exports.isDate = isDate;
exports.isEmptyObject = isEmptyObject;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isPlainObject = isPlainObject;
exports.isPromise = isPromise;
exports.isRegExp = isRegExp;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.makeSymbol = makeSymbol;
exports.objectToString = objectToString;
exports.toDisplayString = toDisplayString;
exports.toTypeString = toTypeString;
exports.warn = warn;
@@ -0,0 +1,209 @@
/*!
* @intlify/shared v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
console.warn(`[intlify] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
const assign = Object.assign;
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/* eslint-enable */
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isSymbol = (val) => typeof val === 'symbol';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const isPromise = (val) => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
exports.assign = assign;
exports.createEmitter = createEmitter;
exports.escapeHtml = escapeHtml;
exports.format = format;
exports.friendlyJSONstringify = friendlyJSONstringify;
exports.generateCodeFrame = generateCodeFrame;
exports.generateFormatCacheKey = generateFormatCacheKey;
exports.getGlobalThis = getGlobalThis;
exports.hasOwn = hasOwn;
exports.inBrowser = inBrowser;
exports.isArray = isArray;
exports.isBoolean = isBoolean;
exports.isDate = isDate;
exports.isEmptyObject = isEmptyObject;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isPlainObject = isPlainObject;
exports.isPromise = isPromise;
exports.isRegExp = isRegExp;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.makeSymbol = makeSymbol;
exports.mark = mark;
exports.measure = measure;
exports.objectToString = objectToString;
exports.toDisplayString = toDisplayString;
exports.toTypeString = toTypeString;
exports.warn = warn;
@@ -0,0 +1,145 @@
export declare const assign: {
<T, U>(target: T, source: U): T & U;
<T_1, U_1, V>(target: T_1, source1: U_1, source2: V): T_1 & U_1 & V;
<T_2, U_2, V_1, W>(target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W;
(target: object, ...sources: any[]): any;
};
/**
* Create a event emitter
*
* @returns An event emitter
*/
export declare function createEmitter<Events extends Record<EventType, unknown>>(): Emittable<Events>;
/**
* Event emitter interface
*/
export declare interface Emittable<Events extends Record<EventType, unknown> = {}> {
/**
* A map of event names of registered event handlers
*/
events: EventHandlerMap<Events>;
/**
* Register an event handler with the event type
*
* @param event - An {@link EventType}
* @param handler - An {@link EventHandler}, or a {@link WildcardEventHandler} if you are specified "*"
*/
on<Key extends keyof Events>(event: Key | '*', handler: EventHandler<Events[keyof Events]> | WildcardEventHandler<Events>): void;
/**
* Unregister an event handler for the event type
*
* @param event - An {@link EventType}
* @param handler - An {@link EventHandler}, or a {@link WildcardEventHandler} if you are specified "*"
*/
off<Key extends keyof Events>(event: Key | '*', handler: EventHandler<Events[keyof Events]> | WildcardEventHandler<Events>): void;
/**
* Invoke all handlers with the event type
*
* @remarks
* Note Manually firing "*" handlers should be not supported
*
* @param event - An {@link EventType}
* @param payload - An event payload, optional
*/
emit<Key extends keyof Events>(event: Key, payload?: Events[keyof Events]): void;
}
export declare function escapeHtml(rawText: string): string;
/**
* Event handler
*/
export declare type EventHandler<T = unknown> = (payload?: T) => void;
/**
* Event handler list
*/
export declare type EventHandlerList<T = unknown> = Array<EventHandler<T>>;
/**
* Event handler map
*/
export declare type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<keyof Events | '*', EventHandlerList<Events[keyof Events]> | WildcardEventHandlerList<Events>>;
/**
* Event type
*/
export declare type EventType = string | symbol;
export declare function format(message: string, ...args: any): string;
export declare const friendlyJSONstringify: (json: unknown) => string;
export declare function generateCodeFrame(source: string, start?: number, end?: number): string;
export declare const generateFormatCacheKey: (locale: string, key: string, source: string) => string;
export declare const getGlobalThis: () => any;
export declare function hasOwn(obj: object | Array<any>, key: string): boolean;
/**
* Original Utilities
* written by kazuya kawaguchi
*/
export declare const inBrowser: boolean;
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
export declare const isArray: (arg: any) => arg is any[];
export declare const isBoolean: (val: unknown) => val is boolean;
export declare const isDate: (val: unknown) => val is Date;
export declare const isEmptyObject: (val: unknown) => val is boolean;
export declare const isFunction: (val: unknown) => val is Function;
export declare const isNumber: (val: unknown) => val is number;
export declare const isObject: (val: unknown) => val is Record<any, any>;
export declare const isPlainObject: (val: unknown) => val is object;
export declare const isPromise: <T = any>(val: unknown) => val is Promise<T>;
export declare const isRegExp: (val: unknown) => val is RegExp;
export declare const isString: (val: unknown) => val is string;
export declare const isSymbol: (val: unknown) => val is symbol;
export declare const makeSymbol: (name: string) => symbol | string;
export declare let mark: (tag: string) => void | undefined;
export declare let measure: (name: string, startTag: string, endTag: string) => void | undefined;
export declare const objectToString: () => string;
export declare const toDisplayString: (val: unknown) => string;
export declare const toTypeString: (value: unknown) => string;
export declare function warn(msg: string, err?: Error): void;
/**
* Wildcard event handler
*/
export declare type WildcardEventHandler<T = Record<string, unknown>> = (event: keyof T, payload?: T[keyof T]) => void;
/**
* Wildcard event handler list
*/
export declare type WildcardEventHandlerList<T = Record<string, unknown>> = Array<WildcardEventHandler<T>>;
export { }
@@ -0,0 +1,192 @@
/*!
* @intlify/shared v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
if ((process.env.NODE_ENV !== 'production')) {
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
mark = (tag) => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
console.warn(`[intlify] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
const assign = Object.assign;
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/* eslint-enable */
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isSymbol = (val) => typeof val === 'symbol';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const isPromise = (val) => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
export { assign, createEmitter, escapeHtml, format, friendlyJSONstringify, generateCodeFrame, generateFormatCacheKey, getGlobalThis, hasOwn, inBrowser, isArray, isBoolean, isDate, isEmptyObject, isFunction, isNumber, isObject, isPlainObject, isPromise, isRegExp, isString, isSymbol, makeSymbol, mark, measure, objectToString, toDisplayString, toTypeString, warn };
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/shared.cjs.prod.js')
} else {
module.exports = require('./dist/shared.cjs.js')
}
@@ -0,0 +1,46 @@
{
"name": "@intlify/shared",
"version": "9.1.7",
"description": "@intlify/shared",
"keywords": [
"i18n",
"internationalization",
"intlify",
"utitlity"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/shared#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/shared"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/shared.esm-bundler.js",
"types": "dist/shared.d.ts",
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyShared",
"formats": [
"esm-bundler",
"cjs"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2021 kazuya kawaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
# @intlify/vue-devtools
The Vue DevTools I/F package for intlify project
## :copyright: License
[MIT](http://opensource.org/licenses/MIT)
@@ -0,0 +1,24 @@
/*!
* @intlify/vue-devtools v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const VueDevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
};
const VueDevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const VueDevToolsTimelineColors = {
["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
};
exports.VueDevToolsLabels = VueDevToolsLabels;
exports.VueDevToolsPlaceholders = VueDevToolsPlaceholders;
exports.VueDevToolsTimelineColors = VueDevToolsTimelineColors;
@@ -0,0 +1,24 @@
/*!
* @intlify/vue-devtools v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const VueDevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
};
const VueDevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const VueDevToolsTimelineColors = {
["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
};
exports.VueDevToolsLabels = VueDevToolsLabels;
exports.VueDevToolsPlaceholders = VueDevToolsPlaceholders;
exports.VueDevToolsTimelineColors = VueDevToolsTimelineColors;
@@ -0,0 +1,81 @@
import type { CoreMissingType } from '@intlify/runtime';
import type { Emittable } from '@intlify/shared';
import type { Locale } from '@intlify/runtime';
import type { Path } from '@intlify/message-resolver';
import type { PathValue } from '@intlify/message-resolver';
export declare type VueDevToolsEmitter = Emittable<VueDevToolsEmitterEvents>;
export declare type VueDevToolsEmitterEvents = {
[VueDevToolsTimelineEvents.COMPILE_ERROR]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.COMPILE_ERROR];
[VueDevToolsTimelineEvents.MISSING]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.MISSING];
[VueDevToolsTimelineEvents.FALBACK]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.FALBACK];
[VueDevToolsTimelineEvents.MESSAGE_RESOLVE]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.MESSAGE_RESOLVE];
[VueDevToolsTimelineEvents.MESSAGE_COMPILATION]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.MESSAGE_COMPILATION];
[VueDevToolsTimelineEvents.MESSAGE_EVALUATION]: VueDevToolsTimelineEventPayloads[VueDevToolsTimelineEvents.MESSAGE_EVALUATION];
};
export declare const enum VueDevToolsIDs {
PLUGIN = "vue-devtools-plugin-vue-i18n",
CUSTOM_INSPECTOR = "vue-i18n-resource-inspector",
TIMELINE = "vue-i18n-timeline"
}
export declare const VueDevToolsLabels: Record<string, string>;
export declare const VueDevToolsPlaceholders: Record<string, string>;
export declare const VueDevToolsTimelineColors: Record<string, number>;
export declare type VueDevToolsTimelineEventPayloads = {
[VueDevToolsTimelineEvents.COMPILE_ERROR]: {
message: PathValue;
error: string;
start?: number;
end?: number;
groupId?: string;
};
[VueDevToolsTimelineEvents.MISSING]: {
locale: Locale;
key: Path;
type: CoreMissingType;
groupId?: string;
};
[VueDevToolsTimelineEvents.FALBACK]: {
key: Path;
type: CoreMissingType;
from?: Locale;
to: Locale | 'global';
groupId?: string;
};
[VueDevToolsTimelineEvents.MESSAGE_RESOLVE]: {
type: VueDevToolsTimelineEvents.MESSAGE_RESOLVE;
key: Path;
message: PathValue;
time: number;
groupId?: string;
};
[VueDevToolsTimelineEvents.MESSAGE_COMPILATION]: {
type: VueDevToolsTimelineEvents.MESSAGE_COMPILATION;
message: PathValue;
time: number;
groupId?: string;
};
[VueDevToolsTimelineEvents.MESSAGE_EVALUATION]: {
type: VueDevToolsTimelineEvents.MESSAGE_EVALUATION;
value: unknown;
time: number;
groupId?: string;
};
};
export declare const enum VueDevToolsTimelineEvents {
COMPILE_ERROR = "compile-error",
MISSING = "missing",
FALBACK = "fallback",
MESSAGE_RESOLVE = "message-resolve",
MESSAGE_COMPILATION = "message-compilation",
MESSAGE_EVALUATION = "message-evaluation"
}
export { }
@@ -0,0 +1,18 @@
/*!
* @intlify/vue-devtools v9.1.7
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
const VueDevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
};
const VueDevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const VueDevToolsTimelineColors = {
["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
};
export { VueDevToolsLabels, VueDevToolsPlaceholders, VueDevToolsTimelineColors };
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/vue-devtools.cjs.prod.js')
} else {
module.exports = require('./dist/vue-devtools.cjs.js')
}
@@ -0,0 +1,51 @@
{
"name": "@intlify/vue-devtools",
"version": "9.1.7",
"description": "@intlify/vue-devtools",
"keywords": [
"i18n",
"internationalization",
"intlify",
"vue-devtools"
],
"license": "MIT",
"author": {
"name": "kazuya kawaguchi",
"email": "kawakazu80@gmail.com"
},
"homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/vue-devtools#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/intlify/vue-i18n-next.git",
"directory": "packages/vue-devtools"
},
"bugs": {
"url": "https://github.com/intlify/vue-i18n-next/issues"
},
"files": [
"index.js",
"dist"
],
"main": "index.js",
"module": "dist/vue-devtools.esm-bundler.js",
"types": "dist/vue-devtools.d.ts",
"dependencies": {
"@intlify/message-resolver": "9.1.7",
"@intlify/runtime": "9.1.7",
"@intlify/shared": "9.1.7"
},
"engines": {
"node": ">= 10"
},
"buildOptions": {
"name": "IntlifyVueDevtools",
"formats": [
"esm-bundler",
"cjs"
]
},
"publishConfig": {
"access": "public"
},
"sideEffects": false
}
@@ -0,0 +1,90 @@
import { ComponentBounds, Hookable } from './hooks';
import { Context } from './context';
import { ComponentInstance, ComponentState, StateBase } from './component';
import { App } from './app';
import { ID } from './util';
export interface DevtoolsPluginApi {
on: Hookable<Context>;
notifyComponentUpdate(instance?: ComponentInstance): any;
addTimelineLayer(options: TimelineLayerOptions): any;
addTimelineEvent(options: TimelineEventOptions): any;
addInspector(options: CustomInspectorOptions): any;
sendInspectorTree(inspectorId: string): any;
sendInspectorState(inspectorId: string): any;
selectInspectorNode(inspectorId: string, nodeId: string): any;
getComponentBounds(instance: ComponentInstance): Promise<ComponentBounds>;
getComponentName(instance: ComponentInstance): Promise<string>;
getComponentInstances(app: App): Promise<ComponentInstance[]>;
highlightElement(instance: ComponentInstance): any;
unhighlightElement(): any;
}
export interface AppRecord {
id: number;
name: string;
instanceMap: Map<string, ComponentInstance>;
rootInstance: ComponentInstance;
}
export interface TimelineLayerOptions<TData = any, TMeta = any> {
id: string;
label: string;
color: number;
skipScreenshots?: boolean;
groupsOnly?: boolean;
ignoreNoDurationGroups?: boolean;
screenshotOverlayRender?: (event: TimelineEvent<TData, TMeta> & ScreenshotOverlayEvent, ctx: ScreenshotOverlayRenderContext) => ScreenshotOverlayRenderResult | Promise<ScreenshotOverlayRenderResult>;
}
export interface ScreenshotOverlayEvent {
layerId: string;
renderMeta: any;
}
export interface ScreenshotOverlayRenderContext<TData = any, TMeta = any> {
screenshot: ScreenshotData;
events: (TimelineEvent<TData, TMeta> & ScreenshotOverlayEvent)[];
index: number;
}
export declare type ScreenshotOverlayRenderResult = HTMLElement | string | false;
export interface ScreenshotData {
time: number;
}
export interface TimelineEventOptions {
layerId: string;
event: TimelineEvent;
all?: boolean;
}
export interface TimelineEvent<TData = any, TMeta = any> {
time: number;
data: TData;
logType?: 'default' | 'warning' | 'error';
meta?: TMeta;
groupId?: ID;
title?: string;
subtitle?: string;
}
export interface CustomInspectorOptions {
id: string;
label: string;
icon?: string;
treeFilterPlaceholder?: string;
stateFilterPlaceholder?: string;
noSelectionText?: string;
actions?: {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[];
}
export interface CustomInspectorNode {
id: string;
label: string;
children?: CustomInspectorNode[];
tags?: InspectorNodeTag[];
}
export interface InspectorNodeTag {
label: string;
textColor: number;
backgroundColor: number;
tooltip?: string;
}
export interface CustomInspectorState {
[key: string]: (StateBase | Omit<ComponentState, 'type'>)[];
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
export declare type App = any;
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,76 @@
import { InspectorNodeTag } from './api';
import { ID } from './util';
export declare type ComponentInstance = any;
export interface ComponentTreeNode {
uid: ID;
id: string;
name: string;
renderKey: string | number;
inactive: boolean;
isFragment: boolean;
hasChildren: boolean;
children: ComponentTreeNode[];
positionTop?: number;
consoleId?: string;
isRouterView?: boolean;
macthedRouteSegment?: string;
tags: InspectorNodeTag[];
meta?: any;
}
export interface InspectedComponentData {
id: string;
name: string;
file: string;
state: ComponentState[];
functional?: boolean;
}
export interface StateBase {
key: string;
value: any;
editable?: boolean;
objectType?: 'ref' | 'reactive' | 'computed' | 'other';
raw?: string;
}
export interface ComponentStateBase extends StateBase {
type: string;
}
export interface ComponentPropState extends ComponentStateBase {
meta?: {
type: string;
required: boolean;
/** Vue 1 only */
mode?: 'default' | 'sync' | 'once';
};
}
export declare type ComponentBuiltinCustomStateTypes = 'function' | 'map' | 'set' | 'reference' | 'component' | 'component-definition' | 'router' | 'store';
export interface ComponentCustomState extends ComponentStateBase {
value: CustomState;
}
export declare type CustomState = {
_custom: {
type: ComponentBuiltinCustomStateTypes | string;
display?: string;
tooltip?: string;
value?: any;
abstract?: boolean;
file?: string;
uid?: number;
readOnly?: boolean;
/** Configure immediate child fields */
fields?: {
abstract?: boolean;
};
id?: any;
actions?: {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[];
/** internal */
_reviveId?: number;
};
};
export declare type ComponentState = ComponentStateBase | ComponentPropState | ComponentCustomState;
export interface ComponentDevtoolsOptions {
hide?: boolean;
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
import { AppRecord } from './api';
export interface Context {
currentTab: string;
currentAppRecord: AppRecord;
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,169 @@
import { ComponentTreeNode, InspectedComponentData, ComponentInstance, ComponentDevtoolsOptions } from './component';
import { App } from './app';
import { CustomInspectorNode, CustomInspectorState, TimelineEvent } from './api';
export declare const enum Hooks {
TRANSFORM_CALL = "transformCall",
GET_APP_RECORD_NAME = "getAppRecordName",
GET_APP_ROOT_INSTANCE = "getAppRootInstance",
REGISTER_APPLICATION = "registerApplication",
WALK_COMPONENT_TREE = "walkComponentTree",
VISIT_COMPONENT_TREE = "visitComponentTree",
WALK_COMPONENT_PARENTS = "walkComponentParents",
INSPECT_COMPONENT = "inspectComponent",
GET_COMPONENT_BOUNDS = "getComponentBounds",
GET_COMPONENT_NAME = "getComponentName",
GET_COMPONENT_INSTANCES = "getComponentInstances",
GET_ELEMENT_COMPONENT = "getElementComponent",
GET_COMPONENT_ROOT_ELEMENTS = "getComponentRootElements",
EDIT_COMPONENT_STATE = "editComponentState",
GET_COMPONENT_DEVTOOLS_OPTIONS = "getAppDevtoolsOptions",
GET_COMPONENT_RENDER_CODE = "getComponentRenderCode",
INSPECT_TIMELINE_EVENT = "inspectTimelineEvent",
TIMELINE_CLEARED = "timelineCleared",
GET_INSPECTOR_TREE = "getInspectorTree",
GET_INSPECTOR_STATE = "getInspectorState",
EDIT_INSPECTOR_STATE = "editInspectorState"
}
export interface ComponentBounds {
left: number;
top: number;
width: number;
height: number;
}
export declare type HookPayloads = {
[Hooks.TRANSFORM_CALL]: {
callName: string;
inArgs: any[];
outArgs: any[];
};
[Hooks.GET_APP_RECORD_NAME]: {
app: App;
name: string;
};
[Hooks.GET_APP_ROOT_INSTANCE]: {
app: App;
root: ComponentInstance;
};
[Hooks.REGISTER_APPLICATION]: {
app: App;
};
[Hooks.WALK_COMPONENT_TREE]: {
componentInstance: ComponentInstance;
componentTreeData: ComponentTreeNode[];
maxDepth: number;
filter: string;
};
[Hooks.VISIT_COMPONENT_TREE]: {
app: App;
componentInstance: ComponentInstance;
treeNode: ComponentTreeNode;
filter: string;
};
[Hooks.WALK_COMPONENT_PARENTS]: {
componentInstance: ComponentInstance;
parentInstances: ComponentInstance[];
};
[Hooks.INSPECT_COMPONENT]: {
app: App;
componentInstance: ComponentInstance;
instanceData: InspectedComponentData;
};
[Hooks.GET_COMPONENT_BOUNDS]: {
componentInstance: ComponentInstance;
bounds: ComponentBounds;
};
[Hooks.GET_COMPONENT_NAME]: {
componentInstance: ComponentInstance;
name: string;
};
[Hooks.GET_COMPONENT_INSTANCES]: {
app: App;
componentInstances: ComponentInstance[];
};
[Hooks.GET_ELEMENT_COMPONENT]: {
element: HTMLElement | any;
componentInstance: ComponentInstance;
};
[Hooks.GET_COMPONENT_ROOT_ELEMENTS]: {
componentInstance: ComponentInstance;
rootElements: (HTMLElement | any)[];
};
[Hooks.EDIT_COMPONENT_STATE]: {
app: App;
componentInstance: ComponentInstance;
path: string[];
type: string;
state: EditStatePayload;
set: (object: any, path: string | (string[]), value: any, cb?: (object: any, field: string, value: any) => void) => void;
};
[Hooks.GET_COMPONENT_DEVTOOLS_OPTIONS]: {
componentInstance: ComponentInstance;
options: ComponentDevtoolsOptions;
};
[Hooks.GET_COMPONENT_RENDER_CODE]: {
componentInstance: ComponentInstance;
code: string;
};
[Hooks.INSPECT_TIMELINE_EVENT]: {
app: App;
layerId: string;
event: TimelineEvent;
all?: boolean;
data: any;
};
[Hooks.TIMELINE_CLEARED]: Record<string, never>;
[Hooks.GET_INSPECTOR_TREE]: {
app: App;
inspectorId: string;
filter: string;
rootNodes: CustomInspectorNode[];
};
[Hooks.GET_INSPECTOR_STATE]: {
app: App;
inspectorId: string;
nodeId: string;
state: CustomInspectorState;
};
[Hooks.EDIT_INSPECTOR_STATE]: {
app: App;
inspectorId: string;
nodeId: string;
path: string[];
type: string;
state: EditStatePayload;
set: (object: any, path: string | (string[]), value: any, cb?: (object: any, field: string, value: any) => void) => void;
};
};
export declare type EditStatePayload = {
value: any;
newKey?: string | null;
remove?: undefined | false;
} | {
value?: undefined;
newKey?: undefined;
remove: true;
};
export declare type HookHandler<TPayload, TContext> = (payload: TPayload, ctx: TContext) => void | Promise<void>;
export interface Hookable<TContext> {
transformCall(handler: HookHandler<HookPayloads[Hooks.TRANSFORM_CALL], TContext>): any;
getAppRecordName(handler: HookHandler<HookPayloads[Hooks.GET_APP_RECORD_NAME], TContext>): any;
getAppRootInstance(handler: HookHandler<HookPayloads[Hooks.GET_APP_ROOT_INSTANCE], TContext>): any;
registerApplication(handler: HookHandler<HookPayloads[Hooks.REGISTER_APPLICATION], TContext>): any;
walkComponentTree(handler: HookHandler<HookPayloads[Hooks.WALK_COMPONENT_TREE], TContext>): any;
visitComponentTree(handler: HookHandler<HookPayloads[Hooks.VISIT_COMPONENT_TREE], TContext>): any;
walkComponentParents(handler: HookHandler<HookPayloads[Hooks.WALK_COMPONENT_PARENTS], TContext>): any;
inspectComponent(handler: HookHandler<HookPayloads[Hooks.INSPECT_COMPONENT], TContext>): any;
getComponentBounds(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_BOUNDS], TContext>): any;
getComponentName(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_NAME], TContext>): any;
getComponentInstances(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_INSTANCES], TContext>): any;
getElementComponent(handler: HookHandler<HookPayloads[Hooks.GET_ELEMENT_COMPONENT], TContext>): any;
getComponentRootElements(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_ROOT_ELEMENTS], TContext>): any;
editComponentState(handler: HookHandler<HookPayloads[Hooks.EDIT_COMPONENT_STATE], TContext>): any;
getComponentDevtoolsOptions(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_DEVTOOLS_OPTIONS], TContext>): any;
getComponentRenderCode(handler: HookHandler<HookPayloads[Hooks.GET_COMPONENT_RENDER_CODE], TContext>): any;
inspectTimelineEvent(handler: HookHandler<HookPayloads[Hooks.INSPECT_TIMELINE_EVENT], TContext>): any;
timelineCleared(handler: HookHandler<HookPayloads[Hooks.TIMELINE_CLEARED], TContext>): any;
getInspectorTree(handler: HookHandler<HookPayloads[Hooks.GET_INSPECTOR_TREE], TContext>): any;
getInspectorState(handler: HookHandler<HookPayloads[Hooks.GET_INSPECTOR_STATE], TContext>): any;
editInspectorState(handler: HookHandler<HookPayloads[Hooks.EDIT_INSPECTOR_STATE], TContext>): any;
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,6 @@
export * from './api';
export * from './app';
export * from './component';
export * from './context';
export * from './hooks';
export * from './util';
@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./api"), exports);
__exportStar(require("./app"), exports);
__exportStar(require("./component"), exports);
__exportStar(require("./context"), exports);
__exportStar(require("./hooks"), exports);
__exportStar(require("./util"), exports);
@@ -0,0 +1,4 @@
export declare type ID = number | string;
export interface WithId {
id: ID;
}
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
export declare const HOOK_SETUP = "devtools-plugin:setup";
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HOOK_SETUP = void 0;
exports.HOOK_SETUP = 'devtools-plugin:setup';
@@ -0,0 +1,10 @@
import { PluginDescriptor, SetupFunction } from '.';
interface GlobalTarget {
__VUE_DEVTOOLS_PLUGINS__: Array<{
pluginDescriptor: PluginDescriptor;
setupFn: SetupFunction;
}>;
}
export declare function getDevtoolsGlobalHook(): any;
export declare function getTarget(): GlobalTarget;
export {};
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTarget = exports.getDevtoolsGlobalHook = void 0;
function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
exports.getDevtoolsGlobalHook = getDevtoolsGlobalHook;
function getTarget() {
// @ts-ignore
return typeof navigator !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
}
exports.getTarget = getTarget;
@@ -0,0 +1,14 @@
import { DevtoolsPluginApi, App } from './api';
export * from './api';
export interface PluginDescriptor {
id: string;
label: string;
app: App;
packageName?: string;
homepage?: string;
componentStateTypes?: string[];
logo?: string;
disableAppScope?: boolean;
}
export declare type SetupFunction = (api: DevtoolsPluginApi) => void;
export declare function setupDevtoolsPlugin(pluginDescriptor: PluginDescriptor, setupFn: SetupFunction): void;
@@ -0,0 +1,31 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
const env_1 = require("./env");
const const_1 = require("./const");
__exportStar(require("./api"), exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const hook = env_1.getDevtoolsGlobalHook();
if (hook) {
hook.emit(const_1.HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const target = env_1.getTarget();
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
@@ -0,0 +1,6 @@
export * from './api';
export * from './app';
export * from './component';
export * from './context';
export * from './hooks';
export * from './util';
@@ -0,0 +1 @@
export const HOOK_SETUP = 'devtools-plugin:setup';
@@ -0,0 +1,11 @@
export function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
export function getTarget() {
// @ts-ignore
return typeof navigator !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
}
@@ -0,0 +1,17 @@
import { getTarget, getDevtoolsGlobalHook } from './env';
import { HOOK_SETUP } from './const';
export * from './api';
export function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const hook = getDevtoolsGlobalHook();
if (hook) {
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const target = getTarget();
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
@@ -0,0 +1,38 @@
{
"name": "@vue/devtools-api",
"version": "6.0.0-beta.15",
"description": "Interact with the Vue devtools from the page",
"main": "lib/cjs/index.js",
"browser": "lib/esm/index.js",
"module": "lib/esm/index.js",
"types": "lib/cjs/index.d.ts",
"sideEffects": false,
"author": {
"name": "Guillaume Chau"
},
"files": [
"lib/esm",
"lib/cjs"
],
"license": "MIT",
"repository": {
"url": "https://github.com/vuejs/vue-devtools.git",
"type": "git",
"directory": "packages/api"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rimraf lib && yarn build:esm && yarn build:cjs",
"build:esm": "tsc --module es2015 --outDir lib/esm",
"build:cjs": "tsc --module commonjs --outDir lib/cjs -d",
"build:watch": "yarn tsc --module commonjs --outDir lib/cjs -d -w --sourceMap",
"ts": "yarn build:esm"
},
"devDependencies": {
"@types/node": "^13.9.1",
"@types/webpack-env": "^1.15.1",
"typescript": "^3.8.3"
}
}
@@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.
@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,742 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More