diff --git a/.eslintignore b/.eslintignore index 6e60e948f3ededf496c04327eec227581580b24f..aea9a83fbeec9549ee693c9f2501c31d8649ef3d 100644 --- a/.eslintignore +++ b/.eslintignore @@ -19,6 +19,8 @@ packages/*/packages/mpvue packages/*/packages/mpvue-page-factory packages/*/packages/mpvue-template-compiler packages/*/packages/postcss-normalize-whitespace +packages/*/packages/uni-app +packages/*/packages/uni-stat packages/*/packages/uni-cloud packages/*/packages/vue-loader packages/*/packages/vue-template-compiler diff --git a/.gitignore b/.gitignore index 299b62f12079c909af718a3ef3a3f8969ab8f2f3..c8bd55941fae4bccca6a7c974d9a4a5869264784 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ unpackage/ .DS_Store !packages/uni-app-plus/dist package-lock.json +!packages/vue-cli-plugin-uni/packages/**/* diff --git a/packages/uni-mp-alipay/dist/uni.api.esm.js b/packages/uni-mp-alipay/dist/uni.api.esm.js index 70ac01eb5b6a2fc3756884de936444a51d11d4ad..cbee7b1c7791b415f9731daab3a502b5f3a2b751 100644 --- a/packages/uni-mp-alipay/dist/uni.api.esm.js +++ b/packages/uni-mp-alipay/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +my.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + my.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return my.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -882,14 +896,14 @@ function createIntersectionObserver(component, options) { } var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider, - setStorageSync: setStorageSync, - getStorageSync: getStorageSync, - removeStorageSync: removeStorageSync, - startGyroscope: startGyroscope, - createSelectorQuery: createSelectorQuery, - createIntersectionObserver: createIntersectionObserver + __proto__: null, + getProvider: getProvider, + setStorageSync: setStorageSync, + getStorageSync: getStorageSync, + removeStorageSync: removeStorageSync, + startGyroscope: startGyroscope, + createSelectorQuery: createSelectorQuery, + createIntersectionObserver: createIntersectionObserver }); function handleNetworkInfo(fromRes, toRes) { @@ -1315,58 +1329,58 @@ const chooseAddress = { }; var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - returnValue: returnValue, - request: request, - setNavigationBarColor: setNavigationBarColor, - setNavigationBarTitle: setNavigationBarTitle, - showModal: showModal, - showToast: showToast, - showActionSheet: showActionSheet, - showLoading: showLoading, - uploadFile: uploadFile, - downloadFile: downloadFile, - getFileInfo: getFileInfo, - compressImage: compressImage, - chooseVideo: chooseVideo, - connectSocket: connectSocket, - chooseImage: chooseImage, - previewImage: previewImage, - saveFile: saveFile, - getSavedFileInfo: getSavedFileInfo, - getSavedFileList: getSavedFileList, - removeSavedFile: removeSavedFile, - getLocation: getLocation, - openLocation: openLocation, - getNetworkType: getNetworkType, - onNetworkStatusChange: onNetworkStatusChange, - stopAccelerometer: stopAccelerometer, - stopCompass: stopCompass, - scanCode: scanCode, - setClipboardData: setClipboardData, - getClipboardData: getClipboardData, - pageScrollTo: pageScrollTo, - login: login, - getUserInfo: getUserInfo, - requestPayment: requestPayment, - getBLEDeviceServices: getBLEDeviceServices, - createBLEConnection: createBLEConnection, - closeBLEConnection: closeBLEConnection, - onBLEConnectionStateChange: onBLEConnectionStateChange, - makePhoneCall: makePhoneCall, - stopGyroscope: stopGyroscope, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync, - canvasToTempFilePath: canvasToTempFilePath, - setScreenBrightness: setScreenBrightness, - getScreenBrightness: getScreenBrightness, - showShareMenu: showShareMenu, - hideHomeButton: hideHomeButton, - saveImageToPhotosAlbum: saveImageToPhotosAlbum, - saveVideoToPhotosAlbum: saveVideoToPhotosAlbum, - chooseAddress: chooseAddress, - redirectTo: redirectTo, - navigateTo: navigateTo + __proto__: null, + returnValue: returnValue, + request: request, + setNavigationBarColor: setNavigationBarColor, + setNavigationBarTitle: setNavigationBarTitle, + showModal: showModal, + showToast: showToast, + showActionSheet: showActionSheet, + showLoading: showLoading, + uploadFile: uploadFile, + downloadFile: downloadFile, + getFileInfo: getFileInfo, + compressImage: compressImage, + chooseVideo: chooseVideo, + connectSocket: connectSocket, + chooseImage: chooseImage, + previewImage: previewImage, + saveFile: saveFile, + getSavedFileInfo: getSavedFileInfo, + getSavedFileList: getSavedFileList, + removeSavedFile: removeSavedFile, + getLocation: getLocation, + openLocation: openLocation, + getNetworkType: getNetworkType, + onNetworkStatusChange: onNetworkStatusChange, + stopAccelerometer: stopAccelerometer, + stopCompass: stopCompass, + scanCode: scanCode, + setClipboardData: setClipboardData, + getClipboardData: getClipboardData, + pageScrollTo: pageScrollTo, + login: login, + getUserInfo: getUserInfo, + requestPayment: requestPayment, + getBLEDeviceServices: getBLEDeviceServices, + createBLEConnection: createBLEConnection, + closeBLEConnection: closeBLEConnection, + onBLEConnectionStateChange: onBLEConnectionStateChange, + makePhoneCall: makePhoneCall, + stopGyroscope: stopGyroscope, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync, + canvasToTempFilePath: canvasToTempFilePath, + setScreenBrightness: setScreenBrightness, + getScreenBrightness: getScreenBrightness, + showShareMenu: showShareMenu, + hideHomeButton: hideHomeButton, + saveImageToPhotosAlbum: saveImageToPhotosAlbum, + saveVideoToPhotosAlbum: saveVideoToPhotosAlbum, + chooseAddress: chooseAddress, + redirectTo: redirectTo, + navigateTo: navigateTo }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-alipay/dist/uni.mp.esm.js b/packages/uni-mp-alipay/dist/uni.mp.esm.js index 3f22d256170fd544f8f52ba6baf2f7387d085922..a04f9acf31ce9e3a510bc1d0db42757cc7d7fb36 100644 --- a/packages/uni-mp-alipay/dist/uni.mp.esm.js +++ b/packages/uni-mp-alipay/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, isArray, extend, hyphenate, isObject, hasOwn, toNumber, capitalize, isFunction, NOOP, EMPTY_OBJ, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -476,7 +476,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -542,6 +542,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook(mpOptions, hook, excludes)); } +my.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + my.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -566,8 +573,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-mp-baidu/dist/uni.api.esm.js b/packages/uni-mp-baidu/dist/uni.api.esm.js index eb8b2d96185c84f1804493d29d62fe5061b428c0..d60c8db10911e460a176cdefa0cf33a1b63005d3 100644 --- a/packages/uni-mp-baidu/dist/uni.api.esm.js +++ b/packages/uni-mp-baidu/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +swan.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + swan.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return swan.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -847,9 +861,9 @@ function requestPayment(params) { } var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider, - requestPayment: requestPayment + __proto__: null, + getProvider: getProvider, + requestPayment: requestPayment }); function createTodoMethod(contextName, methodName) { @@ -922,21 +936,21 @@ const getAccountInfoSync = { }; var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - request: request, - connectSocket: connectSocket, - getRecorderManager: getRecorderManager, - getBackgroundAudioManager: getBackgroundAudioManager, - scanCode: scanCode, - navigateToMiniProgram: navigateToMiniProgram, - navigateBackMiniProgram: navigateBackMiniProgram, - showShareMenu: showShareMenu, - getAccountInfoSync: getAccountInfoSync, - redirectTo: redirectTo, - navigateTo: navigateTo, - previewImage: previewImage, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync + __proto__: null, + request: request, + connectSocket: connectSocket, + getRecorderManager: getRecorderManager, + getBackgroundAudioManager: getBackgroundAudioManager, + scanCode: scanCode, + navigateToMiniProgram: navigateToMiniProgram, + navigateBackMiniProgram: navigateBackMiniProgram, + showShareMenu: showShareMenu, + getAccountInfoSync: getAccountInfoSync, + redirectTo: redirectTo, + navigateTo: navigateTo, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-baidu/dist/uni.mp.esm.js b/packages/uni-mp-baidu/dist/uni.mp.esm.js index 20a90cbce4d924830fb3331837879321022370eb..5b473541558e1131871df23c700e7f614dae98f2 100644 --- a/packages/uni-mp-baidu/dist/uni.mp.esm.js +++ b/packages/uni-mp-baidu/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -501,7 +501,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -567,6 +567,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +swan.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + swan.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -591,8 +598,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-mp-kuaishou/dist/uni.api.esm.js b/packages/uni-mp-kuaishou/dist/uni.api.esm.js index a1d2da6ccb1188e0738edc5b2f45dbfb661b0cc3..a71abe19788af49d6b83156ca0e48259ae6d5bfe 100644 --- a/packages/uni-mp-kuaishou/dist/uni.api.esm.js +++ b/packages/uni-mp-kuaishou/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +ks.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + ks.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return ks.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -827,17 +841,17 @@ const getProvider = initGetProvider({ }); var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider + __proto__: null, + getProvider: getProvider }); var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - redirectTo: redirectTo, - navigateTo: navigateTo, - previewImage: previewImage, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync + __proto__: null, + redirectTo: redirectTo, + navigateTo: navigateTo, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-kuaishou/dist/uni.mp.esm.js b/packages/uni-mp-kuaishou/dist/uni.mp.esm.js index b1d3f97766cce8a8ff66658f731a724f23621796..860f9bf9a464c76be791b18c482d08f5d0116950 100644 --- a/packages/uni-mp-kuaishou/dist/uni.mp.esm.js +++ b/packages/uni-mp-kuaishou/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -501,7 +501,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -567,6 +567,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +ks.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + ks.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -591,8 +598,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-mp-qq/dist/uni.api.esm.js b/packages/uni-mp-qq/dist/uni.api.esm.js index 3a0dc8318edf0a97ddf500e0be10bcb00acab26c..6ee33ac8fabbf3bfbc3b7018e0193af230522a1e 100644 --- a/packages/uni-mp-qq/dist/uni.api.esm.js +++ b/packages/uni-mp-qq/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +qq.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + qq.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return qq.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -827,17 +841,17 @@ const getProvider = initGetProvider({ }); var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider + __proto__: null, + getProvider: getProvider }); var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - redirectTo: redirectTo, - navigateTo: navigateTo, - previewImage: previewImage, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync + __proto__: null, + redirectTo: redirectTo, + navigateTo: navigateTo, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-qq/dist/uni.mp.esm.js b/packages/uni-mp-qq/dist/uni.mp.esm.js index 05f4361200c710eb0487391164e813defabf82e9..ea73fc1e344f37b13cbe0e2c3772d257b0b5d7a5 100644 --- a/packages/uni-mp-qq/dist/uni.mp.esm.js +++ b/packages/uni-mp-qq/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -501,7 +501,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -567,6 +567,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +qq.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + qq.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -591,8 +598,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-mp-toutiao/dist/uni.api.esm.js b/packages/uni-mp-toutiao/dist/uni.api.esm.js index 1641db8f3c4e7b6ca76970a3effb1e5bf4482c15..758ac002d89bcab69f3aa9d501b5a8626c7f1ef9 100644 --- a/packages/uni-mp-toutiao/dist/uni.api.esm.js +++ b/packages/uni-mp-toutiao/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +tt.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + tt.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return tt.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -809,8 +823,8 @@ const getProvider = initGetProvider({ }); var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider + __proto__: null, + getProvider: getProvider }); const chooseImage = { @@ -886,23 +900,23 @@ const getFileInfo = { }; var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - chooseImage: chooseImage, - connectSocket: connectSocket, - chooseVideo: chooseVideo, - scanCode: scanCode, - startAccelerometer: startAccelerometer, - showToast: showToast, - showLoading: showLoading, - showModal: showModal, - showActionSheet: showActionSheet, - login: login, - getUserInfo: getUserInfo, - requestPayment: requestPayment, - getFileInfo: getFileInfo, - redirectTo: redirectTo, - navigateTo: navigateTo, - previewImage: previewImage + __proto__: null, + chooseImage: chooseImage, + connectSocket: connectSocket, + chooseVideo: chooseVideo, + scanCode: scanCode, + startAccelerometer: startAccelerometer, + showToast: showToast, + showLoading: showLoading, + showModal: showModal, + showActionSheet: showActionSheet, + login: login, + getUserInfo: getUserInfo, + requestPayment: requestPayment, + getFileInfo: getFileInfo, + redirectTo: redirectTo, + navigateTo: navigateTo, + previewImage: previewImage }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-toutiao/dist/uni.mp.esm.js b/packages/uni-mp-toutiao/dist/uni.mp.esm.js index fa129fc15188e0e50e3d40896a7c6fe4cb2d4a35..c8cc1366d384df7113c9316b77649037496e8d66 100644 --- a/packages/uni-mp-toutiao/dist/uni.mp.esm.js +++ b/packages/uni-mp-toutiao/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -501,7 +501,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -570,6 +570,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +tt.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + tt.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -594,8 +601,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-mp-weixin/dist/uni.api.esm.js b/packages/uni-mp-weixin/dist/uni.api.esm.js index efaf972f558b49a7597439f8744a17a04eeabf97..429473fb040a1e6b930bd3cb0bbfc7143eed0ccc 100644 --- a/packages/uni-mp-weixin/dist/uni.api.esm.js +++ b/packages/uni-mp-weixin/dist/uni.api.esm.js @@ -1,4 +1,17 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; + +wx.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + wx.appLaunchHooks.push(hook); +} function getBaseSystemInfo() { return wx.getSystemInfoSync() @@ -686,6 +699,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -791,16 +805,16 @@ const getProvider = initGetProvider({ }); var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider + __proto__: null, + getProvider: getProvider }); var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - redirectTo: redirectTo, - previewImage: previewImage, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync + __proto__: null, + redirectTo: redirectTo, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync }); var index = initUni(shims, protocols); diff --git a/packages/uni-mp-weixin/dist/uni.mp.esm.js b/packages/uni-mp-weixin/dist/uni.mp.esm.js index 161e4e76862cdbf1f309394c56cc06736a668d9d..e0ecaf6650cc4334d0ee4709b14c68d2b546e6ed 100644 --- a/packages/uni-mp-weixin/dist/uni.mp.esm.js +++ b/packages/uni-mp-weixin/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; -import { onUnmounted } from 'vue'; +import { onUnmounted, injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -447,7 +447,7 @@ function initScopedSlotsParams(instance) { const vueIds = instance.attrs.vueId; if (vueIds) { const vueId = vueIds.split(',')[0]; - const object = center[vueId] = center[vueId] || {}; + const object = (center[vueId] = center[vueId] || {}); object[name] = value; if (parents[vueId]) { parents[vueId].$forceUpdate(); @@ -513,6 +513,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +wx.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + wx.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -537,8 +544,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/uni-quickapp-webview/dist/uni.api.esm.js b/packages/uni-quickapp-webview/dist/uni.api.esm.js index 986602cc8d03cce8b44c7cc929fd7fd05ec5150b..d6efb2763126e7689038078c20f1c0885614a9db 100644 --- a/packages/uni-quickapp-webview/dist/uni.api.esm.js +++ b/packages/uni-quickapp-webview/dist/uni.api.esm.js @@ -1,4 +1,8 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared'; +import { injectHook } from 'vue'; + +//App +const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -36,6 +40,15 @@ const navigateTo = { }, }; +qa.appLaunchHooks = []; +function onAppLaunch(hook) { + const app = getApp({ allowDefault: true }); + if (app && app.$vm) { + return injectHook(ON_LAUNCH, hook, app.$vm.$); + } + qa.appLaunchHooks.push(hook); +} + function getBaseSystemInfo() { return qa.getSystemInfoSync() } @@ -722,6 +735,7 @@ const baseApis = { upx2px, addInterceptor, removeInterceptor, + onAppLaunch, }; function initUni(api, protocols) { const wrapper = initWrapper(protocols); @@ -834,17 +848,17 @@ if (qa.canIUse('getVendorPaymentProvider')) { const getProvider = initGetProvider(providers); var shims = /*#__PURE__*/Object.freeze({ - __proto__: null, - getProvider: getProvider + __proto__: null, + getProvider: getProvider }); var protocols = /*#__PURE__*/Object.freeze({ - __proto__: null, - redirectTo: redirectTo, - navigateTo: navigateTo, - previewImage: previewImage, - getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync + __proto__: null, + redirectTo: redirectTo, + navigateTo: navigateTo, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync }); var index = initUni(shims, protocols); diff --git a/packages/uni-quickapp-webview/dist/uni.mp.esm.js b/packages/uni-quickapp-webview/dist/uni.mp.esm.js index 0677cd47c8a0a3c659cbb48c656a54453084c7c9..84d914f82c0ea1b099e56afce29d649e0adaeabc 100644 --- a/packages/uni-quickapp-webview/dist/uni.mp.esm.js +++ b/packages/uni-quickapp-webview/dist/uni.mp.esm.js @@ -1,4 +1,5 @@ import { isPlainObject, hasOwn, isArray, extend, hyphenate, isObject, toNumber, isFunction, NOOP, camelize } from '@vue/shared'; +import { injectHook } from 'vue'; const encode = encodeURIComponent; function stringifyQuery(obj, encodeStr = encode) { @@ -497,6 +498,13 @@ function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { findHooks(vueOptions).forEach((hook) => initHook$1(mpOptions, hook, excludes)); } +qa.appLaunchHooks = []; +function injectAppLaunchHooks(appInstance) { + qa.appLaunchHooks.forEach((hook) => { + injectHook(ON_LAUNCH, hook, appInstance); + }); +} + const HOOKS = [ ON_SHOW, ON_HIDE, @@ -521,8 +529,9 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); + injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, options); + instance.$callHook(ON_LAUNCH, extend({ app: this }, options)); }, }; const vueOptions = instance.$.type; diff --git a/packages/vue-cli-plugin-uni/lib/configure-webpack.js b/packages/vue-cli-plugin-uni/lib/configure-webpack.js index 63ec16d38a74bc1c05029b405d385cc25aee4d10..8a9af8b25f7a0e0cc37bcaf518955a92e5661250 100644 --- a/packages/vue-cli-plugin-uni/lib/configure-webpack.js +++ b/packages/vue-cli-plugin-uni/lib/configure-webpack.js @@ -307,7 +307,9 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt .UNI_INPUT_DIR), // css中的'@/static/logo.png'会被转换成'./@/static/logo.png'加载 vue$: getPlatformVue(vueOptions), 'uni-pages': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'), - '@dcloudio/uni-stat': require.resolve('@dcloudio/uni-stat'), + '@dcloudio/uni-stat': process.env.UNI_USING_VUE3 ? require.resolve( + '@dcloudio/vue-cli-plugin-uni/packages/uni-stat') : require + .resolve('@dcloudio/uni-stat'), 'uni-stat-config': path.resolve(process.env.UNI_INPUT_DIR, 'pages.json') + '?' + JSON.stringify({ diff --git a/packages/vue-cli-plugin-uni/lib/mp/index.js b/packages/vue-cli-plugin-uni/lib/mp/index.js index 70f3d81eaa08b9d0f86b63830ffde7ae48f59675..1a8e09aaf0e68a858dcbaed9f11aab1f84a226ff 100644 --- a/packages/vue-cli-plugin-uni/lib/mp/index.js +++ b/packages/vue-cli-plugin-uni/lib/mp/index.js @@ -189,6 +189,9 @@ module.exports = { if (process.env.UNI_USING_VUE3) { alias.vuex = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex') alias['@vue/devtools-api'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/devtools-api') + + alias['vue-i18n'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n') + alias['@dcloudio/uni-app'] = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-app') } else { alias.vuex = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/vuex3') } @@ -306,4 +309,4 @@ module.exports = { webpackConfig.plugins.delete('preload') webpackConfig.plugins.delete('prefetch') } -} +} diff --git a/packages/vue-cli-plugin-uni/lib/options.js b/packages/vue-cli-plugin-uni/lib/options.js index 06e0634ae5d8f939ead02114c41faf95644640f4..77a79d2c68e897ec124f247761ad7e437343bff8 100644 --- a/packages/vue-cli-plugin-uni/lib/options.js +++ b/packages/vue-cli-plugin-uni/lib/options.js @@ -27,8 +27,10 @@ module.exports = function initOptions (options) { options.transpileDependencies.push(genTranspileDepRegex(path.resolve(process.env.UNI_INPUT_DIR, 'node_modules'))) options.transpileDependencies.push('@dcloudio/uni-' + process.env.UNI_PLATFORM) options.transpileDependencies.push('@dcloudio/uni-i18n') - options.transpileDependencies.push('@dcloudio/uni-stat') - options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud') + options.transpileDependencies.push('@dcloudio/uni-stat') + options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-app') + options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud') + options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-stat') if (process.env.UNI_PLATFORM !== 'mp-weixin') { // mp runtime options.transpileDependencies.push('@dcloudio/uni-mp-weixin') diff --git a/packages/vue-cli-plugin-uni/packages/uni-app/LICENSE b/packages/vue-cli-plugin-uni/packages/uni-app/LICENSE new file mode 100755 index 0000000000000000000000000000000000000000..7a4a3ea2424c09fbe48d455aed1eaa94d9124835 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-app/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.cjs.js b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..231cb3dae11fb1ae8a1a7c9fd890b544f938e401 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.cjs.js @@ -0,0 +1,165 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var vue = require('vue'); +var shared = require('@vue/shared'); + +const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val; +const UNI_SSR = '__uniSSR'; +const UNI_SSR_DATA = 'data'; +// lifecycle +// App and Page +const ON_SHOW = 'onShow'; +const ON_HIDE = 'onHide'; +//App +const ON_LAUNCH = 'onLaunch'; +const ON_ERROR = 'onError'; +const ON_THEME_CHANGE = 'onThemeChange'; +const ON_PAGE_NOT_FOUND = 'onPageNotFound'; +const ON_UNHANDLE_REJECTION = 'onUnhandledRejection'; +const ON_READY = 'onReady'; +const ON_UNLOAD = 'onUnload'; +const ON_RESIZE = 'onResize'; +const ON_BACK_PRESS = 'onBackPress'; +const ON_PAGE_SCROLL = 'onPageScroll'; +const ON_TAB_ITEM_TAP = 'onTabItemTap'; +const ON_REACH_BOTTOM = 'onReachBottom'; +const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh'; +const ON_SHARE_TIMELINE = 'onShareTimeline'; +const ON_ADD_TO_FAVORITES = 'onAddToFavorites'; +const ON_SHARE_APP_MESSAGE = 'onShareAppMessage'; +// navigationBar +const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged'; + +function assertKey(key, shallow = false) { + if (!key) { + throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`); + } +} +function proxy(target, track, trigger) { + return new Proxy(target, { + get(target, prop) { + track(); + if (shared.isObject(target[prop])) { + return proxy(target[prop], track, trigger); + } + return Reflect.get(target, prop); + }, + set(obj, prop, newVal) { + const result = Reflect.set(obj, prop, newVal); + trigger(); + return result; + }, + }); +} +const globalData = {}; +const ssrServerRef = (value, key, shallow = false) => { + assertKey(key, shallow); + const ctx = vue.getCurrentInstance() && vue.useSSRContext(); + let state; + if (ctx) { + const __uniSSR = ctx[UNI_SSR] || (ctx[UNI_SSR] = {}); + state = __uniSSR[UNI_SSR_DATA] || (__uniSSR[UNI_SSR_DATA] = {}); + } + else { + state = globalData; + } + state[key] = sanitise(value); + // SSR 模式下 watchEffect 不生效 https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/src/apiWatch.ts#L253 + // 故自定义ref + return vue.customRef((track, trigger) => { + const customTrigger = () => (trigger(), (state[key] = sanitise(value))); + return { + get: () => { + track(); + if (!shallow && shared.isObject(value)) { + return proxy(value, track, customTrigger); + } + return value; + }, + set: (v) => { + value = v; + customTrigger(); + }, + }; + }); +}; +const ssrRef = (value, key) => { + { + return ssrServerRef(value, key); + } +}; +const shallowSsrRef = (value, key) => { + { + return ssrServerRef(value, key, true); + } +}; +function getSsrGlobalData() { + return sanitise(globalData); +} + +function resolveEasycom(component, easycom) { + return shared.isString(component) ? easycom : component; +} + +// @ts-ignore +const createHook = (lifecycle) => (hook, target = vue.getCurrentInstance()) => +// post-create lifecycle registrations are noops during SSR +!vue.isInSSRComponentSetup && vue.injectHook(lifecycle, hook, target); +const onShow = /*#__PURE__*/ createHook(ON_SHOW); +const onHide = /*#__PURE__*/ createHook(ON_HIDE); +const onLaunch = /*#__PURE__*/ createHook(ON_LAUNCH); +const onError = /*#__PURE__*/ createHook(ON_ERROR); +const onThemeChange = /*#__PURE__*/ createHook(ON_THEME_CHANGE); +const onPageNotFound = /*#__PURE__*/ createHook(ON_PAGE_NOT_FOUND); +const onUnhandledRejection = /*#__PURE__*/ createHook(ON_UNHANDLE_REJECTION); + +const onReady = /*#__PURE__*/ createHook(ON_READY); +const onUnload = /*#__PURE__*/ createHook(ON_UNLOAD); +const onResize = /*#__PURE__*/ createHook(ON_RESIZE); +const onBackPress = /*#__PURE__*/ createHook(ON_BACK_PRESS); +const onPageScroll = /*#__PURE__*/ createHook(ON_PAGE_SCROLL); +const onTabItemTap = /*#__PURE__*/ createHook(ON_TAB_ITEM_TAP); +const onReachBottom = /*#__PURE__*/ createHook(ON_REACH_BOTTOM); +const onPullDownRefresh = /*#__PURE__*/ createHook(ON_PULL_DOWN_REFRESH); +const onShareTimeline = /*#__PURE__*/ createHook(ON_SHARE_TIMELINE); +const onAddToFavorites = /*#__PURE__*/ createHook(ON_ADD_TO_FAVORITES); +const onShareAppMessage = /*#__PURE__*/ createHook(ON_SHARE_APP_MESSAGE); +const onNavigationBarButtonTap = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_BUTTON_TAP); +const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED); +const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED); +const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED); +const onNavigationBarSearchInputFocusChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED); + +exports.getSsrGlobalData = getSsrGlobalData; +exports.onAddToFavorites = onAddToFavorites; +exports.onBackPress = onBackPress; +exports.onError = onError; +exports.onHide = onHide; +exports.onLaunch = onLaunch; +exports.onNavigationBarButtonTap = onNavigationBarButtonTap; +exports.onNavigationBarSearchInputChanged = onNavigationBarSearchInputChanged; +exports.onNavigationBarSearchInputClicked = onNavigationBarSearchInputClicked; +exports.onNavigationBarSearchInputConfirmed = onNavigationBarSearchInputConfirmed; +exports.onNavigationBarSearchInputFocusChanged = onNavigationBarSearchInputFocusChanged; +exports.onPageNotFound = onPageNotFound; +exports.onPageScroll = onPageScroll; +exports.onPullDownRefresh = onPullDownRefresh; +exports.onReachBottom = onReachBottom; +exports.onReady = onReady; +exports.onResize = onResize; +exports.onShareAppMessage = onShareAppMessage; +exports.onShareTimeline = onShareTimeline; +exports.onShow = onShow; +exports.onTabItemTap = onTabItemTap; +exports.onThemeChange = onThemeChange; +exports.onUnhandledRejection = onUnhandledRejection; +exports.onUnload = onUnload; +exports.resolveEasycom = resolveEasycom; +exports.shallowSsrRef = shallowSsrRef; +exports.ssrRef = ssrRef; diff --git a/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.d.ts b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a04a7bcf3f5459a0601389c3a23644ebc78d0437 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.d.ts @@ -0,0 +1,61 @@ +import { ComponentInternalInstance } from 'vue'; +import { ref } from 'vue'; +import { shallowRef } from 'vue'; + +export declare function getSsrGlobalData(): any; + +export declare const onAddToFavorites: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onBackPress: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onError: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onHide: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onLaunch: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onNavigationBarButtonTap: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onNavigationBarSearchInputChanged: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onNavigationBarSearchInputClicked: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onNavigationBarSearchInputConfirmed: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onNavigationBarSearchInputFocusChanged: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onPageNotFound: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onPageScroll: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onPullDownRefresh: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onReachBottom: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onReady: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onResize: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onShareAppMessage: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onShareTimeline: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onShow: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onTabItemTap: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onThemeChange: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onUnhandledRejection: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare const onUnload: (hook: () => any, target?: ComponentInternalInstance | null) => any; + +export declare function resolveEasycom(component: unknown, easycom: unknown): unknown; + +export declare const shallowSsrRef: SSRRef; + +declare type SSRRef = (value: unknown, key?: string, shallow?: boolean) => ReturnType | ReturnType; + +export declare const ssrRef: SSRRef; + +export { } diff --git a/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.es.js b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.es.js new file mode 100644 index 0000000000000000000000000000000000000000..64a5f3ab86fffe38b284af1b0bcdfcf2406dfbb8 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-app/dist/uni-app.es.js @@ -0,0 +1,108 @@ +import { shallowRef, ref, getCurrentInstance, isInSSRComponentSetup, injectHook } from 'vue'; +import { hasOwn, isString } from '@vue/shared'; + +const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val; +const UNI_SSR = '__uniSSR'; +const UNI_SSR_DATA = 'data'; +const UNI_SSR_GLOBAL_DATA = 'globalData'; +// lifecycle +// App and Page +const ON_SHOW = 'onShow'; +const ON_HIDE = 'onHide'; +//App +const ON_LAUNCH = 'onLaunch'; +const ON_ERROR = 'onError'; +const ON_THEME_CHANGE = 'onThemeChange'; +const ON_PAGE_NOT_FOUND = 'onPageNotFound'; +const ON_UNHANDLE_REJECTION = 'onUnhandledRejection'; +const ON_READY = 'onReady'; +const ON_UNLOAD = 'onUnload'; +const ON_RESIZE = 'onResize'; +const ON_BACK_PRESS = 'onBackPress'; +const ON_PAGE_SCROLL = 'onPageScroll'; +const ON_TAB_ITEM_TAP = 'onTabItemTap'; +const ON_REACH_BOTTOM = 'onReachBottom'; +const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh'; +const ON_SHARE_TIMELINE = 'onShareTimeline'; +const ON_ADD_TO_FAVORITES = 'onAddToFavorites'; +const ON_SHARE_APP_MESSAGE = 'onShareAppMessage'; +// navigationBar +const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed'; +const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged'; + +function getSSRDataType() { + return getCurrentInstance() ? UNI_SSR_DATA : UNI_SSR_GLOBAL_DATA; +} +function assertKey(key, shallow = false) { + if (!key) { + throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`); + } +} +const ssrClientRef = (value, key, shallow = false) => { + const valRef = shallow ? shallowRef(value) : ref(value); + // 非 h5 平台 + if (typeof window === 'undefined') { + return valRef; + } + const __uniSSR = window[UNI_SSR]; + if (!__uniSSR) { + return valRef; + } + const type = getSSRDataType(); + assertKey(key, shallow); + if (hasOwn(__uniSSR[type], key)) { + valRef.value = __uniSSR[type][key]; + if (type === UNI_SSR_DATA) { + delete __uniSSR[type][key]; // TODO 非全局数据仅使用一次?否则下次还会再次使用该数据 + } + } + return valRef; +}; +const globalData = {}; +const ssrRef = (value, key) => { + return ssrClientRef(value, key); +}; +const shallowSsrRef = (value, key) => { + return ssrClientRef(value, key, true); +}; +function getSsrGlobalData() { + return sanitise(globalData); +} + +function resolveEasycom(component, easycom) { + return isString(component) ? easycom : component; +} + +// @ts-ignore +const createHook = (lifecycle) => (hook, target = getCurrentInstance()) => +// post-create lifecycle registrations are noops during SSR +!isInSSRComponentSetup && injectHook(lifecycle, hook, target); +const onShow = /*#__PURE__*/ createHook(ON_SHOW); +const onHide = /*#__PURE__*/ createHook(ON_HIDE); +const onLaunch = /*#__PURE__*/ createHook(ON_LAUNCH); +const onError = /*#__PURE__*/ createHook(ON_ERROR); +const onThemeChange = /*#__PURE__*/ createHook(ON_THEME_CHANGE); +const onPageNotFound = /*#__PURE__*/ createHook(ON_PAGE_NOT_FOUND); +const onUnhandledRejection = /*#__PURE__*/ createHook(ON_UNHANDLE_REJECTION); + +const onReady = /*#__PURE__*/ createHook(ON_READY); +const onUnload = /*#__PURE__*/ createHook(ON_UNLOAD); +const onResize = /*#__PURE__*/ createHook(ON_RESIZE); +const onBackPress = /*#__PURE__*/ createHook(ON_BACK_PRESS); +const onPageScroll = /*#__PURE__*/ createHook(ON_PAGE_SCROLL); +const onTabItemTap = /*#__PURE__*/ createHook(ON_TAB_ITEM_TAP); +const onReachBottom = /*#__PURE__*/ createHook(ON_REACH_BOTTOM); +const onPullDownRefresh = /*#__PURE__*/ createHook(ON_PULL_DOWN_REFRESH); +const onShareTimeline = /*#__PURE__*/ createHook(ON_SHARE_TIMELINE); +const onAddToFavorites = /*#__PURE__*/ createHook(ON_ADD_TO_FAVORITES); +const onShareAppMessage = /*#__PURE__*/ createHook(ON_SHARE_APP_MESSAGE); +const onNavigationBarButtonTap = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_BUTTON_TAP); +const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED); +const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED); +const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED); +const onNavigationBarSearchInputFocusChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED); + +export { getSsrGlobalData, onAddToFavorites, onBackPress, onError, onHide, onLaunch, onNavigationBarButtonTap, onNavigationBarSearchInputChanged, onNavigationBarSearchInputClicked, onNavigationBarSearchInputConfirmed, onNavigationBarSearchInputFocusChanged, onPageNotFound, onPageScroll, onPullDownRefresh, onReachBottom, onReady, onResize, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, resolveEasycom, shallowSsrRef, ssrRef }; diff --git a/packages/vue-cli-plugin-uni/packages/uni-app/package.json b/packages/vue-cli-plugin-uni/packages/uni-app/package.json new file mode 100644 index 0000000000000000000000000000000000000000..97b29269d33a853e1dbacd8381cf89cb864d8b2a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-app/package.json @@ -0,0 +1,22 @@ +{ + "name": "@dcloudio/uni-app", + "version": "3.0.0-alpha-3000020210813002", + "description": "@dcloudio/uni-app", + "main": "./dist/uni-app.cjs.js", + "module": "./dist/uni-app.es.js", + "types": "./dist/uni-app.d.ts", + "files": [ + "dist" + ], + "sideEffects": false, + "repository": { + "type": "git", + "url": "git+https://github.com/dcloudio/uni-app.git", + "directory": "packages/uni-app" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/dcloudio/uni-app/issues" + }, + "gitHead": "d5896d19315a106039411c16bbf8b804a865450d" +} diff --git a/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.cjs.js b/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..31f86970315ce69beb36e61e1661379544197295 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.cjs.js @@ -0,0 +1,961 @@ +'use strict'; + +var version = "3.0.0-alpha-3000020210813002"; + +const STAT_VERSION = version; +const STAT_URL = 'https://tongji.dcloud.io/uni/stat'; +const STAT_H5_URL = 'https://tongji.dcloud.io/uni/stat.gif'; +const PAGE_PVER_TIME = 1800; +const APP_PVER_TIME = 300; +const OPERATING_TIME = 10; +const DIFF_TIME = 60 * 1000 * 60 * 24; + +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); +}; + +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} +var Stat$1 = Stat; + +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + +main(); diff --git a/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.es.js b/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.es.js new file mode 100644 index 0000000000000000000000000000000000000000..5eb8cd9b8de9d32b82d7f40e76f33f2a0b62cb65 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-stat/dist/uni-stat.es.js @@ -0,0 +1,959 @@ +var version = "3.0.0-alpha-3000020210813002"; + +const STAT_VERSION = version; +const STAT_URL = 'https://tongji.dcloud.io/uni/stat'; +const STAT_H5_URL = 'https://tongji.dcloud.io/uni/stat.gif'; +const PAGE_PVER_TIME = 1800; +const APP_PVER_TIME = 300; +const OPERATING_TIME = 10; +const DIFF_TIME = 60 * 1000 * 60 * 24; + +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); +}; + +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} +var Stat$1 = Stat; + +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + +main(); diff --git a/packages/vue-cli-plugin-uni/packages/uni-stat/lib/uni.plugin.js b/packages/vue-cli-plugin-uni/packages/uni-stat/lib/uni.plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bdb080dc89ea171a3b91e87e8a81668ed5a4214a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-stat/lib/uni.plugin.js @@ -0,0 +1,68 @@ +const debug = require('debug') +const { + M, + defineUniMainJsPlugin, + getUniStatistics, + parseManifestJsonOnce, + parsePagesJsonOnce, +} = require('@dcloudio/uni-cli-shared') + +module.exports = [ + defineUniMainJsPlugin((opts) => { + let isEnable = false + return { + name: 'vite:uni-stat', + enforce: 'pre', + config(config, env) { + if (isSsr(env.command, config)) { + return + } + const inputDir = process.env.UNI_INPUT_DIR + const platform = process.env.UNI_PLATFORM + isEnable = getUniStatistics(inputDir, platform).enable === true + if (process.env.NODE_ENV === 'production') { + const manifestJson = parseManifestJsonOnce(inputDir) + if (!manifestJson.appid) { + console.log() + console.warn(M['stat.warn.appid']) + console.log() + isEnable = false + } + } + const titlesJson = Object.create(null) + if (isEnable) { + parsePagesJsonOnce(inputDir, platform).pages.forEach((page) => { + const titleText = page.style.navigationBar.titleText || '' + if (titleText) { + titlesJson[page.path] = titleText + } + }) + } + debug('vite:uni:stat')('isEnable', isEnable) + return { + define: { + 'process.env.UNI_STAT_TITLE_JSON': JSON.stringify(titlesJson), + }, + } + }, + transform(code, id) { + if (isEnable && opts.filter(id)) { + return { + code: code + `;import '@dcloudio/uni-stat';`, + map: null, + } + } + }, + } + }), +] + +function isSsr(command, config) { + if (command === 'serve') { + return !!(config.server && config.server.middlewareMode) + } + if (command === 'build') { + return !!(config.build && config.build.ssr) + } + return false +} diff --git a/packages/vue-cli-plugin-uni/packages/uni-stat/package.json b/packages/vue-cli-plugin-uni/packages/uni-stat/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3770af6d7c74bac7008447d6bee92d06a9db1295 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/uni-stat/package.json @@ -0,0 +1,25 @@ +{ + "name": "@dcloudio/uni-stat", + "version": "3.0.0-alpha-3000020210813002", + "description": "@dcloudio/uni-stat", + "main": "dist/uni-stat.cjs.js", + "module": "dist/uni-stat.es.js", + "files": [ + "dist", + "lib" + ], + "sideEffects": false, + "repository": { + "type": "git", + "url": "git+https://github.com/dcloudio/uni-app.git", + "directory": "packages/uni-stat" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/dcloudio/uni-app/issues" + }, + "uni-app": { + "name": "uniStat" + }, + "gitHead": "d5896d19315a106039411c16bbf8b804a865450d" +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/.yarn-integrity b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/.yarn-integrity new file mode 100644 index 0000000000000000000000000000000000000000..2748195cd565c54b52dc60e5406eca07f8439f3e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/.yarn-integrity @@ -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": {} +} \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1b7c34803dc0c40dc7f85264e21d6850e3222785 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/README.md @@ -0,0 +1,7 @@ +# @intlify/core-base + +The intlify core base module + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..c6ffe48de73cf11cfde9ca6b08ea04c806be742f --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.js @@ -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]; +}); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..33c33d4357654be2e8b5d3d03e7bc00dd3a368df --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.cjs.prod.js @@ -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]; +}); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3548358da36840432b7d89bf3633cf4f0dc694bf --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.d.ts @@ -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(source: string, options?: CompileOptions): MessageFunction; + +export declare interface CoreCommonContext { + cid: number; + version: string; + locale: Locale; + fallbackLocale: FallbackLocale; + missing: CoreMissingHandler | null; + missingWarn: boolean | RegExp; + fallbackWarn: boolean | RegExp; + fallbackFormat: boolean; + unresolving: boolean; + onWarn(msg: string, err?: Error): void; +} + +export declare interface CoreContext extends CoreTranslationContext, CoreDateTimeContext, CoreNumberContext { +} + +export declare interface CoreDateTimeContext extends CoreCommonContext { + 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; + __numberFormatters: Map; + __localeChainCache?: Map; + __v_emitter?: VueDevToolsEmitter; + __meta: MetaInfo; +} + +export declare interface CoreInternalOptions { + __datetimeFormatters?: Map; + __numberFormatters?: Map; + __v_emitter?: VueDevToolsEmitter; + __meta?: MetaInfo; +} + +export declare type CoreMissingHandler = (context: CoreCommonContext, locale: Locale, key: Path, type: CoreMissingType, ...values: unknown[]) => string | void; + +export declare interface CoreNumberContext extends CoreCommonContext { + numberFormats: NumberFormats; +} + +export declare interface CoreOptions { + version?: string; + locale?: Locale; + fallbackLocale?: FallbackLocale; + messages?: LocaleMessages; + datetimeFormats?: DateTimeFormats; + numberFormats?: NumberFormats; + modifiers?: LinkedModifiers; + pluralRules?: PluralizationRules; + missing?: CoreMissingHandler; + missingWarn?: boolean | RegExp; + fallbackWarn?: boolean | RegExp; + fallbackFormat?: boolean; + unresolving?: boolean; + postTranslation?: PostTranslationHandler; + processor?: MessageProcessor; + warnHtmlMessage?: boolean; + escapeParameter?: boolean; + messageCompiler?: MessageCompiler; + onWarn?: (msg: string, err?: Error) => void; +} + +export declare interface CoreTranslationContext extends CoreCommonContext { + messages: Messages; + modifiers: LinkedModifiers; + pluralRules?: PluralizationRules; + postTranslation: PostTranslationHandler | null; + processor: MessageProcessor | null; + warnHtmlMessage: boolean; + escapeParameter: boolean; + messageCompiler: MessageCompiler | 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 = object, Messages extends Record> = Record>, DateTimeFormats extends Record = Record, NumberFormats extends Record = Record>(options?: Options): CoreContext; + +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(context: CoreDateTimeContext, value: number | Date): string | number | Intl.DateTimeFormatPart[]; + +export declare function datetime(context: CoreDateTimeContext, value: number | Date, key: string): string | number | Intl.DateTimeFormatPart[]; + +export declare function datetime(context: CoreDateTimeContext, value: number | Date, key: string, locale: Locale): string | number | Intl.DateTimeFormatPart[]; + +export declare function datetime(context: CoreDateTimeContext, value: number | Date, options: DateTimeOptions): string | number | Intl.DateTimeFormatPart[]; + +export declare function datetime(context: CoreDateTimeContext, ...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): void; + +export declare const isMessageFunction: (val: unknown) => val is MessageFunction; + +/* Excluded from this release type: isTranslateFallbackWarn */ + +/* Excluded from this release type: isTranslateMissingWarn */ + +export declare type LocaleMatcher = 'lookup' | 'best fit'; + +/** @VueI18nGeneral */ +export declare interface LocaleMessageArray extends Array> { +} + +/** @VueI18nGeneral */ +export declare type LocaleMessageDictionary = { + [property: string]: LocaleMessageValue; +}; + +/** @VueI18nGeneral */ +export declare type LocaleMessages = Record>; + +/** @VueI18nGeneral */ +export declare type LocaleMessageValue = string | MessageFunction | LocaleMessageDictionary | LocaleMessageArray; + +export declare type MessageCompiler = (source: string, options?: CompileOptions) => MessageFunction; + +export declare interface MetaInfo { + [field: string]: unknown; +} + +export declare const MISSING_RESOLVE_VALUE = ""; + +export declare const NOT_REOSLVED = -1; + +export declare function number(context: CoreNumberContext, value: number): string | number | Intl.NumberFormatPart[]; + +export declare function number(context: CoreNumberContext, value: number, key: string): string | number | Intl.NumberFormatPart[]; + +export declare function number(context: CoreNumberContext, value: number, key: string, locale: Locale): string | number | Intl.NumberFormatPart[]; + +export declare function number(context: CoreNumberContext, value: number, options: NumberOptions): string | number | Intl.NumberFormatPart[]; + +export declare function number(context: CoreNumberContext, ...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 = (translated: MessageType) => MessageType; + +export declare function registerMessageCompiler(compiler: MessageCompiler): 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(context: CoreTranslationContext, key: Path | number): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, plural: number): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, plural: number, options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, message: MessageFunction | string, plural: number, options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, defaultMsg: string): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, defaultMsg: string, options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, list: unknown[]): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, list: unknown[], plural: number): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, list: unknown[], defaultMsg: string): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, list: unknown[], options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, message: MessageFunction | string, list: unknown[], options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, named: NamedValue): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, named: NamedValue, plural: number): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, named: NamedValue, defaultMsg: string): MessageType | number; + +export declare function translate(context: CoreTranslationContext, key: Path | number, named: NamedValue, options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, message: MessageFunction | string, named: NamedValue, options: TranslateOptions): MessageType | number; + +export declare function translate(context: CoreTranslationContext, ...args: unknown[]): MessageType | 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 { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..1a84cdbdfa7178f4cd8daa405493cb10b1666a97 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.js @@ -0,0 +1,2771 @@ +/*! + * @intlify/core-base 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; +{ + 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 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; +function escapeHtml(rawText) { + return rawText + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; +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'); +} + +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; +} + +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; +} + +/** @internal */ +const errorMessages$1 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$1)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; + +function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' +}; + +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 + { + 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 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 (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 + 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, { 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) => 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 (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 !! + { + // 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 (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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!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 (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 (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 (!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 (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 (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); + } +} + +export { DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compileToFunction, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, getAdditionalMeta, getDevToolsHook, getLocaleChain, getWarnMessage, handleFlatJson, handleMissing, initI18nDevTools, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerMessageCompiler, resolveValue, setAdditionalMeta, setDevToolsHook, translate, translateDevTools, updateFallbackLocale }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..7fb9863cf327e165e1968481ca438731543a2519 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.esm-browser.prod.js @@ -0,0 +1,6 @@ +/*! + * @intlify/core-base v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +const e=/\{([0-9a-zA-Z]+)\}/g;const t=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),n=e=>"number"==typeof e&&isFinite(e),r=e=>"[object RegExp]"===k(e),o=e=>g(e)&&0===Object.keys(e).length;function c(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const s=Object.assign;function a(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const u=Object.prototype.hasOwnProperty;function l(e,t){return u.call(e,t)}const i=Array.isArray,f=e=>"function"==typeof e,p=e=>"string"==typeof e,m=e=>"boolean"==typeof e,d=e=>null!==e&&"object"==typeof e,h=Object.prototype.toString,k=e=>h.call(e),g=e=>"[object Object]"===k(e),b=[];b[0]={w:[0],i:[3,0],"[":[4],o:[7]},b[1]={w:[1],".":[2],"[":[4],o:[7]},b[2]={w:[2],i:[3,0],0:[3,0]},b[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},b[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},b[5]={"'":[4,0],o:8,l:[5,0]},b[6]={'"':[4,0],o:8,l:[6,0]};const y=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function x(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function w(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(y.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}function C(e){const t=[];let n,r,o,c,s,a,u,l=-1,i=0,f=0;const p=[];function m(){const t=e[l+1];if(5===i&&"'"===t||6===i&&'"'===t)return l++,o="\\"+t,p[0](),!0}for(p[0]=()=>{void 0===r?r=o:r+=o},p[1]=()=>{void 0!==r&&(t.push(r),r=void 0)},p[2]=()=>{p[0](),f++},p[3]=()=>{if(f>0)f--,i=4,p[0]();else{if(f=0,void 0===r)return!1;if(r=w(r),!1===r)return!1;p[1]()}};null!==i;)if(l++,n=e[l],"\\"!==n||!m()){if(c=x(n),u=b[i],s=u[c]||u.l||8,8===s)return;if(i=s[0],void 0!==s[1]&&(a=p[s[1]],a&&(o=n,!1===a())))return;if(7===i)return t}}const _=new Map;function v(e,t){if(!d(e))return null;let n=_.get(t);if(n||(n=C(t),n&&_.set(t,n)),!n)return null;const r=n.length;let o=e,c=0;for(;ce,P=e=>"",O="text",F=e=>0===e.length?"":e.join(""),N=e=>null==e?"":i(e)||g(e)&&e.toString===h?JSON.stringify(e,null,2):String(e);function $(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function S(e={}){const t=e.locale,r=function(e){const t=n(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(n(e.named.count)||n(e.named.n))?n(e.named.count)?e.named.count:n(e.named.n)?e.named.n:t:t}(e),o=d(e.pluralRules)&&p(t)&&f(e.pluralRules[t])?e.pluralRules[t]:$,c=d(e.pluralRules)&&p(t)&&f(e.pluralRules[t])?$:void 0,s=e.list||[],a=e.named||{};n(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(r,a);function u(t){const n=f(e.messages)?e.messages(t):!!d(e.messages)&&e.messages[t];return n||(e.parent?e.parent.message(t):P)}const l=g(e.processor)&&f(e.processor.normalize)?e.processor.normalize:F,i=g(e.processor)&&f(e.processor.interpolate)?e.processor.interpolate:N,m={list:e=>s[e],named:e=>a[e],plural:e=>e[o(r,e.length,c)],linked:(t,n)=>{const r=u(t)(m);return p(n)?(o=n,e.modifiers?e.modifiers[o]:T)(r):r;var o},message:u,type:g(e.processor)&&p(e.processor.type)?e.processor.type:"text",interpolate:i,normalize:l};return m}function I(e,t,n={}){const{domain:r}=n,o=new SyntaxError(String(e));return o.code=e,t&&(o.location=t),o.domain=r,o}function E(e){throw e}function A(e,t,n){const r={start:e,end:t};return null!=n&&(r.source=n),r}const W=String.fromCharCode(8232),j=String.fromCharCode(8233);function M(e){const t=e;let n=0,r=1,o=1,c=0;const s=e=>"\r"===t[e]&&"\n"===t[e+1],a=e=>t[e]===j,u=e=>t[e]===W,l=e=>s(e)||(e=>"\n"===t[e])(e)||a(e)||u(e),i=e=>s(e)||a(e)||u(e)?"\n":t[e];function f(){return c=0,l(n)&&(r++,o=0),s(n)&&n++,n++,o++,t[n]}return{index:()=>n,line:()=>r,column:()=>o,peekOffset:()=>c,charAt:i,currentChar:()=>i(n),currentPeek:()=>i(n+c),next:f,peek:function(){return s(n+c)&&c++,c++,t[n+c]},reset:function(){n=0,r=1,o=1,c=0},resetPeek:function(e=0){c=e},skipToPeek:function(){const e=n+c;for(;e!==n;)f();c=0}}}const R=void 0;function J(e,t={}){const n=!1!==t.location,r=M(e),o=()=>r.index(),c=()=>{return e=r.line(),t=r.column(),n=r.index(),{line:e,column:t,offset:n};var e,t,n},s=c(),a=o(),u={currentType:14,offset:a,startLoc:s,endLoc:s,lastType:14,lastOffset:a,lastStartLoc:s,lastEndLoc:s,braceNest:0,inLinked:!1,text:""},l=()=>u,{onError:i}=t;function f(e,t,r){e.endLoc=c(),e.currentType=t;const o={type:t};return n&&(o.loc=A(e.startLoc,e.endLoc)),null!=r&&(o.value=r),o}const p=e=>f(e,14);function m(e,t){return e.currentChar()===t?(e.next(),t):(c(),"")}function d(e){let t="";for(;" "===e.currentPeek()||"\n"===e.currentPeek();)t+=e.currentPeek(),e.peek();return t}function h(e){const t=d(e);return e.skipToPeek(),t}function k(e){if(e===R)return!1;const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||95===t}function g(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r=function(e){if(e===R)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function b(e){d(e);const t="|"===e.currentPeek();return e.resetPeek(),t}function y(e,t=!0){const n=(t=!1,r="",o=!1)=>{const c=e.currentPeek();return"{"===c?"%"!==r&&t:"@"!==c&&c?"%"===c?(e.peek(),n(t,"%",!0)):"|"===c?!("%"!==r&&!o)||!(" "===r||"\n"===r):" "===c?(e.peek(),n(!0," ",o)):"\n"!==c||(e.peek(),n(!0,"\n",o)):"%"===r||t},r=n();return t&&e.resetPeek(),r}function x(e,t){const n=e.currentChar();return n===R?R:t(n)?(e.next(),n):null}function w(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||t>=48&&t<=57||95===t||36===t}))}function C(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57}))}function _(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}))}function v(e){let t="",n="";for(;t=C(e);)n+=t;return n}function L(e){const t=e.currentChar();switch(t){case"\\":case"'":return e.next(),`\\${t}`;case"u":return T(e,t,4);case"U":return T(e,t,6);default:return c(),""}}function T(e,t,n){m(e,t);let r="";for(let t=0;t=1&&c(),e.next(),n=f(t,2,"{"),h(e),t.braceNest++,n;case"}":return t.braceNest>0&&2===t.currentType&&c(),e.next(),n=f(t,3,"}"),t.braceNest--,t.braceNest>0&&h(e),t.inLinked&&0===t.braceNest&&(t.inLinked=!1),n;case"@":return t.braceNest>0&&c(),n=F(e,t)||p(t),t.braceNest=0,n;default:let r=!0,o=!0,s=!0;if(b(e))return t.braceNest>0&&c(),n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(t.braceNest>0&&(5===t.currentType||6===t.currentType||7===t.currentType))return c(),t.braceNest=0,N(e,t);if(r=function(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r=k(e.currentPeek());return e.resetPeek(),r}(e,t))return n=f(t,5,function(e){h(e);let t="",n="";for(;t=w(e);)n+=t;return e.currentChar()===R&&c(),n}(e)),h(e),n;if(o=g(e,t))return n=f(t,6,function(e){h(e);let t="";return"-"===e.currentChar()?(e.next(),t+=`-${v(e)}`):t+=v(e),e.currentChar()===R&&c(),t}(e)),h(e),n;if(s=function(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,t))return n=f(t,7,function(e){h(e),m(e,"'");let t="",n="";const r=e=>"'"!==e&&"\n"!==e;for(;t=x(e,r);)n+="\\"===t?L(e):t;const o=e.currentChar();return"\n"===o||o===R?(c(),"\n"===o&&(e.next(),m(e,"'")),n):(m(e,"'"),n)}(e)),h(e),n;if(!r&&!o&&!s)return n=f(t,13,function(e){h(e);let t="",n="";const r=e=>"{"!==e&&"}"!==e&&" "!==e&&"\n"!==e;for(;t=x(e,r);)n+=t;return n}(e)),c(),h(e),n}return n}function F(e,t){const{currentType:n}=t;let r=null;const o=e.currentChar();switch(8!==n&&9!==n&&12!==n&&10!==n||"\n"!==o&&" "!==o||c(),o){case"@":return e.next(),r=f(t,8,"@"),t.inLinked=!0,r;case".":return h(e),e.next(),f(t,9,".");case":":return h(e),e.next(),f(t,10,":");default:return b(e)?(r=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,r):function(e,t){const{currentType:n}=t;if(8!==n)return!1;d(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,t)||function(e,t){const{currentType:n}=t;if(8!==n&&12!==n)return!1;d(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,t)?(h(e),F(e,t)):function(e,t){const{currentType:n}=t;if(9!==n)return!1;d(e);const r=k(e.currentPeek());return e.resetPeek(),r}(e,t)?(h(e),f(t,12,function(e){let t="",n="";for(;t=w(e);)n+=t;return n}(e))):function(e,t){const{currentType:n}=t;if(10!==n)return!1;const r=()=>{const t=e.currentPeek();return"{"===t?k(e.peek()):!("@"===t||"%"===t||"|"===t||":"===t||"."===t||" "===t||!t)&&("\n"===t?(e.peek(),r()):k(t))},o=r();return e.resetPeek(),o}(e,t)?(h(e),"{"===o?O(e,t)||r:f(t,11,function(e){const t=(n=!1,r)=>{const o=e.currentChar();return"{"!==o&&"%"!==o&&"@"!==o&&"|"!==o&&o?" "===o?r:"\n"===o?(r+=o,e.next(),t(n,r)):(r+=o,e.next(),t(!0,r)):r};return t(!1,"")}(e))):(8===n&&c(),t.braceNest=0,t.inLinked=!1,N(e,t))}}function N(e,t){let n={type:14};if(t.braceNest>0)return O(e,t)||p(t);if(t.inLinked)return F(e,t)||p(t);const r=e.currentChar();switch(r){case"{":return O(e,t)||p(t);case"}":return c(),e.next(),f(t,3,"}");case"@":return F(e,t)||p(t);default:if(b(e))return n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(y(e))return f(t,0,function(e){const t=n=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?y(e)?(n+=r,e.next(),t(n)):n:"|"===r?n:" "===r||"\n"===r?y(e)?(n+=r,e.next(),t(n)):b(e)?n:(n+=r,e.next(),t(n)):(n+=r,e.next(),t(n)):n};return t("")}(e));if("%"===r)return e.next(),f(t,4,"%")}return n}return{nextToken:function(){const{currentType:e,offset:t,startLoc:n,endLoc:s}=u;return u.lastType=e,u.lastOffset=t,u.lastStartLoc=n,u.lastEndLoc=s,u.offset=o(),u.startLoc=c(),r.currentChar()===R?f(u,14):N(r,u)},currentOffset:o,currentPosition:c,context:l}}const z=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function D(e,t,n){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(t||n,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function H(e={}){const t=!1!==e.location,{onError:n}=e;function r(e,n,r){const o={type:e,start:n,end:n};return t&&(o.loc={start:r,end:r}),o}function o(e,n,r,o){e.end=n,o&&(e.type=o),t&&e.loc&&(e.loc.end=r)}function c(e,t){const n=e.context(),c=r(3,n.offset,n.startLoc);return c.value=t,o(c,e.currentOffset(),e.currentPosition()),c}function a(e,t){const n=e.context(),{lastOffset:c,lastStartLoc:s}=n,a=r(5,c,s);return a.index=parseInt(t,10),e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function u(e,t){const n=e.context(),{lastOffset:c,lastStartLoc:s}=n,a=r(4,c,s);return a.key=t,e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function l(e,t){const n=e.context(),{lastOffset:c,lastStartLoc:s}=n,a=r(9,c,s);return a.value=t.replace(z,D),e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function i(e){const t=e.context(),n=r(6,t.offset,t.startLoc);let c=e.nextToken();if(9===c.type){const t=function(e){const t=e.nextToken(),n=e.context(),{lastOffset:c,lastStartLoc:s}=n,a=r(8,c,s);return 12!==t.type?(a.value="",o(a,c,s),{nextConsumeToken:t,node:a}):(null==t.value&&U(t),a.value=t.value||"",o(a,e.currentOffset(),e.currentPosition()),{node:a})}(e);n.modifier=t.node,c=t.nextConsumeToken||e.nextToken()}switch(10!==c.type&&U(c),c=e.nextToken(),2===c.type&&(c=e.nextToken()),c.type){case 11:null==c.value&&U(c),n.key=function(e,t){const n=e.context(),c=r(7,n.offset,n.startLoc);return c.value=t,o(c,e.currentOffset(),e.currentPosition()),c}(e,c.value||"");break;case 5:null==c.value&&U(c),n.key=u(e,c.value||"");break;case 6:null==c.value&&U(c),n.key=a(e,c.value||"");break;case 7:null==c.value&&U(c),n.key=l(e,c.value||"");break;default:const t=e.context(),s=r(7,t.offset,t.startLoc);return s.value="",o(s,t.offset,t.startLoc),n.key=s,o(n,t.offset,t.startLoc),{nextConsumeToken:c,node:n}}return o(n,e.currentOffset(),e.currentPosition()),{node:n}}function f(e){const t=e.context(),n=r(2,1===t.currentType?e.currentOffset():t.offset,1===t.currentType?t.endLoc:t.startLoc);n.items=[];let s=null;do{const t=s||e.nextToken();switch(s=null,t.type){case 0:null==t.value&&U(t),n.items.push(c(e,t.value||""));break;case 6:null==t.value&&U(t),n.items.push(a(e,t.value||""));break;case 5:null==t.value&&U(t),n.items.push(u(e,t.value||""));break;case 7:null==t.value&&U(t),n.items.push(l(e,t.value||""));break;case 8:const r=i(e);n.items.push(r.node),s=r.nextConsumeToken||null}}while(14!==t.currentType&&1!==t.currentType);return o(n,1===t.currentType?t.lastOffset:e.currentOffset(),1===t.currentType?t.lastEndLoc:e.currentPosition()),n}function p(e){const t=e.context(),{offset:n,startLoc:c}=t,s=f(e);return 14===t.currentType?s:function(e,t,n,c){const s=e.context();let a=0===c.items.length;const u=r(1,t,n);u.cases=[],u.cases.push(c);do{const t=f(e);a||(a=0===t.items.length),u.cases.push(t)}while(14!==s.currentType);return o(u,e.currentOffset(),e.currentPosition()),u}(e,n,c,s)}return{parse:function(n){const c=J(n,s({},e)),a=c.context(),u=r(0,a.offset,a.startLoc);return t&&u.loc&&(u.loc.source=n),u.body=p(c),o(u,c.currentOffset(),c.currentPosition()),u}}}function U(e){if(14===e.type)return"EOF";const t=(e.value||"").replace(/\r?\n/gu,"\\n");return t.length>10?t.slice(0,9)+"…":t}function K(e,t){for(let n=0;nn,helper:e=>(n.helpers.add(e),e)}}(e);n.helper("normalize"),e.body&&q(e.body,n);const r=n.context();e.helpers=Array.from(r.helpers)}function B(e,t){const{helper:n}=e;switch(t.type){case 0:!function(e,t){t.body?B(e,t.body):e.push("null")}(e,t);break;case 1:!function(e,t){const{helper:n,needIndent:r}=e;if(t.cases.length>1){e.push(`${n("plural")}([`),e.indent(r());const o=t.cases.length;for(let n=0;n{const n=p(t.mode)?t.mode:"normal",r=p(t.filename)?t.filename:"message.intl",o=t.needIndent?t.needIndent:"arrow"!==n,c=e.helpers||[],s=function(e,t){const{filename:n,breakLineCode:r,needIndent:o}=t,c={source:e.loc.source,filename:n,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:o,indentLevel:0};function s(e,t){c.code+=e}function a(e,t=!0){const n=t?r:"";s(o?n+" ".repeat(e):n)}return{context:()=>c,push:s,indent:function(e=!0){const t=++c.indentLevel;e&&a(t)},deindent:function(e=!0){const t=--c.indentLevel;e&&a(t)},newline:function(){a(c.indentLevel)},helper:e=>`_${e}`,needIndent:()=>c.needIndent}}(e,{mode:n,filename:r,sourceMap:!!t.sourceMap,breakLineCode:null!=t.breakLineCode?t.breakLineCode:"arrow"===n?";":"\n",needIndent:o});s.push("normal"===n?"function __msg__ (ctx) {":"(ctx) => {"),s.indent(o),c.length>0&&(s.push(`const { ${c.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),s.newline()),s.push("return "),B(s,e),s.deindent(o),s.push("}");const{code:a,map:u}=s.context();return{ast:e,code:a,map:u?u.toJSON():void 0}})(r,n)}const Q="i18n:init";let V=null;function X(e){V=e}function Y(){return V}function ee(e,t,n){V&&V.emit(Q,{timestamp:Date.now(),i18n:e,version:t,meta:n})}const te=ne("function:translate");function ne(e){return t=>V&&V.emit(e,t)}const re={0:"Not found '{key}' key in '{locale}' locale messages.",1:"Fall back to translate '{key}' key with '{target}' locale.",2:"Cannot format a number value due to not supported Intl.NumberFormat.",3:"Fall back to number format '{key}' key with '{target}' locale.",4:"Cannot format a date value due to not supported Intl.DateTimeFormat.",5:"Fall back to datetime format '{key}' key with '{target}' locale."};function oe(t,...n){return function(t,...n){return 1===n.length&&d(n[0])&&(n=n[0]),n&&n.hasOwnProperty||(n={}),t.replace(e,((e,t)=>n.hasOwnProperty(t)?n[t]:""))}(re[t],...n)}const ce="9.1.7",se=-1,ae="";let ue;function le(e){ue=e}let ie=null;const fe=e=>{ie=e},pe=()=>ie;let me=0;function de(e={}){const t=p(e.version)?e.version:"9.1.7",n=p(e.locale)?e.locale:"en-US",o=i(e.fallbackLocale)||g(e.fallbackLocale)||p(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:n,a=g(e.messages)?e.messages:{[n]:{}},u=g(e.datetimeFormats)?e.datetimeFormats:{[n]:{}},l=g(e.numberFormats)?e.numberFormats:{[n]:{}},h=s({},e.modifiers||{},{upper:e=>p(e)?e.toUpperCase():e,lower:e=>p(e)?e.toLowerCase():e,capitalize:e=>p(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),k=e.pluralRules||{},b=f(e.missing)?e.missing:null,y=!m(e.missingWarn)&&!r(e.missingWarn)||e.missingWarn,x=!m(e.fallbackWarn)&&!r(e.fallbackWarn)||e.fallbackWarn,w=!!e.fallbackFormat,C=!!e.unresolving,_=f(e.postTranslation)?e.postTranslation:null,v=g(e.processor)?e.processor:null,L=!m(e.warnHtmlMessage)||e.warnHtmlMessage,T=!!e.escapeParameter,P=f(e.messageCompiler)?e.messageCompiler:ue,O=f(e.onWarn)?e.onWarn:c,F=e,N=d(F.__datetimeFormatters)?F.__datetimeFormatters:new Map,$=d(F.__numberFormatters)?F.__numberFormatters:new Map,S=d(F.__meta)?F.__meta:{};me++;return{version:t,cid:me,locale:n,fallbackLocale:o,messages:a,datetimeFormats:u,numberFormats:l,modifiers:h,pluralRules:k,missing:b,missingWarn:y,fallbackWarn:x,fallbackFormat:w,unresolving:C,postTranslation:_,processor:v,warnHtmlMessage:L,escapeParameter:T,messageCompiler:P,onWarn:O,__datetimeFormatters:N,__numberFormatters:$,__meta:S}}function he(e,t){return e instanceof RegExp?e.test(t):e}function ke(e,t){return e instanceof RegExp?e.test(t):e}function ge(e,t,n,r,o){const{missing:c}=e;if(null!==c){const r=c(e,n,t,o);return p(r)?r:t}return t}function be(e,t,n){const r=e;r.__localeChainCache||(r.__localeChainCache=new Map);let o=r.__localeChainCache.get(n);if(!o){o=[];let e=[n];for(;i(e);)e=ye(o,e,t);const c=i(t)?t:g(t)?t.default?t.default:null:t;e=p(c)?[c]:c,i(e)&&ye(o,e,!1),r.__localeChainCache.set(n,o)}return o}function ye(e,t,n){let r=!0;for(let o=0;oe;let ve=Object.create(null);function Le(){ve=Object.create(null)}function Te(e,t={}){{const n=(t.onCacheKey||_e)(e),r=ve[n];if(r)return r;let o=!1;const c=t.onError||E;t.onError=e=>{o=!0,c(e)};const{code:s}=G(e,t),a=new Function(`return ${s}`)();return o?a:ve[n]=a}}function Pe(e){return I(e,null,void 0)}const Oe=()=>"",Fe=e=>f(e);function Ne(e,...t){const{fallbackFormat:r,postTranslation:o,unresolving:c,fallbackLocale:s,messages:u}=e,[l,h]=Se(...t),k=(m(h.missingWarn),m(h.fallbackWarn),m(h.escapeParameter)?h.escapeParameter:e.escapeParameter),g=!!h.resolvedMessage,b=p(h.default)||m(h.default)?m(h.default)?l:h.default:r?l:"",y=r||""!==b,x=p(h.locale)?h.locale:e.locale;k&&function(e){i(e.list)?e.list=e.list.map((e=>p(e)?a(e):e)):d(e.named)&&Object.keys(e.named).forEach((t=>{p(e.named[t])&&(e.named[t]=a(e.named[t]))}))}(h);let[w,C,_]=g?[l,x,u[x]||{}]:function(e,t,n,r,o,c){const{messages:s}=e,a=be(e,r,n);let u,l={},i=null;const m="translate";for(let n=0;n{T=!0}));if(T)return w;const O=function(e,t,n){return t(n)}(0,P,S(function(e,t,r,o){const{modifiers:c,pluralRules:s}=e,a={locale:t,modifiers:c,pluralRules:s,messages:n=>{const o=v(r,n);if(p(o)){let r=!1;const c=$e(e,n,t,o,n,(()=>{r=!0}));return r?Oe:c}return Fe(o)?o:Oe}};e.processor&&(a.processor=e.processor);o.list&&(a.list=o.list);o.named&&(a.named=o.named);n(o.plural)&&(a.pluralIndex=o.plural);return a}(e,C,_,h)));return o?o(O):O}function $e(e,n,r,o,c,s){const{messageCompiler:a,warnHtmlMessage:u}=e;if(Fe(o)){const e=o;return e.locale=e.locale||r,e.key=e.key||n,e}const l=a(o,function(e,n,r,o,c,s){return{warnHtmlMessage:c,onError:e=>{throw s&&s(e),e},onCacheKey:e=>((e,n,r)=>t({l:e,k:n,s:r}))(n,r,e)}}(0,r,c,0,u,s));return l.locale=r,l.key=n,l.source=o,l}function Se(...e){const[t,r,c]=e,a={};if(!p(t)&&!n(t)&&!Fe(t))throw Error(14);const u=n(t)?String(t):(Fe(t),t);return n(r)?a.plural=r:p(r)?a.default=r:g(r)&&!o(r)?a.named=r:i(r)&&(a.list=r),n(c)?a.plural=c:p(c)?a.default=c:g(c)&&s(a,c),[u,a]}function Ie(e,...t){const{datetimeFormats:n,unresolving:r,fallbackLocale:c}=e,{__datetimeFormatters:a}=e,[u,l,i,f]=Ee(...t);m(i.missingWarn);m(i.fallbackWarn);const d=!!i.part,h=p(i.locale)?i.locale:e.locale,k=be(e,c,h);if(!p(u)||""===u)return new Intl.DateTimeFormat(h).format(l);let b,y={},x=null;for(let t=0;t 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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.js new file mode 100644 index 0000000000000000000000000000000000000000..e2d0faa76106c94f7a76886a3d64bf195b193194 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.js @@ -0,0 +1,2814 @@ +/*! + * @intlify/core-base v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var IntlifyCoreBase = (function (exports) { + 'use strict'; + + /** + * Original Utilities + * written by kazuya kawaguchi + */ + const inBrowser = typeof window !== 'undefined'; + let mark; + let measure; + { + 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 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; + function escapeHtml(rawText) { + return rawText + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + 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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; + 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'); + } + + 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; + } + + 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; + } + + /** @internal */ + const errorMessages$1 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` + }; + function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$1)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; + } + /** @internal */ + function defaultOnError(error) { + throw error; + } + + function createPosition(line, column, offset) { + return { line, column, offset }; + } + function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; + } + + const CHAR_SP = ' '; + const CHAR_CR = '\r'; + const CHAR_LF = '\n'; + const CHAR_LS = String.fromCharCode(0x2028); + const CHAR_PS = String.fromCharCode(0x2029); + function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; + } + + const EOF = undefined; + const LITERAL_DELIMITER = "'"; + const ERROR_DOMAIN$1 = 'tokenizer'; + function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; + } + + const ERROR_DOMAIN = 'parser'; + // Backslash backslash, backslash quote, uHHHH, UHHHHHH. + const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; + function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } + } + function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; + } + function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; + } + + function createTransformer(ast, options = {} // eslint-disable-line + ) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; + } + function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } + } + function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here + } + // transform AST + function transform(ast, options = {} // eslint-disable-line + ) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); + } + + function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; + } + function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); + } + function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); + } + function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } + } + function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } + } + function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } + } + // generate code from AST + const generate = (ast, options = {} // eslint-disable-line + ) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; + }; + + function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); + } + + const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' + }; + + 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 + { + 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 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 (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 + 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, { 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) => 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 (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 !! + { + // 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 (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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!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 (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 (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 (!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 (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 (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); + } + } + + exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE; + 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.createCompileError = createCompileError; + exports.createCoreContext = createCoreContext; + exports.createCoreError = createCoreError; + exports.createMessageContext = createMessageContext; + exports.datetime = datetime; + exports.getAdditionalMeta = getAdditionalMeta; + exports.getDevToolsHook = getDevToolsHook; + exports.getLocaleChain = getLocaleChain; + exports.getWarnMessage = getWarnMessage; + exports.handleFlatJson = handleFlatJson; + exports.handleMissing = handleMissing; + exports.initI18nDevTools = initI18nDevTools; + exports.isMessageFunction = isMessageFunction; + exports.isTranslateFallbackWarn = isTranslateFallbackWarn; + exports.isTranslateMissingWarn = isTranslateMissingWarn; + exports.number = number; + exports.parse = parse; + exports.parseDateTimeArgs = parseDateTimeArgs; + exports.parseNumberArgs = parseNumberArgs; + exports.parseTranslateArgs = parseTranslateArgs; + exports.registerMessageCompiler = registerMessageCompiler; + exports.resolveValue = resolveValue; + exports.setAdditionalMeta = setAdditionalMeta; + exports.setDevToolsHook = setDevToolsHook; + exports.translate = translate; + exports.translateDevTools = translateDevTools; + exports.updateFallbackLocale = updateFallbackLocale; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +}({})); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..588e126c249bbcf254a0420835dd75fca841e486 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/dist/core-base.global.prod.js @@ -0,0 +1,6 @@ +/*! + * @intlify/core-base v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var IntlifyCoreBase=function(e){"use strict";const t=/\{([0-9a-zA-Z]+)\}/g;const n=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),r=e=>"number"==typeof e&&isFinite(e),o=e=>"[object RegExp]"===g(e),s=e=>b(e)&&0===Object.keys(e).length;function c(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const a=Object.assign;function u(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const l=Object.prototype.hasOwnProperty;function i(e,t){return l.call(e,t)}const f=Array.isArray,p=e=>"function"==typeof e,m=e=>"string"==typeof e,d=e=>"boolean"==typeof e,h=e=>null!==e&&"object"==typeof e,k=Object.prototype.toString,g=e=>k.call(e),b=e=>"[object Object]"===g(e),y=[];y[0]={w:[0],i:[3,0],"[":[4],o:[7]},y[1]={w:[1],".":[2],"[":[4],o:[7]},y[2]={w:[2],i:[3,0],0:[3,0]},y[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},y[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},y[5]={"'":[4,0],o:8,l:[5,0]},y[6]={'"':[4,0],o:8,l:[6,0]};const x=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function C(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function T(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(x.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}function _(e){const t=[];let n,r,o,s,c,a,u,l=-1,i=0,f=0;const p=[];function m(){const t=e[l+1];if(5===i&&"'"===t||6===i&&'"'===t)return l++,o="\\"+t,p[0](),!0}for(p[0]=()=>{void 0===r?r=o:r+=o},p[1]=()=>{void 0!==r&&(t.push(r),r=void 0)},p[2]=()=>{p[0](),f++},p[3]=()=>{if(f>0)f--,i=4,p[0]();else{if(f=0,void 0===r)return!1;if(r=T(r),!1===r)return!1;p[1]()}};null!==i;)if(l++,n=e[l],"\\"!==n||!m()){if(s=C(n),u=y[i],c=u[s]||u.l||8,8===c)return;if(i=c[0],void 0!==c[1]&&(a=p[c[1]],a&&(o=n,!1===a())))return;if(7===i)return t}}const v=new Map;function L(e,t){if(!h(e))return null;let n=v.get(t);if(n||(n=_(t),n&&v.set(t,n)),!n)return null;const r=n.length;let o=e,s=0;for(;se,P=e=>"",O="text",F=e=>0===e.length?"":e.join(""),N=e=>null==e?"":f(e)||b(e)&&e.toString===k?JSON.stringify(e,null,2):String(e);function S(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function $(e={}){const t=e.locale,n=function(e){const t=r(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(r(e.named.count)||r(e.named.n))?r(e.named.count)?e.named.count:r(e.named.n)?e.named.n:t:t}(e),o=h(e.pluralRules)&&m(t)&&p(e.pluralRules[t])?e.pluralRules[t]:S,s=h(e.pluralRules)&&m(t)&&p(e.pluralRules[t])?S:void 0,c=e.list||[],a=e.named||{};r(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(n,a);function u(t){const n=p(e.messages)?e.messages(t):!!h(e.messages)&&e.messages[t];return n||(e.parent?e.parent.message(t):P)}const l=b(e.processor)&&p(e.processor.normalize)?e.processor.normalize:F,i=b(e.processor)&&p(e.processor.interpolate)?e.processor.interpolate:N,f={list:e=>c[e],named:e=>a[e],plural:e=>e[o(n,e.length,s)],linked:(t,n)=>{const r=u(t)(f);return m(n)?(o=n,e.modifiers?e.modifiers[o]:w)(r):r;var o},message:u,type:b(e.processor)&&m(e.processor.type)?e.processor.type:O,interpolate:i,normalize:l};return f}function E(e,t,n={}){const{domain:r}=n,o=new SyntaxError(String(e));return o.code=e,t&&(o.location=t),o.domain=r,o}function I(e){throw e}function A(e,t,n){const r={start:e,end:t};return null!=n&&(r.source=n),r}const M=" ",W="\n",j=String.fromCharCode(8232),D=String.fromCharCode(8233);function R(e){const t=e;let n=0,r=1,o=1,s=0;const c=e=>"\r"===t[e]&&t[e+1]===W,a=e=>t[e]===D,u=e=>t[e]===j,l=e=>c(e)||(e=>t[e]===W)(e)||a(e)||u(e),i=e=>c(e)||a(e)||u(e)?W:t[e];function f(){return s=0,l(n)&&(r++,o=0),c(n)&&n++,n++,o++,t[n]}return{index:()=>n,line:()=>r,column:()=>o,peekOffset:()=>s,charAt:i,currentChar:()=>i(n),currentPeek:()=>i(n+s),next:f,peek:function(){return c(n+s)&&s++,s++,t[n+s]},reset:function(){n=0,r=1,o=1,s=0},resetPeek:function(e=0){s=e},skipToPeek:function(){const e=n+s;for(;e!==n;)f();s=0}}}const J=void 0;function z(e,t={}){const n=!1!==t.location,r=R(e),o=()=>r.index(),s=()=>{return e=r.line(),t=r.column(),n=r.index(),{line:e,column:t,offset:n};var e,t,n},c=s(),a=o(),u={currentType:14,offset:a,startLoc:c,endLoc:c,lastType:14,lastOffset:a,lastStartLoc:c,lastEndLoc:c,braceNest:0,inLinked:!1,text:""},l=()=>u,{onError:i}=t;function f(e,t,r){e.endLoc=s(),e.currentType=t;const o={type:t};return n&&(o.loc=A(e.startLoc,e.endLoc)),null!=r&&(o.value=r),o}const p=e=>f(e,14);function m(e,t){return e.currentChar()===t?(e.next(),t):(s(),"")}function d(e){let t="";for(;e.currentPeek()===M||e.currentPeek()===W;)t+=e.currentPeek(),e.peek();return t}function h(e){const t=d(e);return e.skipToPeek(),t}function k(e){if(e===J)return!1;const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||95===t}function g(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r=function(e){if(e===J)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function b(e){d(e);const t="|"===e.currentPeek();return e.resetPeek(),t}function y(e,t=!0){const n=(t=!1,r="",o=!1)=>{const s=e.currentPeek();return"{"===s?"%"!==r&&t:"@"!==s&&s?"%"===s?(e.peek(),n(t,"%",!0)):"|"===s?!("%"!==r&&!o)||!(r===M||r===W):s===M?(e.peek(),n(!0,M,o)):s!==W||(e.peek(),n(!0,W,o)):"%"===r||t},r=n();return t&&e.resetPeek(),r}function x(e,t){const n=e.currentChar();return n===J?J:t(n)?(e.next(),n):null}function C(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||t>=48&&t<=57||95===t||36===t}))}function T(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57}))}function _(e){return x(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}))}function v(e){let t="",n="";for(;t=T(e);)n+=t;return n}function L(e){const t=e.currentChar();switch(t){case"\\":case"'":return e.next(),`\\${t}`;case"u":return w(e,t,4);case"U":return w(e,t,6);default:return s(),""}}function w(e,t,n){m(e,t);let r="";for(let t=0;t=1&&s(),e.next(),n=f(t,2,"{"),h(e),t.braceNest++,n;case"}":return t.braceNest>0&&2===t.currentType&&s(),e.next(),n=f(t,3,"}"),t.braceNest--,t.braceNest>0&&h(e),t.inLinked&&0===t.braceNest&&(t.inLinked=!1),n;case"@":return t.braceNest>0&&s(),n=F(e,t)||p(t),t.braceNest=0,n;default:let r=!0,o=!0,c=!0;if(b(e))return t.braceNest>0&&s(),n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(t.braceNest>0&&(5===t.currentType||6===t.currentType||7===t.currentType))return s(),t.braceNest=0,N(e,t);if(r=function(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r=k(e.currentPeek());return e.resetPeek(),r}(e,t))return n=f(t,5,function(e){h(e);let t="",n="";for(;t=C(e);)n+=t;return e.currentChar()===J&&s(),n}(e)),h(e),n;if(o=g(e,t))return n=f(t,6,function(e){h(e);let t="";return"-"===e.currentChar()?(e.next(),t+=`-${v(e)}`):t+=v(e),e.currentChar()===J&&s(),t}(e)),h(e),n;if(c=function(e,t){const{currentType:n}=t;if(2!==n)return!1;d(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,t))return n=f(t,7,function(e){h(e),m(e,"'");let t="",n="";const r=e=>"'"!==e&&e!==W;for(;t=x(e,r);)n+="\\"===t?L(e):t;const o=e.currentChar();return o===W||o===J?(s(),o===W&&(e.next(),m(e,"'")),n):(m(e,"'"),n)}(e)),h(e),n;if(!r&&!o&&!c)return n=f(t,13,function(e){h(e);let t="",n="";const r=e=>"{"!==e&&"}"!==e&&e!==M&&e!==W;for(;t=x(e,r);)n+=t;return n}(e)),s(),h(e),n}return n}function F(e,t){const{currentType:n}=t;let r=null;const o=e.currentChar();switch(8!==n&&9!==n&&12!==n&&10!==n||o!==W&&o!==M||s(),o){case"@":return e.next(),r=f(t,8,"@"),t.inLinked=!0,r;case".":return h(e),e.next(),f(t,9,".");case":":return h(e),e.next(),f(t,10,":");default:return b(e)?(r=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,r):function(e,t){const{currentType:n}=t;if(8!==n)return!1;d(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,t)||function(e,t){const{currentType:n}=t;if(8!==n&&12!==n)return!1;d(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,t)?(h(e),F(e,t)):function(e,t){const{currentType:n}=t;if(9!==n)return!1;d(e);const r=k(e.currentPeek());return e.resetPeek(),r}(e,t)?(h(e),f(t,12,function(e){let t="",n="";for(;t=C(e);)n+=t;return n}(e))):function(e,t){const{currentType:n}=t;if(10!==n)return!1;const r=()=>{const t=e.currentPeek();return"{"===t?k(e.peek()):!("@"===t||"%"===t||"|"===t||":"===t||"."===t||t===M||!t)&&(t===W?(e.peek(),r()):k(t))},o=r();return e.resetPeek(),o}(e,t)?(h(e),"{"===o?O(e,t)||r:f(t,11,function(e){const t=(n=!1,r)=>{const o=e.currentChar();return"{"!==o&&"%"!==o&&"@"!==o&&"|"!==o&&o?o===M?r:o===W?(r+=o,e.next(),t(n,r)):(r+=o,e.next(),t(!0,r)):r};return t(!1,"")}(e))):(8===n&&s(),t.braceNest=0,t.inLinked=!1,N(e,t))}}function N(e,t){let n={type:14};if(t.braceNest>0)return O(e,t)||p(t);if(t.inLinked)return F(e,t)||p(t);const r=e.currentChar();switch(r){case"{":return O(e,t)||p(t);case"}":return s(),e.next(),f(t,3,"}");case"@":return F(e,t)||p(t);default:if(b(e))return n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(y(e))return f(t,0,function(e){const t=n=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?y(e)?(n+=r,e.next(),t(n)):n:"|"===r?n:r===M||r===W?y(e)?(n+=r,e.next(),t(n)):b(e)?n:(n+=r,e.next(),t(n)):(n+=r,e.next(),t(n)):n};return t("")}(e));if("%"===r)return e.next(),f(t,4,"%")}return n}return{nextToken:function(){const{currentType:e,offset:t,startLoc:n,endLoc:c}=u;return u.lastType=e,u.lastOffset=t,u.lastStartLoc=n,u.lastEndLoc=c,u.offset=o(),u.startLoc=s(),r.currentChar()===J?f(u,14):N(r,u)},currentOffset:o,currentPosition:s,context:l}}const H=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function U(e,t,n){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(t||n,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function V(e={}){const t=!1!==e.location,{onError:n}=e;function r(e,n,r){const o={type:e,start:n,end:n};return t&&(o.loc={start:r,end:r}),o}function o(e,n,r,o){e.end=n,o&&(e.type=o),t&&e.loc&&(e.loc.end=r)}function s(e,t){const n=e.context(),s=r(3,n.offset,n.startLoc);return s.value=t,o(s,e.currentOffset(),e.currentPosition()),s}function c(e,t){const n=e.context(),{lastOffset:s,lastStartLoc:c}=n,a=r(5,s,c);return a.index=parseInt(t,10),e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function u(e,t){const n=e.context(),{lastOffset:s,lastStartLoc:c}=n,a=r(4,s,c);return a.key=t,e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function l(e,t){const n=e.context(),{lastOffset:s,lastStartLoc:c}=n,a=r(9,s,c);return a.value=t.replace(H,U),e.nextToken(),o(a,e.currentOffset(),e.currentPosition()),a}function i(e){const t=e.context(),n=r(6,t.offset,t.startLoc);let s=e.nextToken();if(9===s.type){const t=function(e){const t=e.nextToken(),n=e.context(),{lastOffset:s,lastStartLoc:c}=n,a=r(8,s,c);return 12!==t.type?(a.value="",o(a,s,c),{nextConsumeToken:t,node:a}):(null==t.value&&G(t),a.value=t.value||"",o(a,e.currentOffset(),e.currentPosition()),{node:a})}(e);n.modifier=t.node,s=t.nextConsumeToken||e.nextToken()}switch(10!==s.type&&G(s),s=e.nextToken(),2===s.type&&(s=e.nextToken()),s.type){case 11:null==s.value&&G(s),n.key=function(e,t){const n=e.context(),s=r(7,n.offset,n.startLoc);return s.value=t,o(s,e.currentOffset(),e.currentPosition()),s}(e,s.value||"");break;case 5:null==s.value&&G(s),n.key=u(e,s.value||"");break;case 6:null==s.value&&G(s),n.key=c(e,s.value||"");break;case 7:null==s.value&&G(s),n.key=l(e,s.value||"");break;default:const t=e.context(),a=r(7,t.offset,t.startLoc);return a.value="",o(a,t.offset,t.startLoc),n.key=a,o(n,t.offset,t.startLoc),{nextConsumeToken:s,node:n}}return o(n,e.currentOffset(),e.currentPosition()),{node:n}}function f(e){const t=e.context(),n=r(2,1===t.currentType?e.currentOffset():t.offset,1===t.currentType?t.endLoc:t.startLoc);n.items=[];let a=null;do{const t=a||e.nextToken();switch(a=null,t.type){case 0:null==t.value&&G(t),n.items.push(s(e,t.value||""));break;case 6:null==t.value&&G(t),n.items.push(c(e,t.value||""));break;case 5:null==t.value&&G(t),n.items.push(u(e,t.value||""));break;case 7:null==t.value&&G(t),n.items.push(l(e,t.value||""));break;case 8:const r=i(e);n.items.push(r.node),a=r.nextConsumeToken||null}}while(14!==t.currentType&&1!==t.currentType);return o(n,1===t.currentType?t.lastOffset:e.currentOffset(),1===t.currentType?t.lastEndLoc:e.currentPosition()),n}function p(e){const t=e.context(),{offset:n,startLoc:s}=t,c=f(e);return 14===t.currentType?c:function(e,t,n,s){const c=e.context();let a=0===s.items.length;const u=r(1,t,n);u.cases=[],u.cases.push(s);do{const t=f(e);a||(a=0===t.items.length),u.cases.push(t)}while(14!==c.currentType);return o(u,e.currentOffset(),e.currentPosition()),u}(e,n,s,c)}return{parse:function(n){const s=z(n,a({},e)),c=s.context(),u=r(0,c.offset,c.startLoc);return t&&u.loc&&(u.loc.source=n),u.body=p(s),o(u,s.currentOffset(),s.currentPosition()),u}}}function G(e){if(14===e.type)return"EOF";const t=(e.value||"").replace(/\r?\n/gu,"\\n");return t.length>10?t.slice(0,9)+"…":t}function K(e,t){for(let n=0;nn,helper:e=>(n.helpers.add(e),e)}}(e);n.helper("normalize"),e.body&&q(e.body,n);const r=n.context();e.helpers=Array.from(r.helpers)}function Y(e,t){const{helper:n}=e;switch(t.type){case 0:!function(e,t){t.body?Y(e,t.body):e.push("null")}(e,t);break;case 1:!function(e,t){const{helper:n,needIndent:r}=e;if(t.cases.length>1){e.push(`${n("plural")}([`),e.indent(r());const o=t.cases.length;for(let n=0;n{const n=m(t.mode)?t.mode:"normal",r=m(t.filename)?t.filename:"message.intl",o=t.needIndent?t.needIndent:"arrow"!==n,s=e.helpers||[],c=function(e,t){const{filename:n,breakLineCode:r,needIndent:o}=t,s={source:e.loc.source,filename:n,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:o,indentLevel:0};function c(e,t){s.code+=e}function a(e,t=!0){const n=t?r:"";c(o?n+" ".repeat(e):n)}return{context:()=>s,push:c,indent:function(e=!0){const t=++s.indentLevel;e&&a(t)},deindent:function(e=!0){const t=--s.indentLevel;e&&a(t)},newline:function(){a(s.indentLevel)},helper:e=>`_${e}`,needIndent:()=>s.needIndent}}(e,{mode:n,filename:r,sourceMap:!!t.sourceMap,breakLineCode:null!=t.breakLineCode?t.breakLineCode:"arrow"===n?";":"\n",needIndent:o});c.push("normal"===n?"function __msg__ (ctx) {":"(ctx) => {"),c.indent(o),s.length>0&&(c.push(`const { ${s.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),c.newline()),c.push("return "),Y(c,e),c.deindent(o),c.push("}");const{code:a,map:u}=c.context();return{ast:e,code:a,map:u?u.toJSON():void 0}})(r,n)}const Q="i18n:init";let X=null;const ee=te("function:translate");function te(e){return t=>X&&X.emit(e,t)}const ne={0:"Not found '{key}' key in '{locale}' locale messages.",1:"Fall back to translate '{key}' key with '{target}' locale.",2:"Cannot format a number value due to not supported Intl.NumberFormat.",3:"Fall back to number format '{key}' key with '{target}' locale.",4:"Cannot format a date value due to not supported Intl.DateTimeFormat.",5:"Fall back to datetime format '{key}' key with '{target}' locale."};const re="9.1.7";let oe;let se=null;let ce=0;function ae(e,t,n,r,o){const{missing:s}=e;if(null!==s){const r=s(e,n,t,o);return m(r)?r:t}return t}function ue(e,t,n){const r=e;r.__localeChainCache||(r.__localeChainCache=new Map);let o=r.__localeChainCache.get(n);if(!o){o=[];let e=[n];for(;f(e);)e=le(o,e,t);const s=f(t)?t:b(t)?t.default?t.default:null:t;e=m(s)?[s]:s,f(e)&&le(o,e,!1),r.__localeChainCache.set(n,o)}return o}function le(e,t,n){let r=!0;for(let o=0;oe;let me=Object.create(null);const de=()=>"",he=e=>p(e);function ke(e,t,r,o,s,c){const{messageCompiler:a,warnHtmlMessage:u}=e;if(he(o)){const e=o;return e.locale=e.locale||r,e.key=e.key||t,e}const l=a(o,function(e,t,r,o,s,c){return{warnHtmlMessage:s,onError:e=>{throw c&&c(e),e},onCacheKey:e=>((e,t,r)=>n({l:e,k:t,s:r}))(t,r,e)}}(0,r,s,0,u,c));return l.locale=r,l.key=t,l.source=o,l}function ge(...e){const[t,n,o]=e,c={};if(!m(t)&&!r(t)&&!he(t))throw Error(14);const u=r(t)?String(t):(he(t),t);return r(n)?c.plural=n:m(n)?c.default=n:b(n)&&!s(n)?c.named=n:f(n)&&(c.list=n),r(o)?c.plural=o:m(o)?c.default=o:b(o)&&a(c,o),[u,c]}function be(...e){const[t,n,o,s]=e;let c,a={},u={};if(m(t)){if(!/\d{4}-\d{2}-\d{2}(T.*)?/.test(t))throw Error(16);c=new Date(t);try{c.toISOString()}catch(e){throw Error(16)}}else if("[object Date]"===g(t)){if(isNaN(t.getTime()))throw Error(15);c=t}else{if(!r(t))throw Error(14);c=t}return m(n)?a.key=n:b(n)&&(a=n),m(o)?a.locale=o:b(o)&&(u=o),b(s)&&(u=s),[a.key||"",c,a,u]}function ye(...e){const[t,n,o,s]=e;let c={},a={};if(!r(t))throw Error(14);const u=t;return m(n)?c.key=n:b(n)&&(c=n),m(o)?c.locale=o:b(o)&&(a=o),b(s)&&(a=s),[c.key||"",u,c,a]}return e.DEFAULT_MESSAGE_DATA_TYPE=O,e.MISSING_RESOLVE_VALUE="",e.NOT_REOSLVED=-1,e.VERSION=re,e.clearCompileCache=function(){me=Object.create(null)},e.clearDateTimeFormat=function(e,t,n){const r=e;for(const e in n){const n=`${t}__${e}`;r.__datetimeFormatters.has(n)&&r.__datetimeFormatters.delete(n)}},e.clearNumberFormat=function(e,t,n){const r=e;for(const e in n){const n=`${t}__${e}`;r.__numberFormatters.has(n)&&r.__numberFormatters.delete(n)}},e.compileToFunction=function(e,t={}){{const n=(t.onCacheKey||pe)(e),r=me[n];if(r)return r;let o=!1;const s=t.onError||I;t.onError=e=>{o=!0,s(e)};const{code:c}=Z(e,t),a=new Function(`return ${c}`)();return o?a:me[n]=a}},e.createCompileError=E,e.createCoreContext=function(e={}){const t=m(e.version)?e.version:re,n=m(e.locale)?e.locale:"en-US",r=f(e.fallbackLocale)||b(e.fallbackLocale)||m(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:n,s=b(e.messages)?e.messages:{[n]:{}},u=b(e.datetimeFormats)?e.datetimeFormats:{[n]:{}},l=b(e.numberFormats)?e.numberFormats:{[n]:{}},i=a({},e.modifiers||{},{upper:e=>m(e)?e.toUpperCase():e,lower:e=>m(e)?e.toLowerCase():e,capitalize:e=>m(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),k=e.pluralRules||{},g=p(e.missing)?e.missing:null,y=!d(e.missingWarn)&&!o(e.missingWarn)||e.missingWarn,x=!d(e.fallbackWarn)&&!o(e.fallbackWarn)||e.fallbackWarn,C=!!e.fallbackFormat,T=!!e.unresolving,_=p(e.postTranslation)?e.postTranslation:null,v=b(e.processor)?e.processor:null,L=!d(e.warnHtmlMessage)||e.warnHtmlMessage,w=!!e.escapeParameter,P=p(e.messageCompiler)?e.messageCompiler:oe,O=p(e.onWarn)?e.onWarn:c,F=e,N=h(F.__datetimeFormatters)?F.__datetimeFormatters:new Map,S=h(F.__numberFormatters)?F.__numberFormatters:new Map,$=h(F.__meta)?F.__meta:{};return ce++,{version:t,cid:ce,locale:n,fallbackLocale:r,messages:s,datetimeFormats:u,numberFormats:l,modifiers:i,pluralRules:k,missing:g,missingWarn:y,fallbackWarn:x,fallbackFormat:C,unresolving:T,postTranslation:_,processor:v,warnHtmlMessage:L,escapeParameter:w,messageCompiler:P,onWarn:O,__datetimeFormatters:N,__numberFormatters:S,__meta:$}},e.createCoreError=function(e){return E(e,null,void 0)},e.createMessageContext=$,e.datetime=function(e,...t){const{datetimeFormats:n,unresolving:r,fallbackLocale:o}=e,{__datetimeFormatters:c}=e,[u,l,i,f]=be(...t);d(i.missingWarn),d(i.fallbackWarn);const p=!!i.part,h=m(i.locale)?i.locale:e.locale,k=ue(e,o,h);if(!m(u)||""===u)return new Intl.DateTimeFormat(h).format(l);let g,y={},x=null;for(let t=0;tse,e.getDevToolsHook=function(){return X},e.getLocaleChain=ue,e.getWarnMessage=function(e,...n){return function(e,...n){return 1===n.length&&h(n[0])&&(n=n[0]),n&&n.hasOwnProperty||(n={}),e.replace(t,((e,t)=>n.hasOwnProperty(t)?n[t]:""))}(ne[e],...n)},e.handleFlatJson=function e(t){if(!h(t))return t;for(const n in t)if(i(t,n))if(n.includes(".")){const r=n.split("."),o=r.length-1;let s=t;for(let e=0;e{se=e},e.setDevToolsHook=function(e){X=e},e.translate=function(e,...t){const{fallbackFormat:n,postTranslation:o,unresolving:s,fallbackLocale:c,messages:a}=e,[l,i]=ge(...t),k=(d(i.missingWarn),d(i.fallbackWarn),d(i.escapeParameter)?i.escapeParameter:e.escapeParameter),g=!!i.resolvedMessage,b=m(i.default)||d(i.default)?d(i.default)?l:i.default:n?l:"",y=n||""!==b,x=m(i.locale)?i.locale:e.locale;k&&function(e){f(e.list)?e.list=e.list.map((e=>m(e)?u(e):e)):h(e.named)&&Object.keys(e.named).forEach((t=>{m(e.named[t])&&(e.named[t]=u(e.named[t]))}))}(i);let[C,T,_]=g?[l,x,a[x]||{}]:function(e,t,n,r,o,s){const{messages:c}=e,a=ue(e,r,n);let u,l={},i=null;const f="translate";for(let n=0;n{w=!0}));if(w)return C;const O=function(e,t,n){return t(n)}(0,P,$(function(e,t,n,o){const{modifiers:s,pluralRules:c}=e,a={locale:t,modifiers:s,pluralRules:c,messages:r=>{const o=L(n,r);if(m(o)){let n=!1;const s=ke(e,r,t,o,r,(()=>{n=!0}));return n?de:s}return he(o)?o:de}};e.processor&&(a.processor=e.processor);o.list&&(a.list=o.list);o.named&&(a.named=o.named);r(o.plural)&&(a.pluralIndex=o.plural);return a}(e,T,_,i)));return o?o(O):O},e.translateDevTools=ee,e.updateFallbackLocale=function(e,t,n){e.__localeChainCache=new Map,ue(e,n,t)},Object.defineProperty(e,"__esModule",{value:!0}),e}({}); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/index.js new file mode 100644 index 0000000000000000000000000000000000000000..657e0e62184d06a80d63ab01b761b92a3a605bc6 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f507db713f05012ce85ee888766bf8361c050f0b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/core-base/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d50c49b4d0583e2725e9eff0a2c3a24838b4f44a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cb09235df397689df844f819b1f26b58a8092569 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/README.md @@ -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. + +Don’t use in production yet. + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..a54bd6767d91784680cbb3784a8b97519b327f7b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..a54bd6767d91784680cbb3784a8b97519b327f7b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.cjs.prod.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c865394e08d82ef4351849d99982a8842148dba4 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.d.ts @@ -0,0 +1,43 @@ +import type { Emittable } from '@intlify/shared'; + +export declare type AdditionalPayloads = { + meta?: Record; +}; + +export declare type IntlifyDevToolsEmitter = Emittable; + +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; +} + +export { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..3766777d5edcec5ef68910d8e9c9ae3e5ed9b2d5 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/dist/devtools-if.esm-bundler.js @@ -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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c0b03214aa59228ab811b3116b966bf15d6d569 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/package.json new file mode 100644 index 0000000000000000000000000000000000000000..057a3c1967b80447a8bfa620bdee78a02e22ca3a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/devtools-if/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d3f03af1b6c42314256c4e2075c7ad11208e2946 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/README.md @@ -0,0 +1,7 @@ +# @intlify/message-compiler + +The message compiler for intlify project + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..f302e3ee0fe5ce9b045287db2dd84ead94712fbc --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.js @@ -0,0 +1,1400 @@ +/*! + * @intlify/message-compiler 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'); +var sourceMap = require('source-map'); + +/** @internal */ +const errorMessages = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = shared.format((messages || errorMessages)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +const LocationStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 } +}; +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, shared.assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap: sourceMap$1, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + if (_context.map) { + if (node && node.loc && node.loc !== LocationStub) { + addMapping(node.loc.start, getMappingName(node)); + } + advancePositionWithSource(_context, code); + } + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + function addMapping(loc, name) { + _context.map.addMapping({ + name, + source: _context.filename, + original: { + line: loc.line, + column: loc.column - 1 + }, + generated: { + line: _context.line, + column: _context.column - 1 + } + }); + } + if (sourceMap$1) { + _context.map = new sourceMap.SourceMapGenerator(); + _context.map.setSourceContent(filename, _context.source); + } + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = shared.isString(options.mode) ? options.mode : 'normal'; + const filename = shared.isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; +function getMappingName(node) { + switch (node.type) { + case 3 /* Text */: + return node.value; + case 5 /* List */: + return node.index.toString(); + case 4 /* Named */: + return node.key; + case 9 /* Literal */: + return node.value; + case 8 /* LinkedModifier */: + return node.value; + case 7 /* LinkedKey */: + return node.value; + default: + return undefined; + } +} +function advancePositionWithSource(pos, source, numberOfCharacters = source.length) { + let linesCount = 0; + let lastNewLinePos = -1; + for (let i = 0; i < numberOfCharacters; i++) { + if (source.charCodeAt(i) === 10 /* newline char code */) { + linesCount++; + lastNewLinePos = i; + } + } + pos.offset += numberOfCharacters; + pos.line += linesCount; + pos.column = + lastNewLinePos === -1 + ? pos.column + numberOfCharacters + : numberOfCharacters - lastNewLinePos; + return pos; +} + +function baseCompile(source, options = {}) { + const assignedOptions = shared.assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +exports.ERROR_DOMAIN = ERROR_DOMAIN; +exports.LocationStub = LocationStub; +exports.baseCompile = baseCompile; +exports.createCompileError = createCompileError; +exports.createLocation = createLocation; +exports.createParser = createParser; +exports.createPosition = createPosition; +exports.defaultOnError = defaultOnError; +exports.errorMessages = errorMessages; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..a7b579d681560d1c2a2c8b40522ae221e864e40f --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.cjs.prod.js @@ -0,0 +1,1395 @@ +/*! + * @intlify/message-compiler 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'); +var sourceMap = require('source-map'); + +/** @internal */ +const errorMessages = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = code; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +const LocationStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 } +}; +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, shared.assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap: sourceMap$1, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + if (_context.map) { + if (node && node.loc && node.loc !== LocationStub) { + addMapping(node.loc.start, getMappingName(node)); + } + advancePositionWithSource(_context, code); + } + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + function addMapping(loc, name) { + _context.map.addMapping({ + name, + source: _context.filename, + original: { + line: loc.line, + column: loc.column - 1 + }, + generated: { + line: _context.line, + column: _context.column - 1 + } + }); + } + if (sourceMap$1) { + _context.map = new sourceMap.SourceMapGenerator(); + _context.map.setSourceContent(filename, _context.source); + } + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = shared.isString(options.mode) ? options.mode : 'normal'; + const filename = shared.isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; +function getMappingName(node) { + switch (node.type) { + case 3 /* Text */: + return node.value; + case 5 /* List */: + return node.index.toString(); + case 4 /* Named */: + return node.key; + case 9 /* Literal */: + return node.value; + case 8 /* LinkedModifier */: + return node.value; + case 7 /* LinkedKey */: + return node.value; + default: + return undefined; + } +} +function advancePositionWithSource(pos, source, numberOfCharacters = source.length) { + let linesCount = 0; + let lastNewLinePos = -1; + for (let i = 0; i < numberOfCharacters; i++) { + if (source.charCodeAt(i) === 10 /* newline char code */) { + linesCount++; + lastNewLinePos = i; + } + } + pos.offset += numberOfCharacters; + pos.line += linesCount; + pos.column = + lastNewLinePos === -1 + ? pos.column + numberOfCharacters + : numberOfCharacters - lastNewLinePos; + return pos; +} + +function baseCompile(source, options = {}) { + const assignedOptions = shared.assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +exports.ERROR_DOMAIN = ERROR_DOMAIN; +exports.LocationStub = LocationStub; +exports.baseCompile = baseCompile; +exports.createCompileError = createCompileError; +exports.createLocation = createLocation; +exports.createParser = createParser; +exports.createPosition = createPosition; +exports.defaultOnError = defaultOnError; +exports.errorMessages = errorMessages; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd6809843385b7dfdf6c99375ff8aa161690d85c --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.d.ts @@ -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(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 { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..92330a1d12e2338979a7bea4f08dab9441db59d8 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.js @@ -0,0 +1,1348 @@ +/*! + * @intlify/message-compiler v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +/** + * Original Utilities + * written by kazuya kawaguchi + */ +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 assign = Object.assign; +const isString = (val) => typeof val === 'string'; +const isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; + +/** @internal */ +const errorMessages = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +const LocationStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 } +}; +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; + +function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +export { ERROR_DOMAIN, LocationStub, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, errorMessages }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..9ed0329c2b598599c32e9434ae8a13522f6c70a0 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-browser.prod.js @@ -0,0 +1,6 @@ +/*! + * @intlify/message-compiler v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +const e=Object.assign,n=e=>"string"==typeof e,t={0:"Expected token: '{0}'",1:"Invalid token in placeholder: '{0}'",2:"Unterminated single quote in placeholder",3:"Unknown escape sequence: \\{0}",4:"Invalid unicode escape sequence: {0}",5:"Unbalanced closing brace",6:"Unterminated closing brace",7:"Empty placeholder",8:"Not allowed nest placeholder",9:"Invalid linked format",10:"Plural must have messages",11:"Unexpected empty linked modifier",12:"Unexpected empty linked key",13:"Unexpected lexical analysis in token: '{0}'"};function r(e,n,t={}){const{domain:r}=t,c=new SyntaxError(String(e));return c.code=e,n&&(c.location=n),c.domain=r,c}function c(e){throw e}const o={start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}};function u(e,n,t){return{line:e,column:n,offset:t}}function s(e,n,t){const r={start:e,end:n};return null!=t&&(r.source=t),r}const i=String.fromCharCode(8232),a=String.fromCharCode(8233);function l(e){const n=e;let t=0,r=1,c=1,o=0;const u=e=>"\r"===n[e]&&"\n"===n[e+1],s=e=>n[e]===a,l=e=>n[e]===i,f=e=>u(e)||(e=>"\n"===n[e])(e)||s(e)||l(e),d=e=>u(e)||s(e)||l(e)?"\n":n[e];function p(){return o=0,f(t)&&(r++,c=0),u(t)&&t++,t++,c++,n[t]}return{index:()=>t,line:()=>r,column:()=>c,peekOffset:()=>o,charAt:d,currentChar:()=>d(t),currentPeek:()=>d(t+o),next:p,peek:function(){return u(t+o)&&o++,o++,n[t+o]},reset:function(){t=0,r=1,c=1,o=0},resetPeek:function(e=0){o=e},skipToPeek:function(){const e=t+o;for(;e!==t;)p();o=0}}}const f=void 0;function d(e,n={}){const t=!1!==n.location,r=l(e),c=()=>r.index(),o=()=>u(r.line(),r.column(),r.index()),i=o(),a=c(),d={currentType:14,offset:a,startLoc:i,endLoc:i,lastType:14,lastOffset:a,lastStartLoc:i,lastEndLoc:i,braceNest:0,inLinked:!1,text:""},p=()=>d,{onError:k}=n;function h(e,n,r){e.endLoc=o(),e.currentType=n;const c={type:n};return t&&(c.loc=s(e.startLoc,e.endLoc)),null!=r&&(c.value=r),c}const x=e=>h(e,14);function y(e,n){return e.currentChar()===n?(e.next(),n):(o(),"")}function m(e){let n="";for(;" "===e.currentPeek()||"\n"===e.currentPeek();)n+=e.currentPeek(),e.peek();return n}function b(e){const n=m(e);return e.skipToPeek(),n}function L(e){if(e===f)return!1;const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90||95===n}function T(e,n){const{currentType:t}=n;if(2!==t)return!1;m(e);const r=function(e){if(e===f)return!1;const n=e.charCodeAt(0);return n>=48&&n<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function v(e){m(e);const n="|"===e.currentPeek();return e.resetPeek(),n}function P(e,n=!0){const t=(n=!1,r="",c=!1)=>{const o=e.currentPeek();return"{"===o?"%"!==r&&n:"@"!==o&&o?"%"===o?(e.peek(),t(n,"%",!0)):"|"===o?!("%"!==r&&!c)||!(" "===r||"\n"===r):" "===o?(e.peek(),t(!0," ",c)):"\n"!==o||(e.peek(),t(!0,"\n",c)):"%"===r||n},r=t();return n&&e.resetPeek(),r}function C(e,n){const t=e.currentChar();return t===f?f:n(t)?(e.next(),t):null}function O(e){return C(e,(e=>{const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||95===n||36===n}))}function g(e){return C(e,(e=>{const n=e.charCodeAt(0);return n>=48&&n<=57}))}function N(e){return C(e,(e=>{const n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102}))}function w(e){let n="",t="";for(;n=g(e);)t+=n;return t}function $(e){const n=e.currentChar();switch(n){case"\\":case"'":return e.next(),`\\${n}`;case"u":return S(e,n,4);case"U":return S(e,n,6);default:return o(),""}}function S(e,n,t){y(e,n);let r="";for(let n=0;n=1&&o(),e.next(),t=h(n,2,"{"),b(e),n.braceNest++,t;case"}":return n.braceNest>0&&2===n.currentType&&o(),e.next(),t=h(n,3,"}"),n.braceNest--,n.braceNest>0&&b(e),n.inLinked&&0===n.braceNest&&(n.inLinked=!1),t;case"@":return n.braceNest>0&&o(),t=E(e,n)||x(n),n.braceNest=0,t;default:let r=!0,c=!0,u=!0;if(v(e))return n.braceNest>0&&o(),t=h(n,1,I(e)),n.braceNest=0,n.inLinked=!1,t;if(n.braceNest>0&&(5===n.currentType||6===n.currentType||7===n.currentType))return o(),n.braceNest=0,U(e,n);if(r=function(e,n){const{currentType:t}=n;if(2!==t)return!1;m(e);const r=L(e.currentPeek());return e.resetPeek(),r}(e,n))return t=h(n,5,function(e){b(e);let n="",t="";for(;n=O(e);)t+=n;return e.currentChar()===f&&o(),t}(e)),b(e),t;if(c=T(e,n))return t=h(n,6,function(e){b(e);let n="";return"-"===e.currentChar()?(e.next(),n+=`-${w(e)}`):n+=w(e),e.currentChar()===f&&o(),n}(e)),b(e),t;if(u=function(e,n){const{currentType:t}=n;if(2!==t)return!1;m(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,n))return t=h(n,7,function(e){b(e),y(e,"'");let n="",t="";const r=e=>"'"!==e&&"\n"!==e;for(;n=C(e,r);)t+="\\"===n?$(e):n;const c=e.currentChar();return"\n"===c||c===f?(o(),"\n"===c&&(e.next(),y(e,"'")),t):(y(e,"'"),t)}(e)),b(e),t;if(!r&&!c&&!u)return t=h(n,13,function(e){b(e);let n="",t="";const r=e=>"{"!==e&&"}"!==e&&" "!==e&&"\n"!==e;for(;n=C(e,r);)t+=n;return t}(e)),o(),b(e),t}return t}function E(e,n){const{currentType:t}=n;let r=null;const c=e.currentChar();switch(8!==t&&9!==t&&12!==t&&10!==t||"\n"!==c&&" "!==c||o(),c){case"@":return e.next(),r=h(n,8,"@"),n.inLinked=!0,r;case".":return b(e),e.next(),h(n,9,".");case":":return b(e),e.next(),h(n,10,":");default:return v(e)?(r=h(n,1,I(e)),n.braceNest=0,n.inLinked=!1,r):function(e,n){const{currentType:t}=n;if(8!==t)return!1;m(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,n)||function(e,n){const{currentType:t}=n;if(8!==t&&12!==t)return!1;m(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,n)?(b(e),E(e,n)):function(e,n){const{currentType:t}=n;if(9!==t)return!1;m(e);const r=L(e.currentPeek());return e.resetPeek(),r}(e,n)?(b(e),h(n,12,function(e){let n="",t="";for(;n=O(e);)t+=n;return t}(e))):function(e,n){const{currentType:t}=n;if(10!==t)return!1;const r=()=>{const n=e.currentPeek();return"{"===n?L(e.peek()):!("@"===n||"%"===n||"|"===n||":"===n||"."===n||" "===n||!n)&&("\n"===n?(e.peek(),r()):L(n))},c=r();return e.resetPeek(),c}(e,n)?(b(e),"{"===c?A(e,n)||r:h(n,11,function(e){const n=(t=!1,r)=>{const c=e.currentChar();return"{"!==c&&"%"!==c&&"@"!==c&&"|"!==c&&c?" "===c?r:"\n"===c?(r+=c,e.next(),n(t,r)):(r+=c,e.next(),n(!0,r)):r};return n(!1,"")}(e))):(8===t&&o(),n.braceNest=0,n.inLinked=!1,U(e,n))}}function U(e,n){let t={type:14};if(n.braceNest>0)return A(e,n)||x(n);if(n.inLinked)return E(e,n)||x(n);const r=e.currentChar();switch(r){case"{":return A(e,n)||x(n);case"}":return o(),e.next(),h(n,3,"}");case"@":return E(e,n)||x(n);default:if(v(e))return t=h(n,1,I(e)),n.braceNest=0,n.inLinked=!1,t;if(P(e))return h(n,0,function(e){const n=t=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?P(e)?(t+=r,e.next(),n(t)):t:"|"===r?t:" "===r||"\n"===r?P(e)?(t+=r,e.next(),n(t)):v(e)?t:(t+=r,e.next(),n(t)):(t+=r,e.next(),n(t)):t};return n("")}(e));if("%"===r)return e.next(),h(n,4,"%")}return t}return{nextToken:function(){const{currentType:e,offset:n,startLoc:t,endLoc:u}=d;return d.lastType=e,d.lastOffset=n,d.lastStartLoc=t,d.lastEndLoc=u,d.offset=c(),d.startLoc=o(),r.currentChar()===f?h(d,14):U(r,d)},currentOffset:c,currentPosition:o,context:p}}const p="parser",k=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function h(e,n,t){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(n||t,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function x(n={}){const t=!1!==n.location,{onError:r}=n;function c(e,n,r){const c={type:e,start:n,end:n};return t&&(c.loc={start:r,end:r}),c}function o(e,n,r,c){e.end=n,c&&(e.type=c),t&&e.loc&&(e.loc.end=r)}function u(e,n){const t=e.context(),r=c(3,t.offset,t.startLoc);return r.value=n,o(r,e.currentOffset(),e.currentPosition()),r}function s(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(5,r,u);return s.index=parseInt(n,10),e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function i(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(4,r,u);return s.key=n,e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function a(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(9,r,u);return s.value=n.replace(k,h),e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function l(e){const n=e.context(),t=c(6,n.offset,n.startLoc);let r=e.nextToken();if(9===r.type){const n=function(e){const n=e.nextToken(),t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(8,r,u);return 12!==n.type?(s.value="",o(s,r,u),{nextConsumeToken:n,node:s}):(null==n.value&&y(n),s.value=n.value||"",o(s,e.currentOffset(),e.currentPosition()),{node:s})}(e);t.modifier=n.node,r=n.nextConsumeToken||e.nextToken()}switch(10!==r.type&&y(r),r=e.nextToken(),2===r.type&&(r=e.nextToken()),r.type){case 11:null==r.value&&y(r),t.key=function(e,n){const t=e.context(),r=c(7,t.offset,t.startLoc);return r.value=n,o(r,e.currentOffset(),e.currentPosition()),r}(e,r.value||"");break;case 5:null==r.value&&y(r),t.key=i(e,r.value||"");break;case 6:null==r.value&&y(r),t.key=s(e,r.value||"");break;case 7:null==r.value&&y(r),t.key=a(e,r.value||"");break;default:const n=e.context(),u=c(7,n.offset,n.startLoc);return u.value="",o(u,n.offset,n.startLoc),t.key=u,o(t,n.offset,n.startLoc),{nextConsumeToken:r,node:t}}return o(t,e.currentOffset(),e.currentPosition()),{node:t}}function f(e){const n=e.context(),t=c(2,1===n.currentType?e.currentOffset():n.offset,1===n.currentType?n.endLoc:n.startLoc);t.items=[];let r=null;do{const n=r||e.nextToken();switch(r=null,n.type){case 0:null==n.value&&y(n),t.items.push(u(e,n.value||""));break;case 6:null==n.value&&y(n),t.items.push(s(e,n.value||""));break;case 5:null==n.value&&y(n),t.items.push(i(e,n.value||""));break;case 7:null==n.value&&y(n),t.items.push(a(e,n.value||""));break;case 8:const c=l(e);t.items.push(c.node),r=c.nextConsumeToken||null}}while(14!==n.currentType&&1!==n.currentType);return o(t,1===n.currentType?n.lastOffset:e.currentOffset(),1===n.currentType?n.lastEndLoc:e.currentPosition()),t}function p(e){const n=e.context(),{offset:t,startLoc:r}=n,u=f(e);return 14===n.currentType?u:function(e,n,t,r){const u=e.context();let s=0===r.items.length;const i=c(1,n,t);i.cases=[],i.cases.push(r);do{const n=f(e);s||(s=0===n.items.length),i.cases.push(n)}while(14!==u.currentType);return o(i,e.currentOffset(),e.currentPosition()),i}(e,t,r,u)}return{parse:function(r){const u=d(r,e({},n)),s=u.context(),i=c(0,s.offset,s.startLoc);return t&&i.loc&&(i.loc.source=r),i.body=p(u),o(i,u.currentOffset(),u.currentPosition()),i}}}function y(e){if(14===e.type)return"EOF";const n=(e.value||"").replace(/\r?\n/gu,"\\n");return n.length>10?n.slice(0,9)+"…":n}function m(e,n){for(let t=0;tt,helper:e=>(t.helpers.add(e),e)}}(e);t.helper("normalize"),e.body&&b(e.body,t);const r=t.context();e.helpers=Array.from(r.helpers)}function T(e,n){const{helper:t}=e;switch(n.type){case 0:!function(e,n){n.body?T(e,n.body):e.push("null")}(e,n);break;case 1:!function(e,n){const{helper:t,needIndent:r}=e;if(n.cases.length>1){e.push(`${t("plural")}([`),e.indent(r());const c=n.cases.length;for(let t=0;t{const r=n(t.mode)?t.mode:"normal",c=n(t.filename)?t.filename:"message.intl",o=t.needIndent?t.needIndent:"arrow"!==r,u=e.helpers||[],s=function(e,n){const{filename:t,breakLineCode:r,needIndent:c}=n,o={source:e.loc.source,filename:t,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:c,indentLevel:0};function u(e,n){o.code+=e}function s(e,n=!0){const t=n?r:"";u(c?t+" ".repeat(e):t)}return{context:()=>o,push:u,indent:function(e=!0){const n=++o.indentLevel;e&&s(n)},deindent:function(e=!0){const n=--o.indentLevel;e&&s(n)},newline:function(){s(o.indentLevel)},helper:e=>`_${e}`,needIndent:()=>o.needIndent}}(e,{mode:r,filename:c,sourceMap:!!t.sourceMap,breakLineCode:null!=t.breakLineCode?t.breakLineCode:"arrow"===r?";":"\n",needIndent:o});s.push("normal"===r?"function __msg__ (ctx) {":"(ctx) => {"),s.indent(o),u.length>0&&(s.push(`const { ${u.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),s.newline()),s.push("return "),T(s,e),s.deindent(o),s.push("}");const{code:i,map:a}=s.context();return{ast:e,code:i,map:a?a.toJSON():void 0}})(o,c)}export{p as ERROR_DOMAIN,o as LocationStub,v as baseCompile,r as createCompileError,s as createLocation,x as createParser,u as createPosition,c as defaultOnError,t as errorMessages}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..1b20eec4a9573c228c82ab29e8c9b0b6ddb96d63 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.esm-bundler.js @@ -0,0 +1,1329 @@ +/*! + * @intlify/message-compiler v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import { format, assign, isString } from '@intlify/shared'; + +/** @internal */ +const errorMessages = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = (process.env.NODE_ENV !== 'production') + ? format((messages || errorMessages)[code] || '', ...(args || [])) + : code; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +const LocationStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 } +}; +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + if ((process.env.NODE_ENV !== 'production')) { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; + +function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +export { ERROR_DOMAIN, LocationStub, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, errorMessages }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.js new file mode 100644 index 0000000000000000000000000000000000000000..05cc6aa96469349ec0ceb2079b8793e4a55489d6 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.js @@ -0,0 +1,1365 @@ +/*! + * @intlify/message-compiler v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var IntlifyMessageCompiler = (function (exports) { + 'use strict'; + + /** + * Original Utilities + * written by kazuya kawaguchi + */ + 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 assign = Object.assign; + const isString = (val) => typeof val === 'string'; + const isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; + + /** @internal */ + const errorMessages = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` + }; + function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; + } + /** @internal */ + function defaultOnError(error) { + throw error; + } + + const LocationStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 } + }; + function createPosition(line, column, offset) { + return { line, column, offset }; + } + function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; + } + + const CHAR_SP = ' '; + const CHAR_CR = '\r'; + const CHAR_LF = '\n'; + const CHAR_LS = String.fromCharCode(0x2028); + const CHAR_PS = String.fromCharCode(0x2029); + function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; + } + + const EOF = undefined; + const LITERAL_DELIMITER = "'"; + const ERROR_DOMAIN$1 = 'tokenizer'; + function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; + } + + const ERROR_DOMAIN = 'parser'; + // Backslash backslash, backslash quote, uHHHH, UHHHHHH. + const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; + function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } + } + function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; + } + function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; + } + + function createTransformer(ast, options = {} // eslint-disable-line + ) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; + } + function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } + } + function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here + } + // transform AST + function transform(ast, options = {} // eslint-disable-line + ) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); + } + + function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; + } + function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); + } + function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); + } + function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } + } + function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } + } + function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } + } + // generate code from AST + const generate = (ast, options = {} // eslint-disable-line + ) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; + }; + + function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); + } + + exports.ERROR_DOMAIN = ERROR_DOMAIN; + exports.LocationStub = LocationStub; + exports.baseCompile = baseCompile; + exports.createCompileError = createCompileError; + exports.createLocation = createLocation; + exports.createParser = createParser; + exports.createPosition = createPosition; + exports.defaultOnError = defaultOnError; + exports.errorMessages = errorMessages; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +}({})); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..dde2351ad8bf9ee432cba86bbf4e68b7d6f74fa1 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/dist/message-compiler.global.prod.js @@ -0,0 +1,6 @@ +/*! + * @intlify/message-compiler v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var IntlifyMessageCompiler=function(e){"use strict";const n=Object.assign,t=e=>"string"==typeof e,r={0:"Expected token: '{0}'",1:"Invalid token in placeholder: '{0}'",2:"Unterminated single quote in placeholder",3:"Unknown escape sequence: \\{0}",4:"Invalid unicode escape sequence: {0}",5:"Unbalanced closing brace",6:"Unterminated closing brace",7:"Empty placeholder",8:"Not allowed nest placeholder",9:"Invalid linked format",10:"Plural must have messages",11:"Unexpected empty linked modifier",12:"Unexpected empty linked key",13:"Unexpected lexical analysis in token: '{0}'"};function c(e,n,t={}){const{domain:r}=t,c=new SyntaxError(String(e));return c.code=e,n&&(c.location=n),c.domain=r,c}function o(e,n,t){return{line:e,column:n,offset:t}}function u(e,n,t){const r={start:e,end:n};return null!=t&&(r.source=t),r}const s=" ",i="\n",a=String.fromCharCode(8232),l=String.fromCharCode(8233);function f(e){const n=e;let t=0,r=1,c=1,o=0;const u=e=>"\r"===n[e]&&n[e+1]===i,s=e=>n[e]===l,f=e=>n[e]===a,d=e=>u(e)||(e=>n[e]===i)(e)||s(e)||f(e),p=e=>u(e)||s(e)||f(e)?i:n[e];function k(){return o=0,d(t)&&(r++,c=0),u(t)&&t++,t++,c++,n[t]}return{index:()=>t,line:()=>r,column:()=>c,peekOffset:()=>o,charAt:p,currentChar:()=>p(t),currentPeek:()=>p(t+o),next:k,peek:function(){return u(t+o)&&o++,o++,n[t+o]},reset:function(){t=0,r=1,c=1,o=0},resetPeek:function(e=0){o=e},skipToPeek:function(){const e=t+o;for(;e!==t;)k();o=0}}}const d=void 0;function p(e,n={}){const t=!1!==n.location,r=f(e),c=()=>r.index(),a=()=>o(r.line(),r.column(),r.index()),l=a(),p=c(),k={currentType:14,offset:p,startLoc:l,endLoc:l,lastType:14,lastOffset:p,lastStartLoc:l,lastEndLoc:l,braceNest:0,inLinked:!1,text:""},h=()=>k,{onError:x}=n;function y(e,n,r){e.endLoc=a(),e.currentType=n;const c={type:n};return t&&(c.loc=u(e.startLoc,e.endLoc)),null!=r&&(c.value=r),c}const m=e=>y(e,14);function b(e,n){return e.currentChar()===n?(e.next(),n):(a(),"")}function L(e){let n="";for(;e.currentPeek()===s||e.currentPeek()===i;)n+=e.currentPeek(),e.peek();return n}function P(e){const n=L(e);return e.skipToPeek(),n}function v(e){if(e===d)return!1;const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90||95===n}function T(e,n){const{currentType:t}=n;if(2!==t)return!1;L(e);const r=function(e){if(e===d)return!1;const n=e.charCodeAt(0);return n>=48&&n<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function C(e){L(e);const n="|"===e.currentPeek();return e.resetPeek(),n}function O(e,n=!0){const t=(n=!1,r="",c=!1)=>{const o=e.currentPeek();return"{"===o?"%"!==r&&n:"@"!==o&&o?"%"===o?(e.peek(),t(n,"%",!0)):"|"===o?!("%"!==r&&!c)||!(r===s||r===i):o===s?(e.peek(),t(!0,s,c)):o!==i||(e.peek(),t(!0,i,c)):"%"===r||n},r=t();return n&&e.resetPeek(),r}function g(e,n){const t=e.currentChar();return t===d?d:n(t)?(e.next(),t):null}function N(e){return g(e,(e=>{const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||95===n||36===n}))}function w(e){return g(e,(e=>{const n=e.charCodeAt(0);return n>=48&&n<=57}))}function S(e){return g(e,(e=>{const n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102}))}function $(e){let n="",t="";for(;n=w(e);)t+=n;return t}function I(e){const n=e.currentChar();switch(n){case"\\":case"'":return e.next(),`\\${n}`;case"u":return E(e,n,4);case"U":return E(e,n,6);default:return a(),""}}function E(e,n,t){b(e,n);let r="";for(let n=0;n=1&&a(),e.next(),t=y(n,2,"{"),P(e),n.braceNest++,t;case"}":return n.braceNest>0&&2===n.currentType&&a(),e.next(),t=y(n,3,"}"),n.braceNest--,n.braceNest>0&&P(e),n.inLinked&&0===n.braceNest&&(n.inLinked=!1),t;case"@":return n.braceNest>0&&a(),t=_(e,n)||m(n),n.braceNest=0,t;default:let r=!0,c=!0,o=!0;if(C(e))return n.braceNest>0&&a(),t=y(n,1,A(e)),n.braceNest=0,n.inLinked=!1,t;if(n.braceNest>0&&(5===n.currentType||6===n.currentType||7===n.currentType))return a(),n.braceNest=0,M(e,n);if(r=function(e,n){const{currentType:t}=n;if(2!==t)return!1;L(e);const r=v(e.currentPeek());return e.resetPeek(),r}(e,n))return t=y(n,5,function(e){P(e);let n="",t="";for(;n=N(e);)t+=n;return e.currentChar()===d&&a(),t}(e)),P(e),t;if(c=T(e,n))return t=y(n,6,function(e){P(e);let n="";return"-"===e.currentChar()?(e.next(),n+=`-${$(e)}`):n+=$(e),e.currentChar()===d&&a(),n}(e)),P(e),t;if(o=function(e,n){const{currentType:t}=n;if(2!==t)return!1;L(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,n))return t=y(n,7,function(e){P(e),b(e,"'");let n="",t="";const r=e=>"'"!==e&&e!==i;for(;n=g(e,r);)t+="\\"===n?I(e):n;const c=e.currentChar();return c===i||c===d?(a(),c===i&&(e.next(),b(e,"'")),t):(b(e,"'"),t)}(e)),P(e),t;if(!r&&!c&&!o)return t=y(n,13,function(e){P(e);let n="",t="";const r=e=>"{"!==e&&"}"!==e&&e!==s&&e!==i;for(;n=g(e,r);)t+=n;return t}(e)),a(),P(e),t}return t}function _(e,n){const{currentType:t}=n;let r=null;const c=e.currentChar();switch(8!==t&&9!==t&&12!==t&&10!==t||c!==i&&c!==s||a(),c){case"@":return e.next(),r=y(n,8,"@"),n.inLinked=!0,r;case".":return P(e),e.next(),y(n,9,".");case":":return P(e),e.next(),y(n,10,":");default:return C(e)?(r=y(n,1,A(e)),n.braceNest=0,n.inLinked=!1,r):function(e,n){const{currentType:t}=n;if(8!==t)return!1;L(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,n)||function(e,n){const{currentType:t}=n;if(8!==t&&12!==t)return!1;L(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,n)?(P(e),_(e,n)):function(e,n){const{currentType:t}=n;if(9!==t)return!1;L(e);const r=v(e.currentPeek());return e.resetPeek(),r}(e,n)?(P(e),y(n,12,function(e){let n="",t="";for(;n=N(e);)t+=n;return t}(e))):function(e,n){const{currentType:t}=n;if(10!==t)return!1;const r=()=>{const n=e.currentPeek();return"{"===n?v(e.peek()):!("@"===n||"%"===n||"|"===n||":"===n||"."===n||n===s||!n)&&(n===i?(e.peek(),r()):v(n))},c=r();return e.resetPeek(),c}(e,n)?(P(e),"{"===c?U(e,n)||r:y(n,11,function(e){const n=(t=!1,r)=>{const c=e.currentChar();return"{"!==c&&"%"!==c&&"@"!==c&&"|"!==c&&c?c===s?r:c===i?(r+=c,e.next(),n(t,r)):(r+=c,e.next(),n(!0,r)):r};return n(!1,"")}(e))):(8===t&&a(),n.braceNest=0,n.inLinked=!1,M(e,n))}}function M(e,n){let t={type:14};if(n.braceNest>0)return U(e,n)||m(n);if(n.inLinked)return _(e,n)||m(n);const r=e.currentChar();switch(r){case"{":return U(e,n)||m(n);case"}":return a(),e.next(),y(n,3,"}");case"@":return _(e,n)||m(n);default:if(C(e))return t=y(n,1,A(e)),n.braceNest=0,n.inLinked=!1,t;if(O(e))return y(n,0,function(e){const n=t=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?O(e)?(t+=r,e.next(),n(t)):t:"|"===r?t:r===s||r===i?O(e)?(t+=r,e.next(),n(t)):C(e)?t:(t+=r,e.next(),n(t)):(t+=r,e.next(),n(t)):t};return n("")}(e));if("%"===r)return e.next(),y(n,4,"%")}return t}return{nextToken:function(){const{currentType:e,offset:n,startLoc:t,endLoc:o}=k;return k.lastType=e,k.lastOffset=n,k.lastStartLoc=t,k.lastEndLoc=o,k.offset=c(),k.startLoc=a(),r.currentChar()===d?y(k,14):M(r,k)},currentOffset:c,currentPosition:a,context:h}}const k="parser",h=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function x(e,n,t){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(n||t,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function y(e={}){const t=!1!==e.location,{onError:r}=e;function c(e,n,r){const c={type:e,start:n,end:n};return t&&(c.loc={start:r,end:r}),c}function o(e,n,r,c){e.end=n,c&&(e.type=c),t&&e.loc&&(e.loc.end=r)}function u(e,n){const t=e.context(),r=c(3,t.offset,t.startLoc);return r.value=n,o(r,e.currentOffset(),e.currentPosition()),r}function s(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(5,r,u);return s.index=parseInt(n,10),e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function i(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(4,r,u);return s.key=n,e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function a(e,n){const t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(9,r,u);return s.value=n.replace(h,x),e.nextToken(),o(s,e.currentOffset(),e.currentPosition()),s}function l(e){const n=e.context(),t=c(6,n.offset,n.startLoc);let r=e.nextToken();if(9===r.type){const n=function(e){const n=e.nextToken(),t=e.context(),{lastOffset:r,lastStartLoc:u}=t,s=c(8,r,u);return 12!==n.type?(s.value="",o(s,r,u),{nextConsumeToken:n,node:s}):(null==n.value&&m(n),s.value=n.value||"",o(s,e.currentOffset(),e.currentPosition()),{node:s})}(e);t.modifier=n.node,r=n.nextConsumeToken||e.nextToken()}switch(10!==r.type&&m(r),r=e.nextToken(),2===r.type&&(r=e.nextToken()),r.type){case 11:null==r.value&&m(r),t.key=function(e,n){const t=e.context(),r=c(7,t.offset,t.startLoc);return r.value=n,o(r,e.currentOffset(),e.currentPosition()),r}(e,r.value||"");break;case 5:null==r.value&&m(r),t.key=i(e,r.value||"");break;case 6:null==r.value&&m(r),t.key=s(e,r.value||"");break;case 7:null==r.value&&m(r),t.key=a(e,r.value||"");break;default:const n=e.context(),u=c(7,n.offset,n.startLoc);return u.value="",o(u,n.offset,n.startLoc),t.key=u,o(t,n.offset,n.startLoc),{nextConsumeToken:r,node:t}}return o(t,e.currentOffset(),e.currentPosition()),{node:t}}function f(e){const n=e.context(),t=c(2,1===n.currentType?e.currentOffset():n.offset,1===n.currentType?n.endLoc:n.startLoc);t.items=[];let r=null;do{const n=r||e.nextToken();switch(r=null,n.type){case 0:null==n.value&&m(n),t.items.push(u(e,n.value||""));break;case 6:null==n.value&&m(n),t.items.push(s(e,n.value||""));break;case 5:null==n.value&&m(n),t.items.push(i(e,n.value||""));break;case 7:null==n.value&&m(n),t.items.push(a(e,n.value||""));break;case 8:const c=l(e);t.items.push(c.node),r=c.nextConsumeToken||null}}while(14!==n.currentType&&1!==n.currentType);return o(t,1===n.currentType?n.lastOffset:e.currentOffset(),1===n.currentType?n.lastEndLoc:e.currentPosition()),t}function d(e){const n=e.context(),{offset:t,startLoc:r}=n,u=f(e);return 14===n.currentType?u:function(e,n,t,r){const u=e.context();let s=0===r.items.length;const i=c(1,n,t);i.cases=[],i.cases.push(r);do{const n=f(e);s||(s=0===n.items.length),i.cases.push(n)}while(14!==u.currentType);return o(i,e.currentOffset(),e.currentPosition()),i}(e,t,r,u)}return{parse:function(r){const u=p(r,n({},e)),s=u.context(),i=c(0,s.offset,s.startLoc);return t&&i.loc&&(i.loc.source=r),i.body=d(u),o(i,u.currentOffset(),u.currentPosition()),i}}}function m(e){if(14===e.type)return"EOF";const n=(e.value||"").replace(/\r?\n/gu,"\\n");return n.length>10?n.slice(0,9)+"…":n}function b(e,n){for(let t=0;tt,helper:e=>(t.helpers.add(e),e)}}(e);t.helper("normalize"),e.body&&L(e.body,t);const r=t.context();e.helpers=Array.from(r.helpers)}function v(e,n){const{helper:t}=e;switch(n.type){case 0:!function(e,n){n.body?v(e,n.body):e.push("null")}(e,n);break;case 1:!function(e,n){const{helper:t,needIndent:r}=e;if(n.cases.length>1){e.push(`${t("plural")}([`),e.indent(r());const c=n.cases.length;for(let t=0;t{const r=t(n.mode)?n.mode:"normal",c=t(n.filename)?n.filename:"message.intl",o=n.needIndent?n.needIndent:"arrow"!==r,u=e.helpers||[],s=function(e,n){const{filename:t,breakLineCode:r,needIndent:c}=n,o={source:e.loc.source,filename:t,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:c,indentLevel:0};function u(e,n){o.code+=e}function s(e,n=!0){const t=n?r:"";u(c?t+" ".repeat(e):t)}return{context:()=>o,push:u,indent:function(e=!0){const n=++o.indentLevel;e&&s(n)},deindent:function(e=!0){const n=--o.indentLevel;e&&s(n)},newline:function(){s(o.indentLevel)},helper:e=>`_${e}`,needIndent:()=>o.needIndent}}(e,{mode:r,filename:c,sourceMap:!!n.sourceMap,breakLineCode:null!=n.breakLineCode?n.breakLineCode:"arrow"===r?";":"\n",needIndent:o});s.push("normal"===r?"function __msg__ (ctx) {":"(ctx) => {"),s.indent(o),u.length>0&&(s.push(`const { ${u.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),s.newline()),s.push("return "),v(s,e),s.deindent(o),s.push("}");const{code:i,map:a}=s.context();return{ast:e,code:i,map:a?a.toJSON():void 0}})(o,c)},e.createCompileError=c,e.createLocation=u,e.createParser=y,e.createPosition=o,e.defaultOnError=function(e){throw e},e.errorMessages=r,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c4b50446f3de2330daf70e0b84bcf1704bc8857c --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/package.json new file mode 100644 index 0000000000000000000000000000000000000000..99194339f06b7d6e9b34a20f004a1c6796084c27 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-compiler/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1e913577a938d3c07fa1c11d2b2f84dfd9c55dc2 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/README.md @@ -0,0 +1,7 @@ +# @intlify/message-resolver + +The locale message resolver for intlify project + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..fb100c14ef89018e96e5f5f18ef7b0e5b2e9509b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..fb100c14ef89018e96e5f5f18ef7b0e5b2e9509b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.cjs.prod.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc6245bfbcca5de8aeb472b723ed3a37dc5af9ac --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.d.ts @@ -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 { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..bda5f1ada77696af549559673c67d048853f1007 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/dist/message-resolver.esm-bundler.js @@ -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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/index.js new file mode 100644 index 0000000000000000000000000000000000000000..654efef3fa8f629576cc87df49a8c198d303508e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/package.json new file mode 100644 index 0000000000000000000000000000000000000000..40d4060f0752ee0930c7792279fc0793532cf057 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/message-resolver/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..872d78579f744a6608b3de33497723ae4de36d91 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/README.md @@ -0,0 +1,7 @@ +# @intlify/runtime + +The runtime for intlify project + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..c835b9366aa5943490a18d82b9e0f107c069f1f1 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..c835b9366aa5943490a18d82b9e0f107c069f1f1 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.cjs.prod.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd4e68087fa4e2003b75317ae973ec98a846c41f --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.d.ts @@ -0,0 +1,95 @@ +import { Path } from '@intlify/message-resolver'; + +export declare type CoreMissingType = 'translate' | 'datetime format' | 'number format'; + +export declare function createMessageContext(options?: MessageContextOptions): MessageContext; + +export declare const DEFAULT_MESSAGE_DATA_TYPE = "text"; + +declare type ExtractToStringFunction = T[ExtractToStringKey]; + +declare type ExtractToStringKey = Extract; + +/** @VueI18nGeneral */ +export declare type FallbackLocale = Locale | Locale[] | { + [locale in string]: Locale[]; +} | false; + +/** @VueI18nGeneral */ +export declare type LinkedModifiers = { + [key: string]: LinkedModify; +}; + +export declare type LinkedModify = (value: T) => MessageType; + +/** @VueI18nGeneral */ +export declare type Locale = string; + +export declare interface MessageContext { + list(index: number): unknown; + named(key: string): unknown; + plural(messages: T[]): T; + linked(key: Path, modifier?: string): MessageType; + message(key: Path): MessageFunction; + type: string; + interpolate: MessageInterpolate; + normalize: MessageNormalize; +} + +export declare interface MessageContextOptions { + parent?: MessageContext; + locale?: string; + list?: unknown[]; + named?: NamedValue; + modifiers?: LinkedModifiers; + pluralIndex?: number; + pluralRules?: PluralizationRules; + messages?: MessageFunctions | MessageResolveFunction; + processor?: MessageProcessor; +} + +export declare type MessageFunction = MessageFunctionCallable | MessageFunctionInternal; + +export declare type MessageFunctionCallable = (ctx: MessageContext) => MessageType; + +export declare type MessageFunctionInternal = { + (ctx: MessageContext): MessageType; + key?: string; + locale?: string; + source?: string; +}; + +export declare type MessageFunctions = Record>; + +export declare type MessageInterpolate = (val: unknown) => MessageType; + +export declare type MessageNormalize = (values: MessageType[]) => MessageType; + +export declare interface MessageProcessor { + type?: string; + interpolate?: MessageInterpolate; + normalize?: MessageNormalize; +} + +export declare type MessageResolveFunction = (key: string) => MessageFunction; + +export declare type MessageType = T extends string ? string : StringConvertable; + +/** @VueI18nGeneral */ +export declare type NamedValue = T & Record; + +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 = ExtractToStringKey extends never ? unknown : ExtractToStringFunction extends (...args: any) => string ? T : unknown; + +export { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..ca2c3be733143b3fb82d6ef856d0e30176714a4e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/dist/runtime.esm-bundler.js @@ -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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e444d857ccd30c4f5c7d76ab53d217a12b7aa669 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc3a654bd4d75fcc5854400cb9c5f8333ab09d80 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/runtime/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5cf05564664758147efa5040cfe92b132a895ec7 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/README.md @@ -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) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..728cd3f9076a5da757b7371a010323985dcde22f --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.js @@ -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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..f24ba77dd7f4e4e835192b2cf61694ab6118802c --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.cjs.prod.js @@ -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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82c7b1aa07359cc2a547977bd231d2af138c6150 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.d.ts @@ -0,0 +1,145 @@ + +export declare const assign: { + (target: T, source: U): T & U; + (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; + (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>(): Emittable; + +/** + * Event emitter interface + */ +export declare interface Emittable = {}> { + /** + * A map of event names of registered event handlers + */ + events: EventHandlerMap; + /** + * 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(event: Key | '*', handler: EventHandler | WildcardEventHandler): 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(event: Key | '*', handler: EventHandler | WildcardEventHandler): 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(event: Key, payload?: Events[keyof Events]): void; +} + +export declare function escapeHtml(rawText: string): string; + +/** + * Event handler + */ +export declare type EventHandler = (payload?: T) => void; + +/** + * Event handler list + */ +export declare type EventHandlerList = Array>; + +/** + * Event handler map + */ +export declare type EventHandlerMap> = Map | WildcardEventHandlerList>; + +/** + * 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, 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; + +export declare const isPlainObject: (val: unknown) => val is object; + +export declare const isPromise: (val: unknown) => val is Promise; + +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> = (event: keyof T, payload?: T[keyof T]) => void; + +/** + * Wildcard event handler list + */ +export declare type WildcardEventHandlerList> = Array>; + +export { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..28373ab4aaaad2c750910f1445b54097dd87b9d3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/dist/shared.esm-bundler.js @@ -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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a2ee43e36fd17c71f84bb78b9554c78f6476846a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/package.json new file mode 100644 index 0000000000000000000000000000000000000000..22b1accce03bb7999888c880a3fcb7a7635c07f9 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/shared/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d50c49b4d0583e2725e9eff0a2c3a24838b4f44a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6df4fe77c549a418733fd474f1ffa601f3e66413 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/README.md @@ -0,0 +1,7 @@ +# @intlify/vue-devtools + +The Vue DevTools I/F package for intlify project + +## :copyright: License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..f1ba772d52a7218a6b700729aa247e5865905fdb --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..f1ba772d52a7218a6b700729aa247e5865905fdb --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.cjs.prod.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1fc5e7e7cdf9f2957b10f773ae3b2526fbc339b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.d.ts @@ -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; + +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; + +export declare const VueDevToolsPlaceholders: Record; + +export declare const VueDevToolsTimelineColors: Record; + +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 { } diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..183d6a58822499b7db3541ee00a5cbb7ace6a59e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/dist/vue-devtools.esm-bundler.js @@ -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 }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/index.js new file mode 100644 index 0000000000000000000000000000000000000000..25d6f033cb53d68873a179a4f5d6e57e324a1904 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/index.js @@ -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') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c114858ccd26db9bbe02a5bbc3238b7fa836ce13 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@intlify/vue-devtools/package.json @@ -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 +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7ff345a6ad57206eca4c6f1575cadc5d578d130 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.d.ts @@ -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; + 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; + getComponentName(instance: ComponentInstance): Promise; + getComponentInstances(app: App): Promise; + highlightElement(instance: ComponentInstance): any; + unhighlightElement(): any; +} +export interface AppRecord { + id: number; + name: string; + instanceMap: Map; + rootInstance: ComponentInstance; +} +export interface TimelineLayerOptions { + id: string; + label: string; + color: number; + skipScreenshots?: boolean; + groupsOnly?: boolean; + ignoreNoDurationGroups?: boolean; + screenshotOverlayRender?: (event: TimelineEvent & ScreenshotOverlayEvent, ctx: ScreenshotOverlayRenderContext) => ScreenshotOverlayRenderResult | Promise; +} +export interface ScreenshotOverlayEvent { + layerId: string; + renderMeta: any; +} +export interface ScreenshotOverlayRenderContext { + screenshot: ScreenshotData; + events: (TimelineEvent & 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 { + 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; + }[]; +} +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)[]; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/api.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42638c08c90b0f807bea307468d8b77050b48777 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.d.ts @@ -0,0 +1 @@ +export declare type App = any; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/app.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e822a07a8edca02dfd1a4cd1d6353e40e60a475 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.d.ts @@ -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; + }[]; + /** internal */ + _reviveId?: number; + }; +}; +export declare type ComponentState = ComponentStateBase | ComponentPropState | ComponentCustomState; +export interface ComponentDevtoolsOptions { + hide?: boolean; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/component.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7567403c7b4cf92f5efa1f00a10728ece794283e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.d.ts @@ -0,0 +1,5 @@ +import { AppRecord } from './api'; +export interface Context { + currentTab: string; + currentAppRecord: AppRecord; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/context.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e7de4bcb2aaef5dbfd4f7802011de5efb506790 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.d.ts @@ -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; + [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 = (payload: TPayload, ctx: TContext) => void | Promise; +export interface Hookable { + transformCall(handler: HookHandler): any; + getAppRecordName(handler: HookHandler): any; + getAppRootInstance(handler: HookHandler): any; + registerApplication(handler: HookHandler): any; + walkComponentTree(handler: HookHandler): any; + visitComponentTree(handler: HookHandler): any; + walkComponentParents(handler: HookHandler): any; + inspectComponent(handler: HookHandler): any; + getComponentBounds(handler: HookHandler): any; + getComponentName(handler: HookHandler): any; + getComponentInstances(handler: HookHandler): any; + getElementComponent(handler: HookHandler): any; + getComponentRootElements(handler: HookHandler): any; + editComponentState(handler: HookHandler): any; + getComponentDevtoolsOptions(handler: HookHandler): any; + getComponentRenderCode(handler: HookHandler): any; + inspectTimelineEvent(handler: HookHandler): any; + timelineCleared(handler: HookHandler): any; + getInspectorTree(handler: HookHandler): any; + getInspectorState(handler: HookHandler): any; + editInspectorState(handler: HookHandler): any; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/hooks.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b681795492eeb3f692c5a711208836081115789 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.d.ts @@ -0,0 +1,6 @@ +export * from './api'; +export * from './app'; +export * from './component'; +export * from './context'; +export * from './hooks'; +export * from './util'; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.js new file mode 100644 index 0000000000000000000000000000000000000000..915e610e874d70639fab299f90eeb732ebdf1f8e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/index.js @@ -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); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c437e51ebdd005a91396325e4f7ec0bdac0cb43 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.d.ts @@ -0,0 +1,4 @@ +export declare type ID = number | string; +export interface WithId { + id: ID; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/api/util.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46ea15d3805b96e0511dacc63ff2740c98e057ea --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.d.ts @@ -0,0 +1 @@ +export declare const HOOK_SETUP = "devtools-plugin:setup"; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.js new file mode 100644 index 0000000000000000000000000000000000000000..e22545a344a55e9d452e180d6bcd46b5c4cf68b1 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/const.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HOOK_SETUP = void 0; +exports.HOOK_SETUP = 'devtools-plugin:setup'; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..738376b566833ec70ee78ccfeb628868a9d3fc8d --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.d.ts @@ -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 {}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.js new file mode 100644 index 0000000000000000000000000000000000000000..4593f0e0e0db1438d048c2b765cf3a59f39ab9f2 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/env.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a97ffe2922413c32e7635ea523ee8c7204e84269 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.d.ts @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..67c6338459103559f93adfefde031c54d0f0c63a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/cjs/index.js @@ -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; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/api.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/api.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/app.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/app.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/component.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/component.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/context.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/context.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/hooks.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/hooks.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5b681795492eeb3f692c5a711208836081115789 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/index.js @@ -0,0 +1,6 @@ +export * from './api'; +export * from './app'; +export * from './component'; +export * from './context'; +export * from './hooks'; +export * from './util'; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/util.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/api/util.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/const.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/const.js new file mode 100644 index 0000000000000000000000000000000000000000..0582ba27f68cb4e53939f0934a8bdff7d3f4d8b1 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/const.js @@ -0,0 +1 @@ +export const HOOK_SETUP = 'devtools-plugin:setup'; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/env.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/env.js new file mode 100644 index 0000000000000000000000000000000000000000..b45dbdbe4c6cb8ec3b3f01e7543b12d274327708 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/env.js @@ -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 + : {}; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f0360145608464cd63f022ddbd9b2fd7706e7e9e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/lib/esm/index.js @@ -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 + }); + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b07999acf05a1aaa9e7b874c956ac0e573852cdd --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/@vue/devtools-api/package.json @@ -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" + } +} \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/CHANGELOG.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..3a8c066c66b1dee2e3cf793eb0d2f6ced8a06dee --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/CHANGELOG.md @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ed1b7cf27e97e136918e87ad7bb33baf169f0171 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fea4beb193f3fc95410de89f811639a18a014747 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/README.md @@ -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 + + + +-------------------------------------------------------------------------------- + + + + + +## 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) + + + +## 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] } +``` diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.debug.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000000000000000000000000000000000000..aad0620d70e16717ec338fc1d332279739e0d97c --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * 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. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 name of Google Inc. nor the names of its + * 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 + * OWNER 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * 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`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * 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. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer 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. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to 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 referrenced 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 file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 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. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * 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. + * - 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: + * + * - 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. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * 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. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * 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. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSx1QkFBZTtBQUNmO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7QUFHQTtBQUNBOztBQUVBO0FBQ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JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfZ2VuZXJhdGVTb3VyY2VzQ29udGVudChhU291cmNlcywgYVNvdXJjZVJvb3QpIHtcbiAgICByZXR1cm4gYVNvdXJjZXMubWFwKGZ1bmN0aW9uIChzb3VyY2UpIH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lbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9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LmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..b4eb08742598ff797f613e9bf15e55ce70c9fb10 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * 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. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 name of Google Inc. nor the names of its + * 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 + * OWNER 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * 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`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * 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. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer 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. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to 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 referrenced 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 file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 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. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * 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. + * - 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: + * + * - 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. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * 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. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * 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. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.min.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000000000000000000000000000000000000..c7c72dad8b59de41f3c932da18a5e5577ba76cb8 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/array-set.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd5c81cae66fa6401f871ac7fb02e96fdb9c213 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64-vlq.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000000000000000000000000000000000000..612b404018ece911ab71fc0a8db326d16e6b1287 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 name of Google Inc. nor the names of its + * 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 + * OWNER 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. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000000000000000000000000000000000000..8aa86b30264363990334a7df0aa0d0c9cc1aecfc --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/binary-search.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000000000000000000000000000000000000..010ac941e1568d59c89b67cb649051a14608ee79 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.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 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/mapping-list.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000000000000000000000000000000000000..06d1274a025a8a30879f31c9c6703a14f79f73b9 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/quick-sort.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000000000000000000000000000000000000..6a7caadbbdbea1865cfb947cb21fbf0c8da1289a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-consumer.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b99d1da7feac7c5345af8945ed047c7c054c0ba --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * 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`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * 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. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer 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. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to 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 referrenced 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 file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 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. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * 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. + * - 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: + * + * - 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. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * 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. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * 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. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-generator.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..508bcfbbc936da21673108f7ace72a0af6081664 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * 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. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-node.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcdbe385d2c0d333bcd62648ca700f13f9d3181 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * 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. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/util.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/util.js new file mode 100644 index 0000000000000000000000000000000000000000..3ca92e56f2a8cf086821031145ed60c53f8e9ab2 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/package.json new file mode 100644 index 0000000000000000000000000000000000000000..24663417e7ac507877c002c77dc056757cc34ecc --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f972b0cfbf389901ed4392a635f91d5cf2bf0e0 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..bc88fe820c87a217d27eb010281fe39b71163835 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/LICENSE b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ff3ea6a4ee8b483f1e72c5a0d31638a69f5f3 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/LICENSE @@ -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. diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/README.md b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d28b035a94378bf08f8b526b2fc276dca9ccaf86 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/README.md @@ -0,0 +1,74 @@ +# vue-i18n + +Internationalization plugin for Vue.js + +## Which dist file to use? + +### From CDN or without a Bundler + +- **`vue-i18n(.runtime).global(.prod).js`**: + + - For direct use via ` + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = vue.getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = shared.isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = shared.isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (shared.isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (shared.isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + { + shared.warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = shared.assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + vue.onMounted(() => { + }, target); + vue.onUnmounted(() => { + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = vue.isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +// register message compiler at vue-i18n +coreBase.registerMessageCompiler(coreBase.compileToFunction); +// NOTE: experimental !! +{ + const target = shared.getGlobalThis(); + target.__INTLIFY__ = true; + coreBase.setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); +} + +exports.DatetimeFormat = DatetimeFormat; +exports.NumberFormat = NumberFormat; +exports.Translation = Translation; +exports.VERSION = VERSION; +exports.createI18n = createI18n; +exports.useI18n = useI18n; +exports.vTDirective = vTDirective; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.cjs.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.cjs.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..6b75f7890fc247a0c2d84ff607b410b34c486b13 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.cjs.prod.js @@ -0,0 +1,1685 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var coreBase = require('@intlify/core-base'); +var vue = require('vue'); +var shared = require('@intlify/shared'); + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +const VERSION = '9.1.7'; + +function createI18nError(code, ...args) { + return coreBase.createCompileError(code, null, undefined); +} + +const TransrateVNodeSymbol = shared.makeSymbol('__transrateVNode'); +const DatetimePartsSymbol = shared.makeSymbol('__datetimeParts'); +const NumberPartsSymbol = shared.makeSymbol('__numberParts'); +shared.makeSymbol('__enableEmitter'); +shared.makeSymbol('__disableEmitter'); +const SetPluralRulesSymbol = shared.makeSymbol('__setPluralRules'); +shared.makeSymbol('__intlifyMeta'); +let composerID = 0; +function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, vue.getCurrentInstance() || undefined, type); + }); +} +function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = shared.isPlainObject(messages) + ? messages + : shared.isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (shared.isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (shared.hasOwn(ret, key)) { + coreBase.handleFlatJson(ret[key]); + } + } + } + return ret; +} +const isNotObjectOrIsArray = (val) => !shared.isObject(val) || shared.isArray(val); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (shared.hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } +} +/** + * Create composer interface factory + * + * @internal + */ +function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = shared.isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : shared.isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : shared.isString(options.fallbackLocale) || + shared.isArray(options.fallbackLocale) || + shared.isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = vue.ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = vue.ref(shared.isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = vue.ref(shared.isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : shared.isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = shared.isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = shared.isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = shared.isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : shared.isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return coreBase.createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: shared.isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: shared.isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: shared.isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + coreBase.updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = vue.computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = vue.computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + coreBase.updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = vue.computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = vue.computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = vue.computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return shared.isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + { + ret = fn(_context); + } + if (shared.isNumber(ret) && ret === coreBase.NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => coreBase.translate(context, ...args), () => coreBase.parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => shared.isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !shared.isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, shared.assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => coreBase.datetime(context, ...args), () => coreBase.parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => coreBase.MISSING_RESOLVE_VALUE, val => shared.isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => coreBase.number(context, ...args), () => coreBase.parseNumberArgs(...args), 'number format', root => root.n(...args), () => coreBase.MISSING_RESOLVE_VALUE, val => shared.isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => shared.isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = coreBase.translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => coreBase.parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => shared.isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => coreBase.number(context, ...args), () => coreBase.parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => shared.isString(val) || shared.isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => coreBase.datetime(context, ...args), () => coreBase.parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => shared.isString(val) || shared.isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = shared.isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return coreBase.resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = coreBase.getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = coreBase.resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + coreBase.clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = shared.assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + coreBase.clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + coreBase.clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = shared.assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + coreBase.clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + vue.watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + coreBase.updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + vue.watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + coreBase.updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + coreBase.updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + return composer; +} + +/** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ +function convertComposerOptions(options) { + const locale = shared.isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = shared.isString(options.fallbackLocale) || + shared.isArray(options.fallbackLocale) || + shared.isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = shared.isFunction(options.missing) ? options.missing : undefined; + const missingWarn = shared.isBoolean(options.silentTranslationWarn) || + shared.isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = shared.isBoolean(options.silentFallbackWarn) || + shared.isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = shared.isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = shared.isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = shared.isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = shared.isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = shared.isBoolean(options.sync) ? options.sync : true; + let messages = options.messages; + if (shared.isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + shared.assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; +} +/** + * create VueI18n interface factory + * + * @internal + */ +function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return shared.isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = shared.isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return shared.isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = shared.isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + return true; + }, + set preserveDirectiveContent(val) { + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!shared.isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (shared.isString(arg2)) { + options.locale = arg2; + } + else if (shared.isArray(arg2)) { + list = arg2; + } + else if (shared.isPlainObject(arg2)) { + named = arg2; + } + if (shared.isArray(arg3)) { + list = arg3; + } + else if (shared.isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!shared.isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (shared.isString(arg2)) { + options.locale = arg2; + } + else if (shared.isNumber(arg2)) { + options.plural = arg2; + } + else if (shared.isArray(arg2)) { + list = arg2; + } + else if (shared.isPlainObject(arg2)) { + named = arg2; + } + if (shared.isString(arg3)) { + options.locale = arg3; + } + else if (shared.isArray(arg3)) { + list = arg3; + } + else if (shared.isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + return vueI18n; +} + +const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } +}; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: shared.assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => shared.isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = shared.isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = shared.assign({}, attrs); + // prettier-ignore + return shared.isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : shared.isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; + } +}; +function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } +} + +function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (shared.isString(props.format)) { + options.key = props.format; + } + else if (shared.isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (shared.isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? shared.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (shared.isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (shared.isString(parts)) { + children = [parts]; + } + const assignedAttrs = shared.assign({}, attrs); + // prettier-ignore + return shared.isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : shared.isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; +} + +const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' +]; +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: shared.assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } +}; + +const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' +]; +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: shared.assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } +}; + +function getComposer$1(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } +} +function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$1(i18n, instance.$); + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; +} +function parseValue(value) { + if (shared.isString(value)) { + return { path: value }; + } + else if (shared.isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } +} +function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (shared.isString(locale)) { + options.locale = locale; + } + if (shared.isNumber(choice)) { + options.plural = choice; + } + if (shared.isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; +} + +function apply(app, i18n, ...options) { + const pluginOptions = shared.isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = shared.isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); +} + +// supports compatibility for legacy vue-i18n APIs +function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + }, + beforeUnmount() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; +} +function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = shared.isBoolean(options.legacy) + ? options.legacy + : true; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = shared.makeSymbol(''); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __legacyMode + ? 'legacy' + : 'composition' + ; + }, + // install plugin + async install(app, ...options) { + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; +} +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = vue.getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = shared.isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = shared.isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (shared.isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (shared.isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = shared.assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + vue.onMounted(() => { + }, target); + vue.onUnmounted(() => { + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = vue.isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +// register message compiler at vue-i18n +coreBase.registerMessageCompiler(coreBase.compileToFunction); + +exports.DatetimeFormat = DatetimeFormat; +exports.NumberFormat = NumberFormat; +exports.Translation = Translation; +exports.VERSION = VERSION; +exports.createI18n = createI18n; +exports.useI18n = useI18n; +exports.vTDirective = vTDirective; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.d.ts b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca59f0a506f27bbce113d4deef44a717a41b831a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.d.ts @@ -0,0 +1,3302 @@ +import type { App } from 'vue'; +import type { ComponentInternalInstance } from 'vue'; +import type { ComputedRef } from '@vue/reactivity'; +import { DateTimeOptions } from '@intlify/core-base'; +import { FallbackLocale } from '@intlify/core-base'; +import { DateTimeFormat as IntlDateTimeFormat } from '@intlify/core-base'; +import { DateTimeFormats as IntlDateTimeFormats } from '@intlify/core-base'; +import { FormatMatcher as IntlFormatMatcher } from '@intlify/core-base'; +import { LocaleMatcher as IntlLocaleMatcher } from '@intlify/core-base'; +import { NumberFormat as IntlNumberFormat } from '@intlify/core-base'; +import { NumberFormats as IntlNumberFormats } from '@intlify/core-base'; +import { LinkedModifiers } from '@intlify/core-base'; +import { Locale } from '@intlify/core-base'; +import { LocaleMessageArray } from '@intlify/core-base'; +import { LocaleMessageDictionary } from '@intlify/core-base'; +import { LocaleMessages } from '@intlify/core-base'; +import { LocaleMessageValue } from '@intlify/core-base'; +import { MessageFunction } from '@intlify/core-base'; +import { MessageFunctions } from '@intlify/core-base'; +import { NamedValue } from '@intlify/core-base'; +import { NumberOptions } from '@intlify/core-base'; +import type { ObjectDirective } from 'vue'; +import { Path } from '@intlify/core-base'; +import { PathValue } from '@intlify/core-base'; +import { PluralizationRule } from '@intlify/core-base'; +import type { PluralizationRules } from '@intlify/core-base'; +import { PostTranslationHandler } from '@intlify/core-base'; +import type { RenderFunction } from 'vue'; +import type { SetupContext } from 'vue'; +import { TranslateOptions } from '@intlify/core-base'; +import type { VNode } from 'vue'; +import type { WritableComputedRef } from '@vue/reactivity'; + +/** + * BaseFormat Props for Components that is offered Vue I18n + * + * @remarks + * The interface definitions of the underlying props of components such as Translation, DatetimeFormat, and NumberFormat. + * + * @VueI18nComponent + */ +export declare interface BaseFormatProps { + /** + * @remarks + * Used to wrap the content that is distribute in the slot. If omitted, the slot content is treated as Fragments. + * + * You can specify a string-based tag name, such as `p`, or the object for which the component is defined. + */ + tag?: string | object; + /** + * @remarks + * Specifies the locale to be used for the component. + * + * If specified, the global scope or the locale of the parent scope of the target component will not be overridden and the specified locale will be used. + */ + locale?: Locale; + /** + * @remarks + * Specifies the scope to be used in the target component. + * + * You can specify either `global` or `parent`. + * + * If `global` is specified, global scope is used, else then `parent` is specified, the scope of the parent of the target component is used. + * + * If the parent is a global scope, the global scope is used, if it's a local scope, the local scope is used. + */ + scope?: ComponetI18nScope; + /** + * @remarks + * A composer instance with an existing scope. + * + * This option takes precedence over the `scope` option. + */ + i18n?: Composer; +} + +export declare type Choice = number; + +declare type ComponentInstanceCreatedListener = (target: VueI18n, global: VueI18n) => void; + +export declare type ComponetI18nScope = Exclude; + +/** + * Composer interfaces + * + * @remarks + * This is the interface for being used for Vue 3 Composition API. + * + * @VueI18nComposition + */ +export declare interface Composer { + /** + * @remarks + * Instance ID. + */ + id: number; + /** + * @remarks + * The current locale this Composer instance is using. + * + * If the locale contains a territory and a dialect, this locale contains an implicit fallback. + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + locale: WritableComputedRef; + /** + * @remarks + * The current fallback locales this Composer instance is using. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + fallbackLocale: WritableComputedRef; + /** + * @remarks + * Whether inherit the root level locale to the component localization locale. + * + * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) + */ + inheritLocale: boolean; + /** + * @remarks + * The list of available locales in `messages` in lexical order. + */ + readonly availableLocales: Locale[]; + /** + * @remarks + * The locale messages of localization. + * + * @VueI18nSee [Getting Started](../guide/) + */ + readonly messages: ComputedRef; + /** + * @remarks + * The datetime formats of localization. + * + * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) + */ + readonly datetimeFormats: ComputedRef; + /** + * @remarks + * The number formats of localization. + * + * @VueI18nSee [Number Formatting](../guide/essentials/number) + */ + readonly numberFormats: ComputedRef; + /** + * @remarks + * Custom Modifiers for linked messages. + * + * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) + */ + readonly modifiers: LinkedModifiers; + /** + * @remarks + * A set of rules for word pluralization + * + * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) + */ + readonly pluralRules: PluralizationRules; + /** + * @remarks + * Whether this composer instance is global or not + */ + readonly isGlobal: boolean; + /** + * @remarks + * Whether suppress warnings outputted when localization fails. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + missingWarn: boolean | RegExp; + /** + * @remarks + * Whether suppress fall back warnings when localization fails. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + fallbackWarn: boolean | RegExp; + /** + * @remarks + * Whether to fall back to root level (global scope) localization when localization fails. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + fallbackRoot: boolean; + /** + * @remarks + * Whether suppress warnings when falling back to either `fallbackLocale` or root. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + fallbackFormat: boolean; + /** + * @remarks + * Whether to allow the use locale messages of HTML formatting. + * + * If you set `false`, will check the locale messages on the Composer instance. + * + * If you are specified `true`, a warning will be output at console. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) + */ + warnHtmlMessage: boolean; + /** + * @remarks + * Whether interpolation parameters are escaped before the message is translated. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + */ + escapeParameter: boolean; + /** + * Locale message translation + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. + * + * If not, then it’s translated with global scope locale messages. + * + * @param key - A target locale message key + * + * @returns Translated message + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + t(key: Path | number): string; + /** + * Locale message translation for plurals + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, return a pluralized translation message. + * + * You can also suppress the warning, when the translation missing according to the options. + * + * About details of options, see the {@link TranslateOptions}. + * + * @param key - A target locale message key + * @param plural - Which plural string to get. 1 returns the first one. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + */ + t(key: Path | number, plural: number, options?: TranslateOptions): string; + /** + * Locale message translation for missing default message + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, if no translation was found, return a default message. + * + * You can also suppress the warning, when the translation missing according to the options. + * + * About details of options, see the {@link TranslateOptions}. + * + * @param key - A target locale message key + * @param defaultMsg - A default message to return if no translation was found + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + */ + t(key: Path | number, defaultMsg: string, options?: TranslateOptions): string; + /** + * Locale message translation for list interpolations + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list. + * + * You can also suppress the warning, when the translation missing according to the options. + * + * About details of options, see the {@link TranslateOptions}. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + t(key: Path | number, list: unknown[], options?: TranslateOptions): string; + /** + * Locale message translation for list interpolations and plurals + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list, and return a pluralized translation message. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param plural - Which plural string to get. 1 returns the first one. + * + * @returns Translated message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + t(key: Path | number, list: unknown[], plural: number): string; + /** + * Locale message translation for list interpolations and missing default message + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list, and if no translation was found, return a default message. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param defaultMsg - A default message to return if no translation was found + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + t(key: Path | number, list: unknown[], defaultMsg: string): string; + /** + * Locale message translation for named interpolations + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token. + * + * You can also suppress the warning, when the translation missing according to the options. + * + * About details of options, see the {@link TranslateOptions}. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + t(key: Path | number, named: NamedValue, options?: TranslateOptions): string; + /** + * Locale message translation for named interpolations and plurals + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token, and return a pluralized translation message. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param plural - Which plural string to get. 1 returns the first one. + * + * @returns Translated message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + t(key: Path | number, named: NamedValue, plural: number): string; + /** + * Locale message translation for named interpolations and plurals + * + * @remarks + * Overloaded `t`. About details, see the [t](composition#t-key) details. + * + * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token, and if no translation was found, return a default message. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param defaultMsg - A default message to return if no translation was found + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + t(key: Path | number, named: NamedValue, defaultMsg: string): string; + /* Excluded from this release type: t */ + /** + * Resolve locale message translation + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. + * + * If not, then it’s translated with global scope locale messages. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * + * @returns Translated message + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + rt(message: MessageFunction | Message): string; + /** + * Resolve locale message translation for plurals + * + * @remarks + * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. + * + * In this overloaded `rt`, return a pluralized translation message. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param plural - Which plural string to get. 1 returns the first one. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + */ + rt(message: MessageFunction | Message, plural: number, options?: TranslateOptions): string; + /** + * Resolve locale message translation for list interpolations + * + * @remarks + * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. + * + * In this overloaded `rt`, return a pluralized translation message. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param list - A values of list interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + rt(message: MessageFunction | Message, list: unknown[], options?: TranslateOptions): string; + /** + * Resolve locale message translation for named interpolations + * + * @remarks + * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. + * + * In this overloaded `rt`, for each placeholder x, the locale messages should contain a `{x}` token. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param named - A values of named interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + rt(message: MessageFunction | Message, named: NamedValue, options?: TranslateOptions): string; + /* Excluded from this release type: rt */ + /** + * Datetime formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope datetime formats than global scope datetime formats. + * + * If not, then it’s formatted with global scope datetime formats. + * + * @param value - A value, timestamp number or `Date` instance or ISO 8601 string + * + * @returns Formatted value + * + * @VueI18nSee [Datetime formatting](../guide/essentials/datetime) + */ + d(value: number | Date | string): string; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](composition#d-value) details. + * + * In this overloaded `d`, format in datetime format for a key registered in datetime formats. + * + * @param value - A value, timestamp number or `Date` instance or ISO 8601 string + * @param key - A key of datetime formats + * + * @returns Formatted value + */ + d(value: number | Date | string, key: string): string; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](composition#d-value) details. + * + * In this overloaded `d`, format in datetime format for a key registered in datetime formats at target locale + * + * @param value - A value, timestamp number or `Date` instance or ISO 8601 string + * @param key - A key of datetime formats + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Formatted value + */ + d(value: number | Date | string, key: string, locale: Locale): string; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](composition#d-value) details. + * + * You can also suppress the warning, when the formatting missing according to the options. + * + * About details of options, see the {@link DateTimeOptions}. + * + * @param value - A value, timestamp number or `Date` instance or ISO 8601 string + * @param options - Additional {@link DateTimeOptions | options} for datetime formatting + * + * @returns Formatted value + */ + d(value: number | Date | string, options: DateTimeOptions): string; + /* Excluded from this release type: d */ + /** + * Number Formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope datetime formats than global scope datetime formats. + * + * If not, then it’s formatted with global scope number formats. + * + * @param value - A number value + * + * @returns Formatted value + * + * @VueI18nSee [Number formatting](../guide/essentials/number) + */ + n(value: number): string; + /** + * Number Formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](composition#n-value) details. + * + * In this overloaded `n`, format in number format for a key registered in number formats. + * + * @param value - A number value + * @param key - A key of number formats + * + * @returns Formatted value + */ + n(value: number, key: string): string; + /** + * Number Formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](composition#n-value) details. + * + * In this overloaded `n`, format in number format for a key registered in number formats at target locale. + * + * @param value - A number value + * @param key - A key of number formats + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Formatted value + */ + n(value: number, key: string, locale: Locale): string; + /** + * + * Number Formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](composition#n-value) details. + * + * You can also suppress the warning, when the formatting missing according to the options. + * + * About details of options, see the {@link NumberOptions}. + * + * @param value - A number value + * @param options - Additional {@link NumberOptions | options} for number formatting + * + * @returns Formatted value + */ + n(value: number, options: NumberOptions): string; + /* Excluded from this release type: n */ + /** + * Translation locale message exist + * + * @remarks + * whether do exist locale message on Composer instance [messages](composition#messages). + * + * If you specified `locale`, check the locale messages of `locale`. + * + * @param key - A target locale message key + * @param locale - A locale, it will be used over than global scope or local scope + * + * @returns If found locale message, `true`, else `false` + */ + te(key: Path, locale?: Locale): boolean; + /** + * Locale messages getter + * + * @remarks + * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. + * + * Based on the current `locale`, locale messages will be returned from Composer instance messages. + * + * If you change the `locale`, the locale messages returned will also correspond to the locale. + * + * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with [fallbacking](../guide/essentials/fallback). + * + * @VueI18nWarning + * You need to use `rt` for the locale message returned by `tm`. see the [rt](composition#rt-message) details. + * + * @example + * template block: + * ```html + *
+ * + *
+ * ``` + * script block: + * ```js + * import { defineComponent } from 'vue + * import { useI18n } from 'vue-i18n' + * + * export default defineComponent({ + * setup() { + * const { rt, tm } = useI18n({ + * messages: { + * en: { + * contents: [ + * { + * title: 'Title1', + * // ... + * paragraphs: [ + * // ... + * ] + * } + * ] + * } + * } + * // ... + * }) + * // ... + * return { ... , rt, tm } + * } + * }) + * ``` + * + * @param key - A target locale message key + * + * @return Locale messages + */ + tm(key: Path): LocaleMessageValue | {}; + /** + * Get locale message + * + * @remarks + * get locale message from Composer instance [messages](composition#messages). + * + * @param locale - A target locale + * + * @returns Locale messages + */ + getLocaleMessage(locale: Locale): LocaleMessageDictionary; + /** + * Set locale message + * + * @remarks + * Set locale message to Composer instance [messages](composition#messages). + * + * @param locale - A target locale + * @param message - A message + */ + setLocaleMessage(locale: Locale, message: LocaleMessageDictionary): void; + /** + * Merge locale message + * + * @remarks + * Merge locale message to Composer instance [messages](composition#messages). + * + * @param locale - A target locale + * @param message - A message + */ + mergeLocaleMessage(locale: Locale, message: LocaleMessageDictionary): void; + /** + * Get datetime format + * + * @remarks + * get datetime format from Composer instance [datetimeFormats](composition#datetimeformats). + * + * @param locale - A target locale + * + * @returns Datetime format + */ + getDateTimeFormat(locale: Locale): IntlDateTimeFormat; + /** + * Set datetime format + * + * @remarks + * Set datetime format to Composer instance [datetimeFormats](composition#datetimeformats). + * + * @param locale - A target locale + * @param format - A target datetime format + */ + setDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; + /** + * Merge datetime format + * + * @remarks + * Merge datetime format to Composer instance [datetimeFormats](composition#datetimeformats). + * + * @param locale - A target locale + * @param format - A target datetime format + */ + mergeDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; + /** + * Get number format + * + * @remarks + * get number format from Composer instance [numberFormats](composition#numberFormats). + * + * @param locale - A target locale + * + * @returns Number format + */ + getNumberFormat(locale: Locale): IntlNumberFormat; + /** + * Set number format + * + * @remarks + * Set number format to Composer instance [numberFormats](composition#numberFormats). + * + * @param locale - A target locale + * @param format - A target number format + */ + setNumberFormat(locale: Locale, format: IntlNumberFormat): void; + /** + * Merge number format + * + * @remarks + * Merge number format to Composer instance [numberFormats](composition#numberFormats). + * + * @param locale - A target locale + * @param format - A target number format + */ + mergeNumberFormat(locale: Locale, format: IntlNumberFormat): void; + /** + * Get post translation handler + * + * @returns {@link PostTranslationHandler} + * + * @VueI18nSee [missing](composition#posttranslation) + */ + getPostTranslationHandler(): PostTranslationHandler | null; + /** + * Set post translation handler + * + * @param handler - A {@link PostTranslationHandler} + * + * @VueI18nSee [missing](composition#posttranslation) + */ + setPostTranslationHandler(handler: PostTranslationHandler | null): void; + /** + * Get missing handler + * + * @returns {@link MissingHandler} + * + * @VueI18nSee [missing](composition#missing) + */ + getMissingHandler(): MissingHandler | null; + /** + * Set missing handler + * + * @param handler - A {@link MissingHandler} + * + * @VueI18nSee [missing](composition#missing) + */ + setMissingHandler(handler: MissingHandler | null): void; +} + +/** + * Composer additional options for `useI18n` + * + * @remarks + * `ComposerAdditionalOptions` is extend for {@link ComposerOptions}, so you can specify these options. + * + * @VueI18nSee [useI18n](composition#usei18n) + * + * @VueI18nComposition + */ +export declare interface ComposerAdditionalOptions { + useScope?: I18nScope; +} + +/** + * Composer Options + * + * @remarks + * This is options to create composer. + * + * @VueI18nComposition + */ +export declare interface ComposerOptions { + /** + * @remarks + * The locale of localization. + * + * If the locale contains a territory and a dialect, this locale contains an implicit fallback. + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + * + * @defaultValue `'en-US'` + */ + locale?: Locale; + /** + * @remarks + * The locale of fallback localization. + * + * For more complex fallback definitions see fallback. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue The default `'en-US'` for the `locale` if it's not specified, or it's `locale` value + */ + fallbackLocale?: FallbackLocale; + /** + * @remarks + * Whether inheritance the root level locale to the component localization locale. + * + * If `false`, regardless of the root level locale, localize for each component locale. + * + * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) + * + * @defaultValue `true` + */ + inheritLocale?: boolean; + /** + * @remarks + * The locale messages of localization. + * + * @VueI18nSee [Getting Started](../guide/) + * + * @defaultValue `{}` + */ + messages?: LocaleMessages; + /** + * @remarks + * Allow use flat json messages or not + * + * @defaultValue `false` + */ + flatJson?: boolean; + /** + * @remarks + * The datetime formats of localization. + * + * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) + * + * @defaultValue `{}` + */ + datetimeFormats?: IntlDateTimeFormats; + /** + * @remarks + * The number formats of localization. + * + * @VueI18nSee [Number Formatting](../guide/essentials/number) + * + * @defaultValue `{}` + */ + numberFormats?: IntlNumberFormats; + /** + * @remarks + * Custom Modifiers for linked messages. + * + * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) + */ + modifiers?: LinkedModifiers; + /** + * @remarks + * A set of rules for word pluralization + * + * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) + * + * @defaultValue `{}` + */ + pluralRules?: PluralizationRules; + /** + * @remarks + * A handler for localization missing. + * + * The handler gets called with the localization target locale, localization path key, the Vue instance and values. + * + * If missing handler is assigned, and occurred localization missing, it's not warned. + * + * @defaultValue `null` + */ + missing?: MissingHandler; + /** + * @remarks + * Whether suppress warnings outputted when localization fails. + * + * If `false`, suppress localization fail warnings. + * + * If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. `t`). + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `true` + */ + missingWarn?: boolean | RegExp; + /** + * @remarks + * Whether suppress warnings when falling back to either `fallbackLocale` or root. + * + * If `false`, suppress fall back warnings. + * + * If you use regular expression, you can suppress fallback warnings that it match with translation key (e.g. `t`). + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `true` + */ + fallbackWarn?: boolean | RegExp; + /** + * @remarks + * In the component localization, whether to fallback to root level (global scope) localization when localization fails. + * + * If `false`, it's not fallback to root. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `true` + */ + fallbackRoot?: boolean; + /** + * @remarks + * Whether do template interpolation on translation keys when your language lacks a translation for a key. + * + * If `true`, skip writing templates for your "base" language; the keys are your templates. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `false` + */ + fallbackFormat?: boolean; + /** + * @remarks + * A handler for post processing of translation. + * + * The handler gets after being called with the `t`. + * + * This handler is useful if you want to filter on translated text such as space trimming. + * + * @defaultValue `null` + */ + postTranslation?: PostTranslationHandler; + /** + * @remarks + * Whether to allow the use locale messages of HTML formatting. + * + * See the warnHtmlMessage property. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) + * + * @defaultValue `'off'` + */ + warnHtmlMessage?: boolean; + /** + * @remarks + * If `escapeParameter` is configured as true then interpolation parameters are escaped before the message is translated. + * + * This is useful when translation output is used in `v-html` and the translation resource contains html markup (e.g. around a user provided value). + * + * This usage pattern mostly occurs when passing precomputed text strings into UI components. + * + * The escape process involves replacing the following symbols with their respective HTML character entities: `<`, `>`, `"`, `'`. + * + * Setting `escapeParameter` as true should not break existing functionality but provides a safeguard against a subtle type of XSS attack vectors. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * + * @defaultValue `false` + */ + escapeParameter?: boolean; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +export declare function createI18n> = Record>, DateTimeFormats extends Record = Record, NumberFormats extends Record = Record>(options?: Options): I18n; + +export declare interface CustomBlock { + locale: Locale; + resource: LocaleMessages | LocaleMessageDictionary; +} + +export declare type CustomBlocks = Array>; + +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +export declare const DatetimeFormat: { + name: string; + props: { + value: { + type: (NumberConstructor | DateConstructor)[]; + required: boolean; + }; + format: { + type: (ObjectConstructor | StringConstructor)[]; + }; + } & { + tag: { + type: (ObjectConstructor | StringConstructor)[]; + }; + locale: { + type: StringConstructor; + }; + scope: { + type: StringConstructor; + validator: (val: "parent" | "global") => boolean; + default: "parent" | "global"; + }; + i18n: { + type: ObjectConstructor; + }; + }; + setup(props: DatetimeFormatProps, context: SetupContext): RenderFunction; +}; + +/** + * DatetimeFormat Component Props + * + * @VueI18nComponent + */ +export declare type DatetimeFormatProps = FormattableProps; + +/** @VueI18nLegacy */ +export declare type DateTimeFormatResult = string; +export { DateTimeOptions } + +/** + * Exported global composer instance + * + * @remarks + * This interface is the [global composer](general#global) that is provided interface that is injected into each component with `app.config.globalProperties`. + * + * @VueI18nGeneral + */ +export declare interface ExportedGlobalComposer { + /** + * Locale + * + * @remarks + * This property is proxy-like property for `Composer#locale`. About details, see the [Composer#locale](composition#locale) + */ + locale: Locale; + /** + * Fallback locale + * + * @remarks + * This property is proxy-like property for `Composer#fallbackLocale`. About details, see the [Composer#fallbackLocale](composition#fallbacklocale) + */ + fallbackLocale: FallbackLocale; + /** + * Available locales + * + * @remarks + * This property is proxy-like property for `Composer#availableLocales`. About details, see the [Composer#availableLocales](composition#availablelocales) + */ + readonly availableLocales: Locale[]; +} +export { FallbackLocale } + +/** + * Formattable Props + * + * @remarks + * The props used in DatetimeFormat, or NumberFormat component + * + * @VueI18nComponent + */ +export declare interface FormattableProps extends BaseFormatProps { + /** + * @remarks + * The value specified for the target component + */ + value: Value; + /** + * @remarks + * The format to use in the target component. + * + * Specify the format key string or the format as defined by the Intl API in ECMA 402. + */ + format?: string | Format; +} + +export declare interface Formatter { + interpolate(message: string, values: any, path: string): Array | null; +} + +/** + * I18n instance + * + * @remarks + * The instance required for installation as the Vue plugin + * + * @VueI18nGeneral + */ +export declare interface I18n { + /** + * Vue I18n API mode + * + * @remarks + * If you specified `legacy: true` option in `createI18n`, return `legacy`, else `composition` + * + * @defaultValue `'composition'` + */ + readonly mode: I18nMode; + /** + * The property accessible to the global Composer instance or VueI18n instance + * + * @remarks + * If the [I18n#mode](general#mode) is `'legacy'`, then you can access to a global {@link VueI18n} instance, else then [I18n#mode](general#mode) is `'composition' `, you can access to the global {@link Composer} instance. + * + * An instance of this property is **global scope***. + */ + readonly global: Legacy extends true ? VueI18n : Composer; + /** + * Install entry point + * + * @param app - A target Vue app instance + * @param options - An install options + */ + install(app: App, ...options: unknown[]): void; +} + +/** + * I18n Additional Options + * + * @remarks + * Specific options for {@link createI18n} + * + * @VueI18nGeneral + */ +export declare interface I18nAdditionalOptions { + /** + * Whether vue-i18n Legacy API mode use on your Vue App + * + * @remarks + * The default is to use the Legacy API mode. If you want to use the Composition API mode, you need to set it to `false`. + * + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @defaultValue `true` + */ + legacy?: boolean; + /** + * Whether Whether to inject global properties & functions into for each component. + * + * @remarks + * If set to `true`, then properties and methods prefixed with `$` are injected into Vue Component. + * + * @VueI18nSee [Implicit with injected properties and functions](../guide/advanced/composition#implicit-with-injected-properties-and-functions) + * @VueI18nSee [ComponentCustomProperties](injection#componentcustomproperties) + * + * @defaultValue `false` + */ + globalInjection?: boolean; +} + +/** + * Vue I18n API mode + * + * @VueI18nSee [I18n#mode](general#mode) + * + * @VueI18nGeneral + */ +export declare type I18nMode = 'legacy' | 'composition'; + +/** + * I18n Options for `createI18n` + * + * @remarks + * `I18nOptions` is inherited {@link I18nAdditionalOptions}, {@link ComposerOptions} and {@link VueI18nOptions}, + * so you can specify these options. + * + * @VueI18nGeneral + */ +export declare type I18nOptions = I18nAdditionalOptions & (ComposerOptions | VueI18nOptions); + +/** + * Vue I18n plugin options + * + * @remarks + * An options specified when installing Vue I18n as Vue plugin with using `app.use`. + * + * @VueI18nGeneral + */ +export declare interface I18nPluginOptions { + /** + * Whether to use the tag name `i18n` for Translation Component + * + * @remarks + * This option is used for compatibility with Vue I18n v8.x. + * + * If you can't migrate right away, you can temporarily enable this option, and you can work Translation Component. + * + * @defaultValue `false` + */ + useI18nComponentName?: boolean; + /** + * Whether to globally install the components that is offered by Vue I18n + * + * @remarks + * If this option is enabled, the components will be installed globally at `app.use` time. + * + * If you want to install manually in the `import` syntax, you can set it to `false` to install when needed. + * + * @defaultValue `true` + */ + globalInstall?: boolean; +} + +/** + * I18n Scope + * + * @VueI18nSee [ComposerAdditionalOptions#useScope](composition#usescope) + * @VueI18nSee [useI18n](composition#usei18n) + * + * @VueI18nGeneral + */ +export declare type I18nScope = 'local' | 'parent' | 'global'; +export { IntlDateTimeFormat } +export { IntlDateTimeFormats } +export { IntlFormatMatcher } +export { IntlLocaleMatcher } +export { IntlNumberFormat } +export { IntlNumberFormats } +export { LinkedModifiers } +export { Locale } +export { LocaleMessageArray } +export { LocaleMessageDictionary } + +/** @VueI18nLegacy */ +export declare type LocaleMessageObject = LocaleMessageDictionary; +export { LocaleMessages } +export { LocaleMessageValue } +export { MessageFunction } +export { MessageFunctions } + +/** @VueI18nComposition */ +export declare type MissingHandler = (locale: Locale, key: Path, insttance?: ComponentInternalInstance, type?: string) => string | void; +export { NamedValue } + +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +export declare const NumberFormat: { + name: string; + props: { + value: { + type: NumberConstructor; + required: boolean; + }; + format: { + type: (ObjectConstructor | StringConstructor)[]; + }; + } & { + tag: { + type: (ObjectConstructor | StringConstructor)[]; + }; + locale: { + type: StringConstructor; + }; + scope: { + type: StringConstructor; + validator: (val: "parent" | "global") => boolean; + default: "parent" | "global"; + }; + i18n: { + type: ObjectConstructor; + }; + }; + setup(props: NumberFormatProps, context: SetupContext): RenderFunction; +}; + +/** + * NumberFormat Component Props + * + * @VueI18nComponent + */ +export declare type NumberFormatProps = FormattableProps; + +/** @VueI18nLegacy */ +export declare type NumberFormatResult = string; +export { NumberOptions } +export { Path } +export { PathValue } +export { PluralizationRule } + +export declare type PluralizationRulesMap = { + [locale: string]: PluralizationRule; +}; +export { PostTranslationHandler } +export { TranslateOptions } + +/** @VueI18nLegacy */ +export declare type TranslateResult = string; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +export declare const Translation: { + name: string; + props: { + keypath: { + type: StringConstructor; + required: boolean; + }; + plural: { + type: (StringConstructor | NumberConstructor)[]; + validator: (val: any) => boolean; + }; + } & { + tag: { + type: (ObjectConstructor | StringConstructor)[]; + }; + locale: { + type: StringConstructor; + }; + scope: { + type: StringConstructor; + validator: (val: "parent" | "global") => boolean; + default: "parent" | "global"; + }; + i18n: { + type: ObjectConstructor; + }; + }; + setup(props: TranslationProps, context: SetupContext): RenderFunction; +}; + +/** + * Translation Directive (`v-t`) + * + * @remarks + * Update the element `textContent` that localized with locale messages. + * + * You can use string syntax or object syntax. + * + * String syntax can be specified as a keypath of locale messages. + * + * If you can be used object syntax, you need to specify as the object key the following params + * + * ``` + * - path: required, key of locale messages + * - locale: optional, locale + * - args: optional, for list or named formatting + * ``` + * + * @example + * ```html + * + *

+ * + * + *

+ * + * + *

+ * + * + *

+ * ``` + * + * @VueI18nDirective + */ +export declare type TranslationDirective = ObjectDirective; + +/** + * Translation Component Props + * + * @VueI18nComponent + */ +export declare interface TranslationProps extends BaseFormatProps { + /** + * @remarks + * The locale message key can be specified prop + */ + keypath: string; + /** + * @remarks + * The Plural Choosing the message number prop + */ + plural?: number | string; +} + +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +export declare function useI18n> = Record>, DateTimeFormats extends Record = Record, NumberFormats extends Record = Record>(options?: Options): Composer; + +/** + * I18n Options for `useI18n` + * + * @remarks + * `UseI18nOptions` is inherited {@link ComposerAdditionalOptions} and {@link ComposerOptions}, so you can specify these options. + * + * @VueI18nSee [useI18n](composition#usei18n) + * + * @VueI18nComposition + */ +export declare type UseI18nOptions = ComposerAdditionalOptions & ComposerOptions; + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +export declare const VERSION: string; + +export declare function vTDirective(i18n: I18n): TranslationDirective; + +/** + * VueI18n legacy interfaces + * + * @remarks + * This interface is compatible with interface of `VueI18n` class (offered with Vue I18n v8.x). + * + * @VueI18nLegacy + */ +export declare interface VueI18n { + /** + * @remarks + * Instance ID. + */ + id: number; + /** + * @remarks + * The current locale this VueI18n instance is using. + * + * If the locale contains a territory and a dialect, this locale contains an implicit fallback. + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + locale: Locale; + /** + * @remarks + * The current fallback locales this VueI18n instance is using. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + fallbackLocale: FallbackLocale; + /** + * @remarks + * The list of available locales in `messages` in lexical order. + */ + readonly availableLocales: Locale[]; + /** + * @remarks + * The locale messages of localization. + * + * @VueI18nSee [Getting Started](../guide/) + */ + readonly messages: Messages; + /** + * @remarks + * The datetime formats of localization. + * + * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) + */ + readonly datetimeFormats: DateTimeFormats; + /** + * @remarks + * The number formats of localization. + * + * @VueI18nSee [Number Formatting](../guide/essentials/number) + */ + readonly numberFormats: NumberFormats; + /** + * @remarks + * Custom Modifiers for linked messages. + * + * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) + */ + readonly modifiers: LinkedModifiers; + /** + * @remarks + * The formatter that implemented with Formatter interface. + * + * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) + */ + formatter: Formatter; + /** + * @remarks + * A handler for localization missing. + */ + missing: MissingHandler | null; + /** + * @remarks + * A handler for post processing of translation. + */ + postTranslation: PostTranslationHandler | null; + /** + * @remarks + * Whether suppress warnings outputted when localization fails. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + silentTranslationWarn: boolean | RegExp; + /** + * @remarks + * Whether suppress fallback warnings when localization fails. + */ + silentFallbackWarn: boolean | RegExp; + /** + * @remarks + * Whether suppress warnings when falling back to either `fallbackLocale` or root. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + */ + formatFallbackMessages: boolean; + /** + * @remarks + * Whether synchronize the root level locale to the component localization locale. + * + * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) + */ + sync: boolean; + /** + * @remarks + * Whether to allow the use locale messages of HTML formatting. + * + * If you set `warn` or` error`, will check the locale messages on the VueI18n instance. + * + * If you are specified `warn`, a warning will be output at console. + * + * If you are specified `error` will occurred an Error. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) + */ + warnHtmlInMessage: WarnHtmlInMessageLevel; + /** + * @remarks + * Whether interpolation parameters are escaped before the message is translated. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + */ + escapeParameterHtml: boolean; + /** + * @remarks + * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. + * + * @VueI18nSee [Custom Directive](../guide/advanced/directive) + * @VueI18nSee [Remove preserveDirectiveContent option](../guide/migration/breaking#remove-preservedirectivecontent-option) + * + * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. + */ + preserveDirectiveContent: boolean; + /** + * A set of rules for word pluralization + * + * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) + */ + pluralizationRules: PluralizationRules; + /** + * Locale message translation. + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [i18n component options](injection#i18n) is specified, it’s translated in preferentially local scope locale messages than global scope locale messages. + * + * If [i18n component options](injection#i18n) isn't specified, it’s translated with global scope locale messages. + * + * @param key - A target locale message key + * + * @returns Translated message + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + t(key: Path): TranslateResult; + /** + * Locale message translation. + * + * @remarks + * Overloaded `t`. About details, see the [t](legacy#t-key) details. + * + * @param key - A target locale message key + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Translated message + */ + t(key: Path, locale: Locale): TranslateResult; + /** + * Locale message translation. + * + * @remarks + * Overloaded `t`. About details, see the [t](legacy#t-key) details. + * + * @param key - A target locale message key + * @param locale - A locale, it will be used over than global scope or local scope. + * @param list - A values of list interpolation + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + t(key: Path, locale: Locale, list: unknown[]): TranslateResult; + /** + * Locale message translation. + * + * @remarks + * Overloaded `t`. About details, see the [t](legacy#t-key) details. + * + * @param key - A target locale message key + * @param locale - A locale, it will be used over than global scope or local scope. + * @param named - A values of named interpolation + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + t(key: Path, locale: Locale, named: object): TranslateResult; + /** + * Locale message translation. + * + * @remarks + * Overloaded `t`. About details, see the [t](legacy#t-key) details. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + t(key: Path, list: unknown[]): TranslateResult; + /** + * Locale message translation. + * + * @remarks + * Overloaded `t`. About details, see the [t](legacy#t-key) details. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + t(key: Path, named: Record): TranslateResult; + /* Excluded from this release type: t */ + /** + * Resolve locale message translation + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * + * @returns Translated message + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + */ + rt(message: MessageFunction | VueMessageType): string; + /** + * Resolve locale message translation for plurals + * + * @remarks + * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. + * + * In this overloaded `rt`, return a pluralized translation message. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param plural - Which plural string to get. 1 returns the first one. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + */ + rt(message: MessageFunction | VueMessageType, plural: number, options?: TranslateOptions): string; + /** + * Resolve locale message translation for list interpolations + * + * @remarks + * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. + * + * In this overloaded `rt`, return a pluralized translation message. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param list - A values of list interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) + */ + rt(message: MessageFunction | VueMessageType, list: unknown[], options?: TranslateOptions): string; + /** + * Resolve locale message translation for named interpolations + * + * @remarks + * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. + * + * In this overloaded `rt`, for each placeholder x, the locale messages should contain a `{x}` token. + * + * @VueI18nTip + * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. + * + * @VueI18nWarning + * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. + * @param named - A values of named interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + * + * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) + */ + rt(message: MessageFunction | VueMessageType, named: NamedValue, options?: TranslateOptions): string; + /* Excluded from this release type: rt */ + /** + * Locale message pluralization + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [i18n component options](injection#i18n) is specified, it’s pluraled in preferentially local scope locale messages than global scope locale messages. + * + * If [i18n component options](injection#i18n) isn't specified, it’s pluraled with global scope locale messages. + * + * The plural choice number is handled with default `1`. + * + * @param key - A target locale message key + * + * @returns Pluraled message + * + * @VueI18nSee [Pluralization](../guide/essentials/pluralization) + */ + tc(key: Path): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Pluraled message + */ + tc(key: Path, locale: Locale): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * + * @returns Pluraled message + */ + tc(key: Path, list: unknown[]): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * + * @returns Pluraled message + */ + tc(key: Path, named: Record): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * + * @returns Pluraled message + */ + tc(key: Path, choice: number): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Pluraled message + */ + tc(key: Path, choice: number, locale: Locale): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param list - A values of list interpolation + * + * @returns Pluraled message + */ + tc(key: Path, choice: number, list: unknown[]): TranslateResult; + /** + * Locale message pluralization + * + * @remarks + * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param named - A values of named interpolation + * + * @returns Pluraled message + */ + tc(key: Path, choice: number, named: Record): TranslateResult; + /* Excluded from this release type: tc */ + /** + * Translation locale message exist + * + * @remarks + * whether do exist locale message on VueI18n instance [messages](legacy#messages). + * + * If you specified `locale`, check the locale messages of `locale`. + * + * @param key - A target locale message key + * @param locale - A target locale + * + * @returns If found locale message, `true`, else `false` + */ + te(key: Path, locale?: Locale): boolean; + /** + * Locale messages getter + * + * @remarks + * If [i18n component options](injection#i18n) is specified, it’s get in preferentially local scope locale messages than global scope locale messages. + * + * If [i18n component options](injection#i18n) isn't specified, it’s get with global scope locale messages. + * + * Based on the current `locale`, locale messages will be returned from Composer instance messages. + * + * If you change the `locale`, the locale messages returned will also correspond to the locale. + * + * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with [fallbacking](../guide/essentials/fallback). + * + * @VueI18nWarning + * You need to use `rt` for the locale message returned by `tm`. see the [rt](legacy#rt-message) details. + * + * @example + * template: + * ```html + *
+ * + *
+ * ``` + * + * ```js + * import { createI18n } from 'vue-i18n' + * + * const i18n = createI18n({ + * messages: { + * en: { + * contents: [ + * { + * title: 'Title1', + * // ... + * paragraphs: [ + * // ... + * ] + * } + * ] + * } + * } + * // ... + * }) + * ``` + * @param key - A target locale message key + * + * @return Locale messages + */ + tm(key: Path): LocaleMessageValue | {}; + /** + * Get locale message + * + * @remarks + * get locale message from VueI18n instance [messages](legacy#messages). + * + * @param locale - A target locale + * + * @returns Locale messages + */ + getLocaleMessage(locale: Locale): LocaleMessageDictionary; + /** + * Set locale message + * + * @remarks + * Set locale message to VueI18n instance [messages](legacy#messages). + * + * @param locale - A target locale + * @param message - A message + */ + setLocaleMessage(locale: Locale, message: LocaleMessageDictionary): void; + /** + * Merge locale message + * + * @remarks + * Merge locale message to VueI18n instance [messages](legacy#messages). + * + * @param locale - A target locale + * @param message - A message + */ + mergeLocaleMessage(locale: Locale, message: LocaleMessageDictionary): void; + /** + * Datetime formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope datetime formats than global scope locale messages. + * + * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope datetime formats. + * + * @param value - A value, timestamp number or `Date` instance + * + * @returns Formatted value + * + * @VueI18nSee [Datetime formatting](../guide/essentials/datetime) + */ + d(value: number | Date): DateTimeFormatResult; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](legacy#d-value) details. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * + * @returns Formatted value + */ + d(value: number | Date, key: string): DateTimeFormatResult; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](legacy#d-value) details. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Formatted value + */ + d(value: number | Date, key: string, locale: Locale): DateTimeFormatResult; + /** + * Datetime formatting + * + * @remarks + * Overloaded `d`. About details, see the [d](legacy#d-value) details. + * + * @param value - A value, timestamp number or `Date` instance + * @param args - An argument values + * + * @returns Formatted value + */ + d(value: number | Date, args: { + [key: string]: string; + }): DateTimeFormatResult; + /* Excluded from this release type: d */ + /** + * Get datetime format + * + * @remarks + * get datetime format from VueI18n instance [datetimeFormats](legacy#datetimeformats). + * + * @param locale - A target locale + * + * @returns Datetime format + */ + getDateTimeFormat(locale: Locale): IntlDateTimeFormat; + /** + * Set datetime format + * + * @remarks + * Set datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). + * + * @param locale - A target locale + * @param format - A target datetime format + */ + setDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; + /** + * Merge datetime format + * + * @remarks + * Merge datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). + * + * @param locale - A target locale + * @param format - A target datetime format + */ + mergeDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; + /** + * Number formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope number formats than global scope locale messages. + * + * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope number formats. + * + * @param value - A number value + * + * @returns Formatted value + * + * @VueI18nSee [Number formatting](../guide/essentials/number) + */ + n(value: number): NumberFormatResult; + /** + * Number formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](legacy#n-value) details. + * + * @param value - A number value + @param key - A key of number formats + * + * @returns Formatted value + */ + n(value: number, key: string): NumberFormatResult; + /** + * Number formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](legacy#n-value) details. + * + * @param value - A number value + * @param key - A key of number formats + * @param locale - A locale, it will be used over than global scope or local scope. + * + * @returns Formatted value + */ + n(value: number, key: string, locale: Locale): NumberFormatResult; + /** + * Number formatting + * + * @remarks + * Overloaded `n`. About details, see the [n](legacy#n-value) details. + * + * @param value - A number value + * @param args - An argument values + * + * @returns Formatted value + */ + n(value: number, args: { + [key: string]: string; + }): NumberFormatResult; + /* Excluded from this release type: n */ + /** + * Get number format + * + * @remarks + * get number format from VueI18n instance [numberFormats](legacy#numberFormats). + * + * @param locale - A target locale + * + * @returns Number format + */ + getNumberFormat(locale: Locale): IntlNumberFormat; + /** + * Set number format + * + * @remarks + * Set number format to VueI18n instance [numberFormats](legacy#numberFormats). + * + * @param locale - A target locale + * @param format - A target number format + */ + setNumberFormat(locale: Locale, format: IntlNumberFormat): void; + /** + * Merge number format + * + * @remarks + * Merge number format to VueI18n instance [numberFormats](legacy#numberFormats). + * + * @param locale - A target locale + * @param format - A target number format + */ + mergeNumberFormat(locale: Locale, format: IntlNumberFormat): void; + /** + * Get choice index + * + * @remarks + * Get pluralization index for current pluralizing number and a given amount of choices. + * + * @deprecated Use `pluralizationRules` option instead of `getChoiceIndex`. + */ + getChoiceIndex: (choice: Choice, choicesLength: number) => number; +} + +/** + * VueI18n Options + * + * @remarks + * This option is compatible with `VueI18n` class constructor options (offered with Vue I18n v8.x) + * + * @VueI18nLegacy + */ +export declare interface VueI18nOptions { + /** + * @remarks + * The locale of localization. + * + * If the locale contains a territory and a dialect, this locale contains an implicit fallback. + * + * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) + * + * @defaultValue `'en-US'` + */ + locale?: Locale; + /** + * @remarks + * The locale of fallback localization. + * + * For more complex fallback definitions see fallback. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue The default `'en-US'` for the `locale` if it's not specified, or it's `locale` value + */ + fallbackLocale?: FallbackLocale; + /** + * @remarks + * The locale messages of localization. + * + * @VueI18nSee [Getting Started](../guide/) + * + * @defaultValue `{}` + */ + messages?: LocaleMessages; + /** + * @remarks + * Allow use flat json messages or not + * + * @defaultValue `false` + */ + flatJson?: boolean; + /** + * @remarks + * The datetime formats of localization. + * + * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) + * + * @defaultValue `{}` + */ + datetimeFormats?: IntlDateTimeFormats; + /** + * @remarks + * The number formats of localization. + * + * @VueI18nSee [Number Formatting](../guide/essentials/number) + * + * @defaultValue `{}` + */ + numberFormats?: IntlNumberFormats; + /** + * @remarks + * The list of available locales in messages in lexical order. + * + * @defaultValue `[]` + */ + availableLocales?: Locale[]; + /** + * @remarks + * Custom Modifiers for linked messages. + * + * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) + */ + modifiers?: LinkedModifiers; + /** + * @remarks + * The formatter that implemented with Formatter interface. + * + * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) + */ + formatter?: Formatter; + /** + * @remarks + * A handler for localization missing. + * + * The handler gets called with the localization target locale, localization path key, the Vue instance and values. + * + * If missing handler is assigned, and occurred localization missing, it's not warned. + * + * @defaultValue `null` + */ + missing?: MissingHandler; + /** + * @remarks + * In the component localization, whether to fall back to root level (global scope) localization when localization fails. + * + * If `false`, it's not fallback to root. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `true` + */ + fallbackRoot?: boolean; + /** + * @remarks + * Whether suppress warnings outputted when localization fails. + * + * If `true`, suppress localization fail warnings. + * + * If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. `t`). + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `false` + */ + silentTranslationWarn?: boolean | RegExp; + /** + * @remarks + * Whether do template interpolation on translation keys when your language lacks a translation for a key. + * + * If `true`, skip writing templates for your "base" language; the keys are your templates. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `false` + */ + silentFallbackWarn?: boolean | RegExp; + /** + * @remarks + * Whether suppress warnings when falling back to either `fallbackLocale` or root. + * + * @VueI18nSee [Fallbacking](../guide/essentials/fallback) + * + * @defaultValue `false` + */ + formatFallbackMessages?: boolean; + /** + * @remarks + * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. + * + * @VueI18nSee [Custom Directive](../guide/advanced/directive) + * @VueI18nSee [Remove `preserveDirectiveContent` option](../guide/migration/breaking#remove-preservedirectivecontent-option) + * + * @defaultValue `false` + * + * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. + */ + preserveDirectiveContent?: boolean; + /** + * @remarks + * Whether to allow the use locale messages of HTML formatting. + * + * See the warnHtmlInMessage property. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) + * + * @defaultValue `'off'` + */ + warnHtmlInMessage?: WarnHtmlInMessageLevel; + /** + * @remarks + * If `escapeParameterHtml` is configured as true then interpolation parameters are escaped before the message is translated. + * + * This is useful when translation output is used in `v-html` and the translation resource contains html markup (e.g. around a user provided value). + * + * This usage pattern mostly occurs when passing precomputed text strings into UI components. + * + * The escape process involves replacing the following symbols with their respective HTML character entities: `<`, `>`, `"`, `'`. + * + * Setting `escapeParameterHtml` as true should not break existing functionality but provides a safeguard against a subtle type of XSS attack vectors. + * + * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) + * + * @defaultValue `false` + */ + escapeParameterHtml?: boolean; + /** + * @remarks + * The shared locale messages of localization for components. More detail see Component based localization. + * + * @VueI18nSee [Shared locale messages for components](../guide/essentials/local#shared-locale-messages-for-components) + * + * @defaultValue `undefined` + */ + sharedMessages?: LocaleMessages; + /** + * @remarks + * A set of rules for word pluralization + * + * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) + * + * @defaultValue `{}` + */ + pluralizationRules?: PluralizationRules; + /** + * @remarks + * A handler for post processing of translation. The handler gets after being called with the `$t`, `t`, `$tc`, and `tc`. + * + * This handler is useful if you want to filter on translated text such as space trimming. + * + * @defaultValue `null` + */ + postTranslation?: PostTranslationHandler; + /** + * @remarks + * Whether synchronize the root level locale to the component localization locale. + * + * If `false`, regardless of the root level locale, localize for each component locale. + * + * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) + * + * @defaultValue `true` + */ + sync?: boolean; + /** + * @remarks + * A handler for getting notified when component-local instance was created. + * + * The handler gets called with new and old (root) VueI18n instances. + * + * This handler is useful when extending the root VueI18n instance and wanting to also apply those extensions to component-local instance. + * + * @defaultValue `null` + */ + componentInstanceCreatedListener?: ComponentInstanceCreatedListener; +} + +/** @VueI18nComposition */ +export declare type VueMessageType = string | VNode; + +export declare type WarnHtmlInMessageLevel = 'off' | 'warn' | 'error'; + +export { } + +declare module '@vue/runtime-core' { + /** + * Component Custom Options for Vue I18n + * + * @VueI18nInjection + */ + export interface ComponentCustomOptions { + /** + * VueI18n options + * + * @remarks + * See the {@link VueI18nOptions} + */ + i18n?: VueI18nOptions + /** + * For custom blocks options + * @internal + */ + __i18n?: CustomBlocks + /** + * For devtools + * @internal + */ + __INTLIFY_META__?: string + } + + /** + * Component Custom Properties for Vue I18n + * + * @VueI18nInjection + */ + export interface ComponentCustomProperties { + /** + * Exported Global Composer instance, or global VueI18n instance. + * + * @remarks + * You can get the {@link ExportedGlobalComposer | exported composer instance} which are exported from global {@link Composer | composer instance} created with {@link createI18n}, or global {@link VueI18n | VueI18n instance}. + * You can get the exported composer instance in {@link I18nMode | Composition API mode}, or the Vuei18n instance in {@link I18nMode | Legacy API mode}, which is the instance you can refer to with this property. + * The locales, locale messages, and other resources managed by the instance referenced by this property are valid as global scope. + * If the `i18n` component custom option is not specified, it's the same as the VueI18n instance that can be referenced by the i18n instance {@link I18n.global | global} property. + */ + $i18n: VueI18n | ExportedGlobalComposer + /** + * Locale message translation + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#t | `VueI18n#t`}. + * + * In {@link I18nMode | Composition API mode}, the `$t` is injected by `app.config.globalProperties`. + * the input / output is the same as for Composer, and it work on **global scope**. About that details, see {@link Composer#t | `Composer#t` }. + * + * @param key - A target locale message key + * + * @returns translation message + */ + $t(key: Path): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param locale - A locale, override locale that global scope or local scope + * + * @returns translation message + */ + $t(key: Path, locale: Locale): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param locale - A locale, override locale that global scope or local scope + * @param list - A values of list interpolation + * + * @returns translation message + */ + $t(key: Path, locale: Locale, list: unknown[]): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param locale - A locale, override locale that global scope or local scope + * @param named - A values of named interpolation + * + * @returns translation message + */ + $t(key: Path, locale: Locale, named: object): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * + * @returns translation message + */ + $t(key: Path, list: unknown[]): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * + * @returns translation message + */ + $t(key: Path, named: Record): TranslateResult + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * + * @returns translation message + */ + $t(key: Path): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param plural - A choice number of plural + * + * @returns translation message + */ + $t(key: Path, plural: number): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param plural - Which plural string to get. 1 returns the first one. + * @param options - An options, see the {@link TranslateOptions} + * + * @returns translation message + */ + $t(key: Path, plural: number, options: TranslateOptions): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param defaultMsg - A default message to return if no translation was found + * + * @returns translation message + */ + $t(key: Path, defaultMsg: string): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param defaultMsg - A default message to return if no translation was found + * @param options - An options, see the {@link TranslateOptions} + * + * @returns translation message + */ + $t(key: Path, defaultMsg: string, options: TranslateOptions): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * + * @returns translation message + */ + $t(key: Path, list: unknown[]): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param plural - A choice number of plural + * + * @returns translation message + */ + $t(key: Path, list: unknown[], plural: number): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param defaultMsg - A default message to return if no translation was found + * + * @returns translation message + */ + $t(key: Path, list: unknown[], defaultMsg: string): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * @param options - An options, see the {@link TranslateOptions} + * + * @returns translation message + */ + $t(key: Path, list: unknown[], options: TranslateOptions): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * + * @returns translation message + */ + $t(key: Path, named: NamedValue): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param plural - A choice number of plural + * + * @returns translation message + */ + $t(key: Path, named: NamedValue, plural: number): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param defaultMsg - A default message to return if no translation was found + * + * @returns translation message + */ + $t(key: Path, named: NamedValue, defaultMsg: string): string + /** + * Locale message translation + * + * @remarks + * Overloaded `$t`. About details, see the {@link $t} remarks. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * @param options - An options, see the {@link TranslateOptions} + * + * @returns translation message + */ + $t(key: Path, named: NamedValue, options: TranslateOptions): string + /** + * Resolve locale message translation + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#rt | `VueI18n#rt`}. + * + * In {@link I18nMode | Composition API mode}, the `$rt` is injected by `app.config.globalProperties`. + * the input / output is the same as for Composer, and it work on **global scope**. About that details, see {@link Composer#rt | `Composer#rt` }. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. + * + * @returns translated message + */ + $rt(message: MessageFunction | VueMessageType): string + /** + * Resolve locale message translation for plurals + * + * @remarks + * Overloaded `$rt`. About details, see the {@link $rt} remarks. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. + * @param plural - Which plural string to get. 1 returns the first one. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + */ + $rt( + message: MessageFunction | VueMessageType, + plural: number, + options?: TranslateOptions + ): string + /** + * Resolve locale message translation for list interpolations + * + * @remarks + * Overloaded `$rt`. About details, see the {@link $rt} remarks. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. + * @param list - A values of list interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + */ + $rt( + message: MessageFunction | VueMessageType, + list: unknown[], + options?: TranslateOptions + ): string + /** + * Resolve locale message translation for named interpolations + * + * @remarks + * Overloaded `$rt`. About details, see the {@link $rt} remarks. + * + * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. + * @param named - A values of named interpolation. + * @param options - Additional {@link TranslateOptions | options} for translation + * + * @returns Translated message + */ + $rt( + message: MessageFunction | VueMessageType, + named: NamedValue, + options?: TranslateOptions + ): string + /** + * Locale message pluralization + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * The input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#tc | `VueI18n#tc` }. + * The value of plural is handled with default `1`. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * + * @returns translation message that is pluraled + */ + $tc(key: Path): TranslateResult + /** + * Locale message pluralization + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param locale - A locale, override locale that global scope or local scope + * + * @returns translation message that is pluraled + */ + $tc(key: Path, locale: Locale): TranslateResult + /** + * Locale message pluralization + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param list - A values of list interpolation + * + * @returns translation message that is pluraled + */ + $tc(key: Path, list: unknown[]): TranslateResult + /** + * Locale message pluralization + * Supported for Legacy API mode only. + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param named - A values of named interpolation + * + * @returns translation message that is pluraled + */ + $tc(key: Path, named: Record): TranslateResult + /** + * Locale message pluralization + * Supported for Legacy API mode only. + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * + * @returns translation message that is pluraled + */ + $tc(key: Path, choice: number): TranslateResult + /** + * Locale message pluralization + * Supported for Legacy API mode only. + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param locale - A locale, override locale that global scope or local scope + * + * @returns translation message that is pluraled + */ + $tc(key: Path, choice: number, locale: Locale): TranslateResult + /** + * Locale message pluralization + * Supported for Legacy API mode only. + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param list - A values of list interpolation + * + * @returns translation message that is pluraled + */ + $tc(key: Path, choice: number, list: unknown[]): TranslateResult + /** + * Locale message pluralization + * Supported for Legacy API mode only. + * + * @remarks + * Overloaded `$tc`. About details, see the {@link $tc} remarks. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param choice - Which plural string to get. 1 returns the first one. + * @param named - A values of named interpolation + * + * @returns translation message that is pluraled + */ + $tc( + key: Path, + choice: number, + named: Record + ): TranslateResult + /** + * Translation message exist + * + * @remarks + * The input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#te | `VueI18n.#te` }. + * Supported for Legacy API mode only. + * + * @param key - A target locale message key + * @param locale - A locale, optional, override locale that global scope or local scope + * + * @returns if found locale message, `true`, else `false` + */ + $te(key: Path, locale?: Locale): boolean + /** + * Datetime formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#d | `VueI18n#d` }. + * + * In {@link I18nMode | Composition API mode}, the `$d` is injected by `app.config.globalProperties`. + * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#d | `Composer#d` }. + * + * @param value - A value, timestamp number or `Date` instance + * + * @returns formatted value + */ + $d(value: number | Date): DateTimeFormatResult + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * + * @returns formatted value + */ + $d(value: number | Date, key: string): DateTimeFormatResult + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * @param locale - A locale, optional, override locale that global scope or local scope + * + * @returns formatted value + */ + $d(value: number | Date, key: string, locale: Locale): DateTimeFormatResult + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param args - An argument values + * + * @returns formatted value + */ + $d( + value: number | Date, + args: { [key: string]: string } + ): DateTimeFormatResult + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * + * @returns formatted value + */ + $d(value: number | Date): string + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * + * @returns formatted value + */ + $d(value: number | Date, key: string): string + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param key - A key of datetime formats + * @param locale - A locale, optional, override locale that global scope or local scope + * + * @returns formatted value + */ + $d(value: number | Date, key: string, locale: Locale): string + /** + * Datetime formatting + * + * @remarks + * Overloaded `$d`. About details, see the {@link $d} remarks. + * + * @param value - A value, timestamp number or `Date` instance + * @param options - An options, see the {@link DateTimeOptions} + * + * @returns formatted value + */ + $d(value: number | Date, options: DateTimeOptions): string + /** + * Number formatting + * + * @remarks + * If this is used in a reactive context, it will re-evaluate once the locale changes. + * + * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#n | `VueI18n.n` }. + * + * In {@link I18nMode | Composition API mode}, the `$n` is injected by `app.config.globalProperties`. + * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#n | `Composer.n` }. + * + * @param value - A number value + * + * @returns formatted value + */ + $n(value: number): NumberFormatResult + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param key - A key of number formats + * + * @returns formatted value + */ + $n(value: number, key: string): NumberFormatResult + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param key - A key of number formats + * @param locale - A locale, optional, override locale that global scope or local scope + * + * @returns formatted value + */ + $n(value: number, key: string, locale: Locale): NumberFormatResult + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param args - An argument values + * + * @returns formatted value + */ + $n(value: number, args: { [key: string]: string }): NumberFormatResult + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * + * @returns formatted value + */ + $n(value: number): string + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param key - A key of number formats + * + * @returns formatted value + */ + $n(value: number, key: string): string + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param key - A key of number formats + * @param locale - A locale, optional, override locale that global scope or local scope + * + * @returns formatted value + */ + $n(value: number, key: string, locale: Locale): string + /** + * Number formatting + * + * @remarks + * Overloaded `$n`. About details, see the {@link $n} remarks. + * + * @param value - A number value + * @param options - An options, see the {@link NumberOptions} + * + * @returns formatted value + */ + $n(value: number, options: NumberOptions): string + /** + * Locale messages getter + * + * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#tm | `VueI18n#tm` }. + * + * @remarks + * In {@link I18nMode | Composition API mode}, the `$tm` is injected by `app.config.globalProperties`. + * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#tm | `Composer.tm` }. + * Based on the current `locale`, locale messages will be returned from Composer instance messages. + * If you change the `locale`, the locale messages returned will also correspond to the locale. + * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with fallbacking. + * + * @param key - A target locale message key + * + * @returns locale messages + */ + $tm(key: Path): LocaleMessageValue | {} + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..61a8e95707f18afba3141f2ebb4e2a22e767169a --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.js @@ -0,0 +1,5052 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; + +/** + * Original Utilities + * written by kazuya kawaguchi + */ +const inBrowser = typeof window !== 'undefined'; +let mark; +let measure; +{ + 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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; +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; +} + +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; +} + +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; +} + +/** @internal */ +const errorMessages$2 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$2)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} +/** @internal */ +function defaultOnError(error) { + throw error; +} + +function createPosition(line, column, offset) { + return { line, column, offset }; +} +function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; +} + +const CHAR_SP = ' '; +const CHAR_CR = '\r'; +const CHAR_LF = '\n'; +const CHAR_LS = String.fromCharCode(0x2028); +const CHAR_PS = String.fromCharCode(0x2029); +function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; +} + +const EOF = undefined; +const LITERAL_DELIMITER = "'"; +const ERROR_DOMAIN$1 = 'tokenizer'; +function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; +} + +const ERROR_DOMAIN = 'parser'; +// Backslash backslash, backslash quote, uHHHH, UHHHHHH. +const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; +function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } +} +function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; +} +function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; +} + +function createTransformer(ast, options = {} // eslint-disable-line +) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; +} +function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } +} +function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here +} +// transform AST +function transform(ast, options = {} // eslint-disable-line +) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); +} + +function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; +} +function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); +} +function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); +} +function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } +} +function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } +} +function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } +} +// generate code from AST +const generate = (ast, options = {} // eslint-disable-line +) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; +}; + +function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); +} + +const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' +}; + +let devtools = null; +function setDevToolsHook(hook) { + devtools = hook; +} +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$1 = { + [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$1(code, ...args) { + return format(warnMessages$1[code], ...args); +} + +/** + * Intlify core-base version + * @internal + */ +const VERSION$1 = '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$1; + 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 + { + 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 isString(ret) ? ret : key; + } + else { + if (isTranslateMissingWarn(missingWarn, key)) { + onWarn(getWarnMessage$1(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 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 || 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, { messages: errorMessages$1 } ); +} +/** @internal */ +const errorMessages$1 = { + [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 (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 !! + { + // 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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!Availabilities.dateTimeFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (!Availabilities.numberFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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); + } +} + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +const VERSION = '9.1.7'; +/** + * This is only called development env + * istanbul-ignore-next + */ +function initDev() { + { + { + console.info(`You are running a development build of vue-i18n.\n` + + `Make sure to use the production build (*.prod.js) when deploying for production.`); + } + } +} + +const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` +}; +function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); +} + +function createI18nError(code, ...args) { + return createCompileError(code, null, { messages: errorMessages, args } ); +} +const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` +}; + +const DEVTOOLS_META = '__INTLIFY_META__'; +const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); +const DatetimePartsSymbol = makeSymbol('__datetimeParts'); +const NumberPartsSymbol = makeSymbol('__numberParts'); +const EnableEmitter = makeSymbol('__enableEmitter'); +const DisableEmitter = makeSymbol('__disableEmitter'); +const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); +let composerID = 0; +function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, getCurrentInstance() || undefined, type); + }); +} +function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; +} +const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } +} +// for Intlify DevTools +const getMetaInfo = /* #__PURE__*/ () => { + const instance = getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; +}; +/** + * Create composer interface factory + * + * @internal + */ +function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if (__root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; +} + +/** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ +function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if (options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if (options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; +} +/** + * create VueI18n interface factory + * + * @internal + */ +function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; +} + +const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } +}; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; + } +}; +function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } +} + +function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; +} + +const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' +]; +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } +}; + +const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' +]; +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } +}; + +function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } +} +function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if (modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; +} +function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } +} +function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; +} + +function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if (globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +function getDevtoolsGlobalHook() { + return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; +} +function getTarget() { + // @ts-ignore + return typeof navigator !== 'undefined' + ? window + : typeof global$1 !== 'undefined' + ? global$1 + : {}; +} + +const HOOK_SETUP = 'devtools-plugin:setup'; + +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 + }); + } +} + +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 +}; + +const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; +let devtoolsApi; +async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); +} +function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any +treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } +} +function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; +} +const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' +}; +function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); +} +function escapeChar(a) { + return ESC[a] || a; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; +} +function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } +} +function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } +} +function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } +} +function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; +} +function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } +} +function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } +} + +// supports compatibility for legacy vue-i18n APIs +function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; +} +function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = isBoolean(options.legacy) + ? options.legacy + : true; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol('vue-i18n' ); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __legacyMode + ? 'legacy' + : 'composition' + ; + }, + // install plugin + async install(app, ...options) { + { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; +} +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + let emitter = null; + onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +// register message compiler at vue-i18n +registerMessageCompiler(compileToFunction); +// NOTE: experimental !! +{ + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); +} +{ + initDev(); +} + +export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..b12bb18327000e33ce4b1ed16fbd12088c0bdbbb --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-browser.prod.js @@ -0,0 +1,6 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import{ref as e,getCurrentInstance as t,computed as n,watch as r,createVNode as a,Text as o,h as s,Fragment as l,inject as c,onMounted as i,onUnmounted as u,isRef as f}from"vue";const m="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,p=e=>m?Symbol(e):e,g=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),d=e=>"number"==typeof e&&isFinite(e),b=e=>"[object RegExp]"===$(e),h=e=>M(e)&&0===Object.keys(e).length;function k(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const _=Object.assign;function v(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const y=Object.prototype.hasOwnProperty;function F(e,t){return y.call(e,t)}const L=Array.isArray,w=e=>"function"==typeof e,T=e=>"string"==typeof e,x=e=>"boolean"==typeof e,P=e=>null!==e&&"object"==typeof e,C=Object.prototype.toString,$=e=>C.call(e),M=e=>"[object Object]"===$(e),O=[];O[0]={w:[0],i:[3,0],"[":[4],o:[7]},O[1]={w:[1],".":[2],"[":[4],o:[7]},O[2]={w:[2],i:[3,0],0:[3,0]},O[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},O[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},O[5]={"'":[4,0],o:8,l:[5,0]},O[6]={'"':[4,0],o:8,l:[6,0]};const W=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function N(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function S(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(W.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}const I=new Map;function E(e,t){if(!P(e))return null;let n=I.get(t);if(n||(n=function(e){const t=[];let n,r,a,o,s,l,c,i=-1,u=0,f=0;const m=[];function p(){const t=e[i+1];if(5===u&&"'"===t||6===u&&'"'===t)return i++,a="\\"+t,m[0](),!0}for(m[0]=()=>{void 0===r?r=a:r+=a},m[1]=()=>{void 0!==r&&(t.push(r),r=void 0)},m[2]=()=>{m[0](),f++},m[3]=()=>{if(f>0)f--,u=4,m[0]();else{if(f=0,void 0===r)return!1;if(r=S(r),!1===r)return!1;m[1]()}};null!==u;)if(i++,n=e[i],"\\"!==n||!p()){if(o=N(n),c=O[u],s=c[o]||c.l||8,8===s)return;if(u=s[0],void 0!==s[1]&&(l=m[s[1]],l&&(a=n,!1===l())))return;if(7===u)return t}}(t),n&&I.set(t,n)),!n)return null;const r=n.length;let a=e,o=0;for(;oe,R=e=>"",D=e=>0===e.length?"":e.join(""),A=e=>null==e?"":L(e)||M(e)&&e.toString===C?JSON.stringify(e,null,2):String(e);function U(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function z(e={}){const t=e.locale,n=function(e){const t=d(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(d(e.named.count)||d(e.named.n))?d(e.named.count)?e.named.count:d(e.named.n)?e.named.n:t:t}(e),r=P(e.pluralRules)&&T(t)&&w(e.pluralRules[t])?e.pluralRules[t]:U,a=P(e.pluralRules)&&T(t)&&w(e.pluralRules[t])?U:void 0,o=e.list||[],s=e.named||{};d(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(n,s);function l(t){const n=w(e.messages)?e.messages(t):!!P(e.messages)&&e.messages[t];return n||(e.parent?e.parent.message(t):R)}const c=M(e.processor)&&w(e.processor.normalize)?e.processor.normalize:D,i=M(e.processor)&&w(e.processor.interpolate)?e.processor.interpolate:A,u={list:e=>o[e],named:e=>s[e],plural:e=>e[r(n,e.length,a)],linked:(t,n)=>{const r=l(t)(u);return T(n)?(a=n,e.modifiers?e.modifiers[a]:j)(r):r;var a},message:l,type:M(e.processor)&&T(e.processor.type)?e.processor.type:"text",interpolate:i,normalize:c};return u}function J(e){throw e}function V(e,t,n){const r={start:e,end:t};return null!=n&&(r.source=n),r}const q=String.fromCharCode(8232),B=String.fromCharCode(8233);function G(e){const t=e;let n=0,r=1,a=1,o=0;const s=e=>"\r"===t[e]&&"\n"===t[e+1],l=e=>t[e]===B,c=e=>t[e]===q,i=e=>s(e)||(e=>"\n"===t[e])(e)||l(e)||c(e),u=e=>s(e)||l(e)||c(e)?"\n":t[e];function f(){return o=0,i(n)&&(r++,a=0),s(n)&&n++,n++,a++,t[n]}return{index:()=>n,line:()=>r,column:()=>a,peekOffset:()=>o,charAt:u,currentChar:()=>u(n),currentPeek:()=>u(n+o),next:f,peek:function(){return s(n+o)&&o++,o++,t[n+o]},reset:function(){n=0,r=1,a=1,o=0},resetPeek:function(e=0){o=e},skipToPeek:function(){const e=n+o;for(;e!==n;)f();o=0}}}const Y=void 0;function K(e,t={}){const n=!1!==t.location,r=G(e),a=()=>r.index(),o=()=>{return e=r.line(),t=r.column(),n=r.index(),{line:e,column:t,offset:n};var e,t,n},s=o(),l=a(),c={currentType:14,offset:l,startLoc:s,endLoc:s,lastType:14,lastOffset:l,lastStartLoc:s,lastEndLoc:s,braceNest:0,inLinked:!1,text:""},i=()=>c,{onError:u}=t;function f(e,t,r){e.endLoc=o(),e.currentType=t;const a={type:t};return n&&(a.loc=V(e.startLoc,e.endLoc)),null!=r&&(a.value=r),a}const m=e=>f(e,14);function p(e,t){return e.currentChar()===t?(e.next(),t):(o(),"")}function g(e){let t="";for(;" "===e.currentPeek()||"\n"===e.currentPeek();)t+=e.currentPeek(),e.peek();return t}function d(e){const t=g(e);return e.skipToPeek(),t}function b(e){if(e===Y)return!1;const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||95===t}function h(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r=function(e){if(e===Y)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function k(e){g(e);const t="|"===e.currentPeek();return e.resetPeek(),t}function _(e,t=!0){const n=(t=!1,r="",a=!1)=>{const o=e.currentPeek();return"{"===o?"%"!==r&&t:"@"!==o&&o?"%"===o?(e.peek(),n(t,"%",!0)):"|"===o?!("%"!==r&&!a)||!(" "===r||"\n"===r):" "===o?(e.peek(),n(!0," ",a)):"\n"!==o||(e.peek(),n(!0,"\n",a)):"%"===r||t},r=n();return t&&e.resetPeek(),r}function v(e,t){const n=e.currentChar();return n===Y?Y:t(n)?(e.next(),n):null}function y(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||t>=48&&t<=57||95===t||36===t}))}function F(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57}))}function L(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}))}function w(e){let t="",n="";for(;t=F(e);)n+=t;return n}function T(e){const t=e.currentChar();switch(t){case"\\":case"'":return e.next(),`\\${t}`;case"u":return x(e,t,4);case"U":return x(e,t,6);default:return o(),""}}function x(e,t,n){p(e,t);let r="";for(let t=0;t=1&&o(),e.next(),n=f(t,2,"{"),d(e),t.braceNest++,n;case"}":return t.braceNest>0&&2===t.currentType&&o(),e.next(),n=f(t,3,"}"),t.braceNest--,t.braceNest>0&&d(e),t.inLinked&&0===t.braceNest&&(t.inLinked=!1),n;case"@":return t.braceNest>0&&o(),n=$(e,t)||m(t),t.braceNest=0,n;default:let r=!0,a=!0,s=!0;if(k(e))return t.braceNest>0&&o(),n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(t.braceNest>0&&(5===t.currentType||6===t.currentType||7===t.currentType))return o(),t.braceNest=0,M(e,t);if(r=function(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r=b(e.currentPeek());return e.resetPeek(),r}(e,t))return n=f(t,5,function(e){d(e);let t="",n="";for(;t=y(e);)n+=t;return e.currentChar()===Y&&o(),n}(e)),d(e),n;if(a=h(e,t))return n=f(t,6,function(e){d(e);let t="";return"-"===e.currentChar()?(e.next(),t+=`-${w(e)}`):t+=w(e),e.currentChar()===Y&&o(),t}(e)),d(e),n;if(s=function(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,t))return n=f(t,7,function(e){d(e),p(e,"'");let t="",n="";const r=e=>"'"!==e&&"\n"!==e;for(;t=v(e,r);)n+="\\"===t?T(e):t;const a=e.currentChar();return"\n"===a||a===Y?(o(),"\n"===a&&(e.next(),p(e,"'")),n):(p(e,"'"),n)}(e)),d(e),n;if(!r&&!a&&!s)return n=f(t,13,function(e){d(e);let t="",n="";const r=e=>"{"!==e&&"}"!==e&&" "!==e&&"\n"!==e;for(;t=v(e,r);)n+=t;return n}(e)),o(),d(e),n}return n}function $(e,t){const{currentType:n}=t;let r=null;const a=e.currentChar();switch(8!==n&&9!==n&&12!==n&&10!==n||"\n"!==a&&" "!==a||o(),a){case"@":return e.next(),r=f(t,8,"@"),t.inLinked=!0,r;case".":return d(e),e.next(),f(t,9,".");case":":return d(e),e.next(),f(t,10,":");default:return k(e)?(r=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,r):function(e,t){const{currentType:n}=t;if(8!==n)return!1;g(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,t)||function(e,t){const{currentType:n}=t;if(8!==n&&12!==n)return!1;g(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,t)?(d(e),$(e,t)):function(e,t){const{currentType:n}=t;if(9!==n)return!1;g(e);const r=b(e.currentPeek());return e.resetPeek(),r}(e,t)?(d(e),f(t,12,function(e){let t="",n="";for(;t=y(e);)n+=t;return n}(e))):function(e,t){const{currentType:n}=t;if(10!==n)return!1;const r=()=>{const t=e.currentPeek();return"{"===t?b(e.peek()):!("@"===t||"%"===t||"|"===t||":"===t||"."===t||" "===t||!t)&&("\n"===t?(e.peek(),r()):b(t))},a=r();return e.resetPeek(),a}(e,t)?(d(e),"{"===a?C(e,t)||r:f(t,11,function(e){const t=(n=!1,r)=>{const a=e.currentChar();return"{"!==a&&"%"!==a&&"@"!==a&&"|"!==a&&a?" "===a?r:"\n"===a?(r+=a,e.next(),t(n,r)):(r+=a,e.next(),t(!0,r)):r};return t(!1,"")}(e))):(8===n&&o(),t.braceNest=0,t.inLinked=!1,M(e,t))}}function M(e,t){let n={type:14};if(t.braceNest>0)return C(e,t)||m(t);if(t.inLinked)return $(e,t)||m(t);const r=e.currentChar();switch(r){case"{":return C(e,t)||m(t);case"}":return o(),e.next(),f(t,3,"}");case"@":return $(e,t)||m(t);default:if(k(e))return n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(_(e))return f(t,0,function(e){const t=n=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?_(e)?(n+=r,e.next(),t(n)):n:"|"===r?n:" "===r||"\n"===r?_(e)?(n+=r,e.next(),t(n)):k(e)?n:(n+=r,e.next(),t(n)):(n+=r,e.next(),t(n)):n};return t("")}(e));if("%"===r)return e.next(),f(t,4,"%")}return n}return{nextToken:function(){const{currentType:e,offset:t,startLoc:n,endLoc:s}=c;return c.lastType=e,c.lastOffset=t,c.lastStartLoc=n,c.lastEndLoc=s,c.offset=a(),c.startLoc=o(),r.currentChar()===Y?f(c,14):M(r,c)},currentOffset:a,currentPosition:o,context:i}}const Z=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function Q(e,t,n){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(t||n,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function X(e={}){const t=!1!==e.location,{onError:n}=e;function r(e,n,r){const a={type:e,start:n,end:n};return t&&(a.loc={start:r,end:r}),a}function a(e,n,r,a){e.end=n,a&&(e.type=a),t&&e.loc&&(e.loc.end=r)}function o(e,t){const n=e.context(),o=r(3,n.offset,n.startLoc);return o.value=t,a(o,e.currentOffset(),e.currentPosition()),o}function s(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(5,o,s);return l.index=parseInt(t,10),e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function l(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(4,o,s);return l.key=t,e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function c(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(9,o,s);return l.value=t.replace(Z,Q),e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function i(e){const t=e.context(),n=r(6,t.offset,t.startLoc);let o=e.nextToken();if(9===o.type){const t=function(e){const t=e.nextToken(),n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(8,o,s);return 12!==t.type?(l.value="",a(l,o,s),{nextConsumeToken:t,node:l}):(null==t.value&&ee(t),l.value=t.value||"",a(l,e.currentOffset(),e.currentPosition()),{node:l})}(e);n.modifier=t.node,o=t.nextConsumeToken||e.nextToken()}switch(10!==o.type&&ee(o),o=e.nextToken(),2===o.type&&(o=e.nextToken()),o.type){case 11:null==o.value&&ee(o),n.key=function(e,t){const n=e.context(),o=r(7,n.offset,n.startLoc);return o.value=t,a(o,e.currentOffset(),e.currentPosition()),o}(e,o.value||"");break;case 5:null==o.value&&ee(o),n.key=l(e,o.value||"");break;case 6:null==o.value&&ee(o),n.key=s(e,o.value||"");break;case 7:null==o.value&&ee(o),n.key=c(e,o.value||"");break;default:const t=e.context(),i=r(7,t.offset,t.startLoc);return i.value="",a(i,t.offset,t.startLoc),n.key=i,a(n,t.offset,t.startLoc),{nextConsumeToken:o,node:n}}return a(n,e.currentOffset(),e.currentPosition()),{node:n}}function u(e){const t=e.context(),n=r(2,1===t.currentType?e.currentOffset():t.offset,1===t.currentType?t.endLoc:t.startLoc);n.items=[];let u=null;do{const t=u||e.nextToken();switch(u=null,t.type){case 0:null==t.value&&ee(t),n.items.push(o(e,t.value||""));break;case 6:null==t.value&&ee(t),n.items.push(s(e,t.value||""));break;case 5:null==t.value&&ee(t),n.items.push(l(e,t.value||""));break;case 7:null==t.value&&ee(t),n.items.push(c(e,t.value||""));break;case 8:const r=i(e);n.items.push(r.node),u=r.nextConsumeToken||null}}while(14!==t.currentType&&1!==t.currentType);return a(n,1===t.currentType?t.lastOffset:e.currentOffset(),1===t.currentType?t.lastEndLoc:e.currentPosition()),n}function f(e){const t=e.context(),{offset:n,startLoc:o}=t,s=u(e);return 14===t.currentType?s:function(e,t,n,o){const s=e.context();let l=0===o.items.length;const c=r(1,t,n);c.cases=[],c.cases.push(o);do{const t=u(e);l||(l=0===t.items.length),c.cases.push(t)}while(14!==s.currentType);return a(c,e.currentOffset(),e.currentPosition()),c}(e,n,o,s)}return{parse:function(n){const o=K(n,_({},e)),s=o.context(),l=r(0,s.offset,s.startLoc);return t&&l.loc&&(l.loc.source=n),l.body=f(o),a(l,o.currentOffset(),o.currentPosition()),l}}}function ee(e){if(14===e.type)return"EOF";const t=(e.value||"").replace(/\r?\n/gu,"\\n");return t.length>10?t.slice(0,9)+"…":t}function te(e,t){for(let n=0;nn,helper:e=>(n.helpers.add(e),e)}}(e);n.helper("normalize"),e.body&&ne(e.body,n);const r=n.context();e.helpers=Array.from(r.helpers)}function ae(e,t){const{helper:n}=e;switch(t.type){case 0:!function(e,t){t.body?ae(e,t.body):e.push("null")}(e,t);break;case 1:!function(e,t){const{helper:n,needIndent:r}=e;if(t.cases.length>1){e.push(`${n("plural")}([`),e.indent(r());const a=t.cases.length;for(let n=0;n{const n=T(t.mode)?t.mode:"normal",r=T(t.filename)?t.filename:"message.intl",a=t.needIndent?t.needIndent:"arrow"!==n,o=e.helpers||[],s=function(e,t){const{filename:n,breakLineCode:r,needIndent:a}=t,o={source:e.loc.source,filename:n,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:a,indentLevel:0};function s(e,t){o.code+=e}function l(e,t=!0){const n=t?r:"";s(a?n+" ".repeat(e):n)}return{context:()=>o,push:s,indent:function(e=!0){const t=++o.indentLevel;e&&l(t)},deindent:function(e=!0){const t=--o.indentLevel;e&&l(t)},newline:function(){l(o.indentLevel)},helper:e=>`_${e}`,needIndent:()=>o.needIndent}}(e,{mode:n,filename:r,sourceMap:!!t.sourceMap,breakLineCode:null!=t.breakLineCode?t.breakLineCode:"arrow"===n?";":"\n",needIndent:a});s.push("normal"===n?"function __msg__ (ctx) {":"(ctx) => {"),s.indent(a),o.length>0&&(s.push(`const { ${o.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),s.newline()),s.push("return "),ae(s,e),s.deindent(a),s.push("}");const{code:l,map:c}=s.context();return{ast:e,code:l,map:c?c.toJSON():void 0}})(r,n)}let se;let le=0;function ce(e={}){const t=T(e.version)?e.version:"9.1.7",n=T(e.locale)?e.locale:"en-US",r=L(e.fallbackLocale)||M(e.fallbackLocale)||T(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:n,a=M(e.messages)?e.messages:{[n]:{}},o=M(e.datetimeFormats)?e.datetimeFormats:{[n]:{}},s=M(e.numberFormats)?e.numberFormats:{[n]:{}},l=_({},e.modifiers||{},{upper:e=>T(e)?e.toUpperCase():e,lower:e=>T(e)?e.toLowerCase():e,capitalize:e=>T(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),c=e.pluralRules||{},i=w(e.missing)?e.missing:null,u=!x(e.missingWarn)&&!b(e.missingWarn)||e.missingWarn,f=!x(e.fallbackWarn)&&!b(e.fallbackWarn)||e.fallbackWarn,m=!!e.fallbackFormat,p=!!e.unresolving,g=w(e.postTranslation)?e.postTranslation:null,d=M(e.processor)?e.processor:null,h=!x(e.warnHtmlMessage)||e.warnHtmlMessage,v=!!e.escapeParameter,y=w(e.messageCompiler)?e.messageCompiler:se,F=w(e.onWarn)?e.onWarn:k,C=e,$=P(C.__datetimeFormatters)?C.__datetimeFormatters:new Map,O=P(C.__numberFormatters)?C.__numberFormatters:new Map,W=P(C.__meta)?C.__meta:{};le++;return{version:t,cid:le,locale:n,fallbackLocale:r,messages:a,datetimeFormats:o,numberFormats:s,modifiers:l,pluralRules:c,missing:i,missingWarn:u,fallbackWarn:f,fallbackFormat:m,unresolving:p,postTranslation:g,processor:d,warnHtmlMessage:h,escapeParameter:v,messageCompiler:y,onWarn:F,__datetimeFormatters:$,__numberFormatters:O,__meta:W}}function ie(e,t,n,r,a){const{missing:o}=e;if(null!==o){const r=o(e,n,t,a);return T(r)?r:t}return t}function ue(e,t,n){const r=e;r.__localeChainCache||(r.__localeChainCache=new Map);let a=r.__localeChainCache.get(n);if(!a){a=[];let e=[n];for(;L(e);)e=fe(a,e,t);const o=L(t)?t:M(t)?t.default?t.default:null:t;e=T(o)?[o]:o,L(e)&&fe(a,e,!1),r.__localeChainCache.set(n,a)}return a}function fe(e,t,n){let r=!0;for(let a=0;ae;let be=Object.create(null);const he=()=>"",ke=e=>w(e);function _e(e,...t){const{fallbackFormat:n,postTranslation:r,unresolving:a,fallbackLocale:o,messages:s}=e,[l,c]=ye(...t),i=(x(c.missingWarn),x(c.fallbackWarn),x(c.escapeParameter)?c.escapeParameter:e.escapeParameter),u=!!c.resolvedMessage,f=T(c.default)||x(c.default)?x(c.default)?l:c.default:n?l:"",m=n||""!==f,p=T(c.locale)?c.locale:e.locale;i&&function(e){L(e.list)?e.list=e.list.map((e=>T(e)?v(e):e)):P(e.named)&&Object.keys(e.named).forEach((t=>{T(e.named[t])&&(e.named[t]=v(e.named[t]))}))}(c);let[g,b,h]=u?[l,p,s[p]||{}]:function(e,t,n,r,a,o){const{messages:s}=e,l=ue(e,r,n);let c,i={},u=null;const f="translate";for(let n=0;n{_=!0}));if(_)return g;const F=function(e,t,n){return t(n)}(0,y,z(function(e,t,n,r){const{modifiers:a,pluralRules:o}=e,s={locale:t,modifiers:a,pluralRules:o,messages:r=>{const a=E(n,r);if(T(a)){let n=!1;const o=ve(e,r,t,a,r,(()=>{n=!0}));return n?he:o}return ke(a)?a:he}};e.processor&&(s.processor=e.processor);r.list&&(s.list=r.list);r.named&&(s.named=r.named);d(r.plural)&&(s.pluralIndex=r.plural);return s}(e,b,h,c)));return r?r(F):F}function ve(e,t,n,r,a,o){const{messageCompiler:s,warnHtmlMessage:l}=e;if(ke(r)){const e=r;return e.locale=e.locale||n,e.key=e.key||t,e}const c=s(r,function(e,t,n,r,a,o){return{warnHtmlMessage:a,onError:e=>{throw o&&o(e),e},onCacheKey:e=>((e,t,n)=>g({l:e,k:t,s:n}))(t,n,e)}}(0,n,a,0,l,o));return c.locale=n,c.key=t,c.source=r,c}function ye(...e){const[t,n,r]=e,a={};if(!T(t)&&!d(t)&&!ke(t))throw Error(14);const o=d(t)?String(t):(ke(t),t);return d(n)?a.plural=n:T(n)?a.default=n:M(n)&&!h(n)?a.named=n:L(n)&&(a.list=n),d(r)?a.plural=r:T(r)?a.default=r:M(r)&&_(a,r),[o,a]}function Fe(e,...t){const{datetimeFormats:n,unresolving:r,fallbackLocale:a}=e,{__datetimeFormatters:o}=e,[s,l,c,i]=Le(...t);x(c.missingWarn);x(c.fallbackWarn);const u=!!c.part,f=T(c.locale)?c.locale:e.locale,m=ue(e,a,f);if(!T(s)||""===s)return new Intl.DateTimeFormat(f).format(l);let p,g={},d=null;for(let t=0;te(r,a,t()||void 0,o)}function Ie(e,t){const{messages:n,__i18n:r}=t,a=M(n)?n:L(r)?{}:{[e]:{}};if(L(r)&&r.forEach((({locale:e,resource:t})=>{e?(a[e]=a[e]||{},He(t,a[e])):He(t,a)})),t.flatJson)for(const e in a)F(a,e)&&H(a[e]);return a}const Ee=e=>!P(e)||L(e);function He(e,t){if(Ee(e)||Ee(t))throw Error(20);for(const n in e)F(e,n)&&(Ee(e[n])||Ee(t[n])?t[n]=e[n]:He(e[n],t[n]))}function je(t={}){const{__root:s}=t,l=void 0===s;let c=!x(t.inheritLocale)||t.inheritLocale;const i=e(s&&c?s.locale.value:T(t.locale)?t.locale:"en-US"),u=e(s&&c?s.fallbackLocale.value:T(t.fallbackLocale)||L(t.fallbackLocale)||M(t.fallbackLocale)||!1===t.fallbackLocale?t.fallbackLocale:i.value),f=e(Ie(i.value,t)),m=e(M(t.datetimeFormats)?t.datetimeFormats:{[i.value]:{}}),p=e(M(t.numberFormats)?t.numberFormats:{[i.value]:{}});let g=s?s.missingWarn:!x(t.missingWarn)&&!b(t.missingWarn)||t.missingWarn,h=s?s.fallbackWarn:!x(t.fallbackWarn)&&!b(t.fallbackWarn)||t.fallbackWarn,k=s?s.fallbackRoot:!x(t.fallbackRoot)||t.fallbackRoot,v=!!t.fallbackFormat,y=w(t.missing)?t.missing:null,F=w(t.missing)?Se(t.missing):null,C=w(t.postTranslation)?t.postTranslation:null,$=!x(t.warnHtmlMessage)||t.warnHtmlMessage,O=!!t.escapeParameter;const W=s?s.modifiers:M(t.modifiers)?t.modifiers:{};let N,S=t.pluralRules||s&&s.pluralRules;N=ce({version:"9.1.7",locale:i.value,fallbackLocale:u.value,messages:f.value,datetimeFormats:m.value,numberFormats:p.value,modifiers:W,pluralRules:S,missing:null===F?void 0:F,missingWarn:g,fallbackWarn:h,fallbackFormat:v,unresolving:!0,postTranslation:null===C?void 0:C,warnHtmlMessage:$,escapeParameter:O,__datetimeFormatters:M(N)?N.__datetimeFormatters:void 0,__numberFormatters:M(N)?N.__numberFormatters:void 0,__v_emitter:M(N)?N.__v_emitter:void 0,__meta:{framework:"vue"}}),ge(N,i.value,u.value);const I=n({get:()=>i.value,set:e=>{i.value=e,N.locale=i.value}}),H=n({get:()=>u.value,set:e=>{u.value=e,N.fallbackLocale=u.value,ge(N,i.value,e)}}),j=n((()=>f.value)),R=n((()=>m.value)),D=n((()=>p.value));function A(e,t,n,r,a,o){let l;if(l=e(N),d(l)&&-1===l){const[e,n]=t();return s&&k?r(s):a(e)}if(o(l))return l;throw Error(14)}function U(...e){return A((t=>_e(t,...e)),(()=>ye(...e)),0,(t=>t.t(...e)),(e=>e),(e=>T(e)))}const z={normalize:function(e){return e.map((e=>T(e)?a(o,null,e,0):e))},interpolate:e=>e,type:"vnode"};function J(e){return f.value[e]||{}}Ne++,s&&(r(s.locale,(e=>{c&&(i.value=e,N.locale=e,ge(N,i.value,u.value))})),r(s.fallbackLocale,(e=>{c&&(u.value=e,N.fallbackLocale=e,ge(N,i.value,u.value))})));return{id:Ne,locale:I,fallbackLocale:H,get inheritLocale(){return c},set inheritLocale(e){c=e,e&&s&&(i.value=s.locale.value,u.value=s.fallbackLocale.value,ge(N,i.value,u.value))},get availableLocales(){return Object.keys(f.value).sort()},messages:j,datetimeFormats:R,numberFormats:D,get modifiers(){return W},get pluralRules(){return S||{}},get isGlobal(){return l},get missingWarn(){return g},set missingWarn(e){g=e,N.missingWarn=g},get fallbackWarn(){return h},set fallbackWarn(e){h=e,N.fallbackWarn=h},get fallbackRoot(){return k},set fallbackRoot(e){k=e},get fallbackFormat(){return v},set fallbackFormat(e){v=e,N.fallbackFormat=v},get warnHtmlMessage(){return $},set warnHtmlMessage(e){$=e,N.warnHtmlMessage=e},get escapeParameter(){return O},set escapeParameter(e){O=e,N.escapeParameter=e},t:U,rt:function(...e){const[t,n,r]=e;if(r&&!P(r))throw Error(15);return U(t,n,_({resolvedMessage:!0},r||{}))},d:function(...e){return A((t=>Fe(t,...e)),(()=>Le(...e)),0,(t=>t.d(...e)),(()=>""),(e=>T(e)))},n:function(...e){return A((t=>Te(t,...e)),(()=>xe(...e)),0,(t=>t.n(...e)),(()=>""),(e=>T(e)))},te:function(e,t){return null!==E(J(T(t)?t:i.value),e)},tm:function(e){const t=function(e){let t=null;const n=ue(N,u.value,i.value);for(let r=0;r{let n;const r=t;try{r.processor=z,n=_e(r,...e)}finally{r.processor=null}return n}),(()=>ye(...e)),0,(t=>t[$e](...e)),(e=>[a(o,null,e,0)]),(e=>L(e)))},[Oe]:function(...e){return A((t=>Te(t,...e)),(()=>xe(...e)),0,(t=>t[Oe](...e)),(()=>[]),(e=>T(e)||L(e)))},[Me]:function(...e){return A((t=>Fe(t,...e)),(()=>Le(...e)),0,(t=>t[Me](...e)),(()=>[]),(e=>T(e)||L(e)))},[We]:function(e){S=e,N.pluralRules=S}}}function Re(e={}){const t=je(function(e){const t=T(e.locale)?e.locale:"en-US",n=T(e.fallbackLocale)||L(e.fallbackLocale)||M(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:t,r=w(e.missing)?e.missing:void 0,a=!x(e.silentTranslationWarn)&&!b(e.silentTranslationWarn)||!e.silentTranslationWarn,o=!x(e.silentFallbackWarn)&&!b(e.silentFallbackWarn)||!e.silentFallbackWarn,s=!x(e.fallbackRoot)||e.fallbackRoot,l=!!e.formatFallbackMessages,c=M(e.modifiers)?e.modifiers:{},i=e.pluralizationRules,u=w(e.postTranslation)?e.postTranslation:void 0,f=!T(e.warnHtmlInMessage)||"off"!==e.warnHtmlInMessage,m=!!e.escapeParameterHtml,p=!x(e.sync)||e.sync;let g=e.messages;if(M(e.sharedMessages)){const t=e.sharedMessages;g=Object.keys(t).reduce(((e,n)=>{const r=e[n]||(e[n]={});return _(r,t[n]),e}),g||{})}const{__i18n:d,__root:h}=e;return{locale:t,fallbackLocale:n,messages:g,flatJson:e.flatJson,datetimeFormats:e.datetimeFormats,numberFormats:e.numberFormats,missing:r,missingWarn:a,fallbackWarn:o,fallbackRoot:s,fallbackFormat:l,modifiers:c,pluralRules:i,postTranslation:u,warnHtmlMessage:f,escapeParameter:m,inheritLocale:p,__i18n:d,__root:h}}(e)),n={id:t.id,get locale(){return t.locale.value},set locale(e){t.locale.value=e},get fallbackLocale(){return t.fallbackLocale.value},set fallbackLocale(e){t.fallbackLocale.value=e},get messages(){return t.messages.value},get datetimeFormats(){return t.datetimeFormats.value},get numberFormats(){return t.numberFormats.value},get availableLocales(){return t.availableLocales},get formatter(){return{interpolate:()=>[]}},set formatter(e){},get missing(){return t.getMissingHandler()},set missing(e){t.setMissingHandler(e)},get silentTranslationWarn(){return x(t.missingWarn)?!t.missingWarn:t.missingWarn},set silentTranslationWarn(e){t.missingWarn=x(e)?!e:e},get silentFallbackWarn(){return x(t.fallbackWarn)?!t.fallbackWarn:t.fallbackWarn},set silentFallbackWarn(e){t.fallbackWarn=x(e)?!e:e},get modifiers(){return t.modifiers},get formatFallbackMessages(){return t.fallbackFormat},set formatFallbackMessages(e){t.fallbackFormat=e},get postTranslation(){return t.getPostTranslationHandler()},set postTranslation(e){t.setPostTranslationHandler(e)},get sync(){return t.inheritLocale},set sync(e){t.inheritLocale=e},get warnHtmlInMessage(){return t.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(e){t.warnHtmlMessage="off"!==e},get escapeParameterHtml(){return t.escapeParameter},set escapeParameterHtml(e){t.escapeParameter=e},get preserveDirectiveContent(){return!0},set preserveDirectiveContent(e){},get pluralizationRules(){return t.pluralRules||{}},__composer:t,t(...e){const[n,r,a]=e,o={};let s=null,l=null;if(!T(n))throw Error(15);const c=n;return T(r)?o.locale=r:L(r)?s=r:M(r)&&(l=r),L(a)?s=a:M(a)&&(l=a),t.t(c,s||l||{},o)},rt:(...e)=>t.rt(...e),tc(...e){const[n,r,a]=e,o={plural:1};let s=null,l=null;if(!T(n))throw Error(15);const c=n;return T(r)?o.locale=r:d(r)?o.plural=r:L(r)?s=r:M(r)&&(l=r),T(a)?o.locale=a:L(a)?s=a:M(a)&&(l=a),t.t(c,s||l||{},o)},te:(e,n)=>t.te(e,n),tm:e=>t.tm(e),getLocaleMessage:e=>t.getLocaleMessage(e),setLocaleMessage(e,n){t.setLocaleMessage(e,n)},mergeLocaleMessage(e,n){t.mergeLocaleMessage(e,n)},d:(...e)=>t.d(...e),getDateTimeFormat:e=>t.getDateTimeFormat(e),setDateTimeFormat(e,n){t.setDateTimeFormat(e,n)},mergeDateTimeFormat(e,n){t.mergeDateTimeFormat(e,n)},n:(...e)=>t.n(...e),getNumberFormat:e=>t.getNumberFormat(e),setNumberFormat(e,n){t.setNumberFormat(e,n)},mergeNumberFormat(e,n){t.mergeNumberFormat(e,n)},getChoiceIndex:(e,t)=>-1,__onComponentInstanceCreated(t){const{componentInstanceCreatedListener:r}=e;r&&r(t,n)}};return n}const De={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:e=>"parent"===e||"global"===e,default:"parent"},i18n:{type:Object}},Ae={name:"i18n-t",props:_({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:e=>d(e)||!isNaN(e)}},De),setup(e,t){const{slots:n,attrs:r}=t,a=e.i18n||Ke({useScope:e.scope}),o=Object.keys(n).filter((e=>"_"!==e));return()=>{const n={};e.locale&&(n.locale=e.locale),void 0!==e.plural&&(n.plural=T(e.plural)?+e.plural:e.plural);const c=function({slots:e},t){return 1===t.length&&"default"===t[0]?e.default?e.default():[]:t.reduce(((t,n)=>{const r=e[n];return r&&(t[n]=r()),t}),{})}(t,o),i=a[$e](e.keypath,c,n),u=_({},r);return T(e.tag)||P(e.tag)?s(e.tag,u,i):s(l,u,i)}}};function Ue(e,t,n,r){const{slots:a,attrs:o}=t;return()=>{const t={part:!0};let c={};e.locale&&(t.locale=e.locale),T(e.format)?t.key=e.format:P(e.format)&&(T(e.format.key)&&(t.key=e.format.key),c=Object.keys(e.format).reduce(((t,r)=>n.includes(r)?_({},t,{[r]:e.format[r]}):t),{}));const i=r(e.value,t,c);let u=[t.key];L(i)?u=i.map(((e,t)=>{const n=a[e.type];return n?n({[e.type]:e.value,index:t,parts:i}):[e.value]})):T(i)&&(u=[i]);const f=_({},o);return T(e.tag)||P(e.tag)?s(e.tag,f,u):s(l,f,u)}}const ze=["localeMatcher","style","unit","unitDisplay","currency","currencyDisplay","useGrouping","numberingSystem","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","notation","formatMatcher"],Je={name:"i18n-n",props:_({value:{type:Number,required:!0},format:{type:[String,Object]}},De),setup(e,t){const n=e.i18n||Ke({useScope:"parent"});return Ue(e,t,ze,((...e)=>n[Oe](...e)))}},Ve=["dateStyle","timeStyle","fractionalSecondDigits","calendar","dayPeriod","numberingSystem","localeMatcher","timeZone","hour12","hourCycle","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"],qe={name:"i18n-d",props:_({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},De),setup(e,t){const n=e.i18n||Ke({useScope:"parent"});return Ue(e,t,Ve,((...e)=>n[Me](...e)))}};function Be(e){const t=(t,{instance:n,value:r})=>{if(!n||!n.$)throw Error(22);const a=function(e,t){const n=e;if("composition"===e.mode)return n.__getInstance(t)||e.global;{const r=n.__getInstance(t);return null!=r?r.__composer:e.global.__composer}}(e,n.$),o=function(e){if(T(e))return{path:e};if(M(e)){if(!("path"in e))throw Error(19,"path");return e}throw Error(20)}(r);t.textContent=a.t(...function(e){const{path:t,locale:n,args:r,choice:a,plural:o}=e,s={},l=r||{};T(n)&&(s.locale=n);d(a)&&(s.plural=a);d(o)&&(s.plural=o);return[t,l,s]}(o))};return{beforeMount:t,beforeUpdate:t}}function Ge(e,t){e.locale=t.locale||e.locale,e.fallbackLocale=t.fallbackLocale||e.fallbackLocale,e.missing=t.missing||e.missing,e.silentTranslationWarn=t.silentTranslationWarn||e.silentFallbackWarn,e.silentFallbackWarn=t.silentFallbackWarn||e.silentFallbackWarn,e.formatFallbackMessages=t.formatFallbackMessages||e.formatFallbackMessages,e.postTranslation=t.postTranslation||e.postTranslation,e.warnHtmlInMessage=t.warnHtmlInMessage||e.warnHtmlInMessage,e.escapeParameterHtml=t.escapeParameterHtml||e.escapeParameterHtml,e.sync=t.sync||e.sync,e.__composer[We](t.pluralizationRules||e.pluralizationRules);const n=Ie(e.locale,{messages:t.messages,__i18n:t.__i18n});return Object.keys(n).forEach((t=>e.mergeLocaleMessage(t,n[t]))),t.datetimeFormats&&Object.keys(t.datetimeFormats).forEach((n=>e.mergeDateTimeFormat(n,t.datetimeFormats[n]))),t.numberFormats&&Object.keys(t.numberFormats).forEach((n=>e.mergeNumberFormat(n,t.numberFormats[n]))),e}function Ye(e={}){const n=!x(e.legacy)||e.legacy,r=!!e.globalInjection,a=new Map,o=n?Re(e):je(e),s=p(""),l={get mode(){return n?"legacy":"composition"},async install(e,...a){e.__VUE_I18N_SYMBOL__=s,e.provide(e.__VUE_I18N_SYMBOL__,l),!n&&r&&function(e,t){const n=Object.create(null);Ze.forEach((e=>{const r=Object.getOwnPropertyDescriptor(t,e);if(!r)throw Error(22);const a=f(r.value)?{get:()=>r.value.value,set(e){r.value.value=e}}:{get:()=>r.get&&r.get()};Object.defineProperty(n,e,a)})),e.config.globalProperties.$i18n=n,Qe.forEach((n=>{const r=Object.getOwnPropertyDescriptor(t,n);if(!r||!r.value)throw Error(22);Object.defineProperty(e.config.globalProperties,`$${n}`,r)}))}(e,l.global),function(e,t,...n){const r=M(n[0])?n[0]:{},a=!!r.useI18nComponentName;(!x(r.globalInstall)||r.globalInstall)&&(e.component(a?"i18n":Ae.name,Ae),e.component(Je.name,Je),e.component(qe.name,qe)),e.directive("t",Be(t))}(e,l,...a),n&&e.mixin(function(e,n,r){return{beforeCreate(){const a=t();if(!a)throw Error(22);const o=this.$options;if(o.i18n){const t=o.i18n;o.__i18n&&(t.__i18n=o.__i18n),t.__root=n,this.$i18n=this===this.$root?Ge(e,t):Re(t)}else this.$i18n=o.__i18n?this===this.$root?Ge(e,o):Re({__i18n:o.__i18n,__root:n}):e;e.__onComponentInstanceCreated(this.$i18n),r.__setInstance(a,this.$i18n),this.$t=(...e)=>this.$i18n.t(...e),this.$rt=(...e)=>this.$i18n.rt(...e),this.$tc=(...e)=>this.$i18n.tc(...e),this.$te=(e,t)=>this.$i18n.te(e,t),this.$d=(...e)=>this.$i18n.d(...e),this.$n=(...e)=>this.$i18n.n(...e),this.$tm=e=>this.$i18n.tm(e)},mounted(){},beforeUnmount(){const e=t();if(!e)throw Error(22);delete this.$t,delete this.$rt,delete this.$tc,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,r.__deleteInstance(e),delete this.$i18n}}}(o,o.__composer,l))},get global(){return o},__instances:a,__getInstance:e=>a.get(e)||null,__setInstance(e,t){a.set(e,t)},__deleteInstance(e){a.delete(e)}};return l}function Ke(e={}){const n=t();if(null==n)throw Error(16);if(!n.appContext.app.__VUE_I18N_SYMBOL__)throw Error(17);const r=c(n.appContext.app.__VUE_I18N_SYMBOL__);if(!r)throw Error(22);const a="composition"===r.mode?r.global:r.global.__composer,o=h(e)?"__i18n"in n.type?"local":"global":e.useScope?e.useScope:"local";if("global"===o){let t=P(e.messages)?e.messages:{};"__i18nGlobal"in n.type&&(t=Ie(a.locale.value,{messages:t,__i18n:n.type.__i18nGlobal}));const r=Object.keys(t);if(r.length&&r.forEach((e=>{a.mergeLocaleMessage(e,t[e])})),P(e.datetimeFormats)){const t=Object.keys(e.datetimeFormats);t.length&&t.forEach((t=>{a.mergeDateTimeFormat(t,e.datetimeFormats[t])}))}if(P(e.numberFormats)){const t=Object.keys(e.numberFormats);t.length&&t.forEach((t=>{a.mergeNumberFormat(t,e.numberFormats[t])}))}return a}if("parent"===o){let e=function(e,t){let n=null;const r=t.root;let a=t.parent;for(;null!=a;){const t=e;if("composition"===e.mode)n=t.__getInstance(a);else{const e=t.__getInstance(a);null!=e&&(n=e.__composer)}if(null!=n)break;if(r===a)break;a=a.parent}return n}(r,n);return null==e&&(e=a),e}if("legacy"===r.mode)throw Error(18);const s=r;let l=s.__getInstance(n);if(null==l){const t=n.type,r=_({},e);t.__i18n&&(r.__i18n=t.__i18n),a&&(r.__root=a),l=je(r),function(e,t,n){i((()=>{}),t),u((()=>{e.__deleteInstance(t)}),t)}(s,n),s.__setInstance(n,l)}return l}const Ze=["locale","fallbackLocale","availableLocales"],Qe=["t","rt","d","n","tm"];se=function(e,t={}){{const n=(t.onCacheKey||de)(e),r=be[n];if(r)return r;let a=!1;const o=t.onError||J;t.onError=e=>{a=!0,o(e)};const{code:s}=oe(e,t),l=new Function(`return ${s}`)();return a?l:be[n]=l}};export{qe as DatetimeFormat,Je as NumberFormat,Ae as Translation,Ce as VERSION,Ye as createI18n,Ke as useI18n,Be as vTDirective}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..a450dc189098b15bdbab2f79a31be50ae06ddfe2 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.esm-bundler.js @@ -0,0 +1,2226 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, hasOwn, isObject, isBoolean, isString, isRegExp, isFunction, assign, isNumber, warn, createEmitter, isEmptyObject } from '@intlify/shared'; +import { createCompileError, handleFlatJson, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, getLocaleChain, registerMessageCompiler, compileToFunction, setDevToolsHook } from '@intlify/core-base'; +import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; +import { setupDevtoolsPlugin } from '@vue/devtools-api'; +import { VueDevToolsLabels, VueDevToolsPlaceholders, VueDevToolsTimelineColors } from '@intlify/vue-devtools'; + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +const VERSION = '9.1.7'; +/** + * This is only called in esm-bundler builds. + * istanbul-ignore-next + */ +function initFeatureFlags() { + let needWarn = false; + if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true; + } + if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_LEGACY_API__ = true; + } + if (typeof __VUE_I18N_PROD_DEVTOOLS__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_PROD_DEVTOOLS__ = false; + } + if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') { + getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false; + } + if ((process.env.NODE_ENV !== 'production') && typeof true === 'boolean') { + needWarn = true; + } + if ((process.env.NODE_ENV !== 'production') && needWarn) { + console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` + + `configure your bundler to explicitly replace feature flag globals ` + + `with boolean literals to get proper tree-shaking in the final bundle.`); + } +} + +const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` +}; +function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); +} + +function createI18nError(code, ...args) { + return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined); +} +const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` +}; + +const DEVTOOLS_META = '__INTLIFY_META__'; +const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); +const DatetimePartsSymbol = makeSymbol('__datetimeParts'); +const NumberPartsSymbol = makeSymbol('__numberParts'); +const EnableEmitter = makeSymbol('__enableEmitter'); +const DisableEmitter = makeSymbol('__disableEmitter'); +const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); +makeSymbol('__intlifyMeta'); +let composerID = 0; +function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, getCurrentInstance() || undefined, type); + }); +} +function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; +} +const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } +} +// for Intlify DevTools +const getMetaInfo = /* #__PURE__*/ () => { + const instance = getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; +}; +/** + * Create composer interface factory + * + * @internal + */ +function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + else { + ret = fn(_context); + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if ((process.env.NODE_ENV !== 'production') && + __root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; +} + +/** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ +function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if ((process.env.NODE_ENV !== 'production') && options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; +} +/** + * create VueI18n interface factory + * + * @internal + */ +function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; +} + +const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } +}; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; + } +}; +function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } +} + +function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; +} + +const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' +]; +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } +}; + +const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' +]; +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } +}; + +function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } +} +function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; +} +function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } +} +function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; +} + +function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); +} + +const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; +let devtoolsApi; +async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); +} +function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any +treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } +} +function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; +} +const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' +}; +function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); +} +function escapeChar(a) { + return ESC[a] || a; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; +} +function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } +} +function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } +} +function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } +} +function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; +} +function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } +} +function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } +} + +// supports compatibility for legacy vue-i18n APIs +function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; +} +function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy) + ? options.legacy + : __VUE_I18N_LEGACY_API__; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __VUE_I18N_LEGACY_API__ && __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : ''); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __VUE_I18N_LEGACY_API__ + ? __legacyMode + ? 'legacy' + : 'composition' + : 'composition'; + }, + // install plugin + async install(app, ...options) { + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + if (__VUE_I18N_FULL_INSTALL__) { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__VUE_I18N_LEGACY_API__ && __legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; +} +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + if ((process.env.NODE_ENV !== 'production')) { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + let emitter = null; + onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && + !false && + target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && + !false && + target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +// register message compiler at vue-i18n +registerMessageCompiler(compileToFunction); +{ + initFeatureFlags(); +} +// NOTE: experimental !! +if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) { + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); +} +if ((process.env.NODE_ENV !== 'production')) ; + +export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.js new file mode 100644 index 0000000000000000000000000000000000000000..ceb9f676ae57b4886890f6d63ef5dab243a02b1e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.js @@ -0,0 +1,5065 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var VueI18n = (function (exports, vue) { + 'use strict'; + + /** + * Original Utilities + * written by kazuya kawaguchi + */ + const inBrowser = typeof window !== 'undefined'; + let mark; + let measure; + { + 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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + 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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; + 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; + } + + 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; + } + + 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; + } + + /** @internal */ + const errorMessages$2 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` + }; + function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$2)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; + } + /** @internal */ + function defaultOnError(error) { + throw error; + } + + function createPosition(line, column, offset) { + return { line, column, offset }; + } + function createLocation(start, end, source) { + const loc = { start, end }; + if (source != null) { + loc.source = source; + } + return loc; + } + + const CHAR_SP = ' '; + const CHAR_CR = '\r'; + const CHAR_LF = '\n'; + const CHAR_LS = String.fromCharCode(0x2028); + const CHAR_PS = String.fromCharCode(0x2029); + function createScanner(str) { + const _buf = str; + let _index = 0; + let _line = 1; + let _column = 1; + let _peekOffset = 0; + const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; + const isLF = (index) => _buf[index] === CHAR_LF; + const isPS = (index) => _buf[index] === CHAR_PS; + const isLS = (index) => _buf[index] === CHAR_LS; + const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); + const index = () => _index; + const line = () => _line; + const column = () => _column; + const peekOffset = () => _peekOffset; + const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; + const currentChar = () => charAt(_index); + const currentPeek = () => charAt(_index + _peekOffset); + function next() { + _peekOffset = 0; + if (isLineEnd(_index)) { + _line++; + _column = 0; + } + if (isCRLF(_index)) { + _index++; + } + _index++; + _column++; + return _buf[_index]; + } + function peek() { + if (isCRLF(_index + _peekOffset)) { + _peekOffset++; + } + _peekOffset++; + return _buf[_index + _peekOffset]; + } + function reset() { + _index = 0; + _line = 1; + _column = 1; + _peekOffset = 0; + } + function resetPeek(offset = 0) { + _peekOffset = offset; + } + function skipToPeek() { + const target = _index + _peekOffset; + // eslint-disable-next-line no-unmodified-loop-condition + while (target !== _index) { + next(); + } + _peekOffset = 0; + } + return { + index, + line, + column, + peekOffset, + charAt, + currentChar, + currentPeek, + next, + peek, + reset, + resetPeek, + skipToPeek + }; + } + + const EOF = undefined; + const LITERAL_DELIMITER = "'"; + const ERROR_DOMAIN$1 = 'tokenizer'; + function createTokenizer(source, options = {}) { + const location = options.location !== false; + const _scnr = createScanner(source); + const currentOffset = () => _scnr.index(); + const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); + const _initLoc = currentPosition(); + const _initOffset = currentOffset(); + const _context = { + currentType: 14 /* EOF */, + offset: _initOffset, + startLoc: _initLoc, + endLoc: _initLoc, + lastType: 14 /* EOF */, + lastOffset: _initOffset, + lastStartLoc: _initLoc, + lastEndLoc: _initLoc, + braceNest: 0, + inLinked: false, + text: '' + }; + const context = () => _context; + const { onError } = options; + function emitError(code, pos, offset, ...args) { + const ctx = context(); + pos.column += offset; + pos.offset += offset; + if (onError) { + const loc = createLocation(ctx.startLoc, pos); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN$1, + args + }); + onError(err); + } + } + function getToken(context, type, value) { + context.endLoc = currentPosition(); + context.currentType = type; + const token = { type }; + if (location) { + token.loc = createLocation(context.startLoc, context.endLoc); + } + if (value != null) { + token.value = value; + } + return token; + } + const getEndToken = (context) => getToken(context, 14 /* EOF */); + function eat(scnr, ch) { + if (scnr.currentChar() === ch) { + scnr.next(); + return ch; + } + else { + emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); + return ''; + } + } + function peekSpaces(scnr) { + let buf = ''; + while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { + buf += scnr.currentPeek(); + scnr.peek(); + } + return buf; + } + function skipSpaces(scnr) { + const buf = peekSpaces(scnr); + scnr.skipToPeek(); + return buf; + } + function isIdentifierStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + cc === 95 // _ + ); + } + function isNumberStart(ch) { + if (ch === EOF) { + return false; + } + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + } + function isNamedIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isListIdentifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); + const ret = isNumberStart(ch); + scnr.resetPeek(); + return ret; + } + function isLiteralStart(scnr, context) { + const { currentType } = context; + if (currentType !== 2 /* BraceLeft */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === LITERAL_DELIMITER; + scnr.resetPeek(); + return ret; + } + function isLinkedDotStart(scnr, context) { + const { currentType } = context; + if (currentType !== 8 /* LinkedAlias */) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === "." /* LinkedDot */; + scnr.resetPeek(); + return ret; + } + function isLinkedModifierStart(scnr, context) { + const { currentType } = context; + if (currentType !== 9 /* LinkedDot */) { + return false; + } + peekSpaces(scnr); + const ret = isIdentifierStart(scnr.currentPeek()); + scnr.resetPeek(); + return ret; + } + function isLinkedDelimiterStart(scnr, context) { + const { currentType } = context; + if (!(currentType === 8 /* LinkedAlias */ || + currentType === 12 /* LinkedModifier */)) { + return false; + } + peekSpaces(scnr); + const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; + scnr.resetPeek(); + return ret; + } + function isLinkedReferStart(scnr, context) { + const { currentType } = context; + if (currentType !== 10 /* LinkedDelimiter */) { + return false; + } + const fn = () => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return isIdentifierStart(scnr.peek()); + } + else if (ch === "@" /* LinkedAlias */ || + ch === "%" /* Modulo */ || + ch === "|" /* Pipe */ || + ch === ":" /* LinkedDelimiter */ || + ch === "." /* LinkedDot */ || + ch === CHAR_SP || + !ch) { + return false; + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(); + } + else { + // other characters + return isIdentifierStart(ch); + } + }; + const ret = fn(); + scnr.resetPeek(); + return ret; + } + function isPluralStart(scnr) { + peekSpaces(scnr); + const ret = scnr.currentPeek() === "|" /* Pipe */; + scnr.resetPeek(); + return ret; + } + function isTextStart(scnr, reset = true) { + const fn = (hasSpace = false, prev = '', detectModulo = false) => { + const ch = scnr.currentPeek(); + if (ch === "{" /* BraceLeft */) { + return prev === "%" /* Modulo */ ? false : hasSpace; + } + else if (ch === "@" /* LinkedAlias */ || !ch) { + return prev === "%" /* Modulo */ ? true : hasSpace; + } + else if (ch === "%" /* Modulo */) { + scnr.peek(); + return fn(hasSpace, "%" /* Modulo */, true); + } + else if (ch === "|" /* Pipe */) { + return prev === "%" /* Modulo */ || detectModulo + ? true + : !(prev === CHAR_SP || prev === CHAR_LF); + } + else if (ch === CHAR_SP) { + scnr.peek(); + return fn(true, CHAR_SP, detectModulo); + } + else if (ch === CHAR_LF) { + scnr.peek(); + return fn(true, CHAR_LF, detectModulo); + } + else { + return true; + } + }; + const ret = fn(); + reset && scnr.resetPeek(); + return ret; + } + function takeChar(scnr, fn) { + const ch = scnr.currentChar(); + if (ch === EOF) { + return EOF; + } + if (fn(ch)) { + scnr.next(); + return ch; + } + return null; + } + function takeIdentifierChar(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 97 && cc <= 122) || // a-z + (cc >= 65 && cc <= 90) || // A-Z + (cc >= 48 && cc <= 57) || // 0-9 + cc === 95 || // _ + cc === 36 // $ + ); + }; + return takeChar(scnr, closure); + } + function takeDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return cc >= 48 && cc <= 57; // 0-9 + }; + return takeChar(scnr, closure); + } + function takeHexDigit(scnr) { + const closure = (ch) => { + const cc = ch.charCodeAt(0); + return ((cc >= 48 && cc <= 57) || // 0-9 + (cc >= 65 && cc <= 70) || // A-F + (cc >= 97 && cc <= 102)); // a-f + }; + return takeChar(scnr, closure); + } + function getDigits(scnr) { + let ch = ''; + let num = ''; + while ((ch = takeDigit(scnr))) { + num += ch; + } + return num; + } + function readText(scnr) { + const fn = (buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "}" /* BraceRight */ || + ch === "@" /* LinkedAlias */ || + !ch) { + return buf; + } + else if (ch === "%" /* Modulo */) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else { + return buf; + } + } + else if (ch === "|" /* Pipe */) { + return buf; + } + else if (ch === CHAR_SP || ch === CHAR_LF) { + if (isTextStart(scnr)) { + buf += ch; + scnr.next(); + return fn(buf); + } + else if (isPluralStart(scnr)) { + return buf; + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + } + else { + buf += ch; + scnr.next(); + return fn(buf); + } + }; + return fn(''); + } + function readNamedIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return name; + } + function readListIdentifier(scnr) { + skipSpaces(scnr); + let value = ''; + if (scnr.currentChar() === '-') { + scnr.next(); + value += `-${getDigits(scnr)}`; + } + else { + value += getDigits(scnr); + } + if (scnr.currentChar() === EOF) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + return value; + } + function readLiteral(scnr) { + skipSpaces(scnr); + eat(scnr, `\'`); + let ch = ''; + let literal = ''; + const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; + while ((ch = takeChar(scnr, fn))) { + if (ch === '\\') { + literal += readEscapeSequence(scnr); + } + else { + literal += ch; + } + } + const current = scnr.currentChar(); + if (current === CHAR_LF || current === EOF) { + emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); + // TODO: Is it correct really? + if (current === CHAR_LF) { + scnr.next(); + eat(scnr, `\'`); + } + return literal; + } + eat(scnr, `\'`); + return literal; + } + function readEscapeSequence(scnr) { + const ch = scnr.currentChar(); + switch (ch) { + case '\\': + case `\'`: + scnr.next(); + return `\\${ch}`; + case 'u': + return readUnicodeEscapeSequence(scnr, ch, 4); + case 'U': + return readUnicodeEscapeSequence(scnr, ch, 6); + default: + emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); + return ''; + } + } + function readUnicodeEscapeSequence(scnr, unicode, digits) { + eat(scnr, unicode); + let sequence = ''; + for (let i = 0; i < digits; i++) { + const ch = takeHexDigit(scnr); + if (!ch) { + emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); + break; + } + sequence += ch; + } + return `\\${unicode}${sequence}`; + } + function readInvalidIdentifier(scnr) { + skipSpaces(scnr); + let ch = ''; + let identifiers = ''; + const closure = (ch) => ch !== "{" /* BraceLeft */ && + ch !== "}" /* BraceRight */ && + ch !== CHAR_SP && + ch !== CHAR_LF; + while ((ch = takeChar(scnr, closure))) { + identifiers += ch; + } + return identifiers; + } + function readLinkedModifier(scnr) { + let ch = ''; + let name = ''; + while ((ch = takeIdentifierChar(scnr))) { + name += ch; + } + return name; + } + function readLinkedRefer(scnr) { + const fn = (detect = false, buf) => { + const ch = scnr.currentChar(); + if (ch === "{" /* BraceLeft */ || + ch === "%" /* Modulo */ || + ch === "@" /* LinkedAlias */ || + ch === "|" /* Pipe */ || + !ch) { + return buf; + } + else if (ch === CHAR_SP) { + return buf; + } + else if (ch === CHAR_LF) { + buf += ch; + scnr.next(); + return fn(detect, buf); + } + else { + buf += ch; + scnr.next(); + return fn(true, buf); + } + }; + return fn(false, ''); + } + function readPlural(scnr) { + skipSpaces(scnr); + const plural = eat(scnr, "|" /* Pipe */); + skipSpaces(scnr); + return plural; + } + // TODO: We need refactoring of token parsing ... + function readTokenInPlaceholder(scnr, context) { + let token = null; + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + if (context.braceNest >= 1) { + emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); + skipSpaces(scnr); + context.braceNest++; + return token; + case "}" /* BraceRight */: + if (context.braceNest > 0 && + context.currentType === 2 /* BraceLeft */) { + emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); + } + scnr.next(); + token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + context.braceNest--; + context.braceNest > 0 && skipSpaces(scnr); + if (context.inLinked && context.braceNest === 0) { + context.inLinked = false; + } + return token; + case "@" /* LinkedAlias */: + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = readTokenInLinked(scnr, context) || getEndToken(context); + context.braceNest = 0; + return token; + default: + let validNamedIdentifier = true; + let validListIdentifier = true; + let validLiteral = true; + if (isPluralStart(scnr)) { + if (context.braceNest > 0) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + } + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (context.braceNest > 0 && + (context.currentType === 5 /* Named */ || + context.currentType === 6 /* List */ || + context.currentType === 7 /* Literal */)) { + emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); + context.braceNest = 0; + return readToken(scnr, context); + } + if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { + token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validListIdentifier = isListIdentifierStart(scnr, context))) { + token = getToken(context, 6 /* List */, readListIdentifier(scnr)); + skipSpaces(scnr); + return token; + } + if ((validLiteral = isLiteralStart(scnr, context))) { + token = getToken(context, 7 /* Literal */, readLiteral(scnr)); + skipSpaces(scnr); + return token; + } + if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { + // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... + token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); + emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); + skipSpaces(scnr); + return token; + } + break; + } + return token; + } + // TODO: We need refactoring of token parsing ... + function readTokenInLinked(scnr, context) { + const { currentType } = context; + let token = null; + const ch = scnr.currentChar(); + if ((currentType === 8 /* LinkedAlias */ || + currentType === 9 /* LinkedDot */ || + currentType === 12 /* LinkedModifier */ || + currentType === 10 /* LinkedDelimiter */) && + (ch === CHAR_LF || ch === CHAR_SP)) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + switch (ch) { + case "@" /* LinkedAlias */: + scnr.next(); + token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); + context.inLinked = true; + return token; + case "." /* LinkedDot */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); + case ":" /* LinkedDelimiter */: + skipSpaces(scnr); + scnr.next(); + return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isLinkedDotStart(scnr, context) || + isLinkedDelimiterStart(scnr, context)) { + skipSpaces(scnr); + return readTokenInLinked(scnr, context); + } + if (isLinkedModifierStart(scnr, context)) { + skipSpaces(scnr); + return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); + } + if (isLinkedReferStart(scnr, context)) { + skipSpaces(scnr); + if (ch === "{" /* BraceLeft */) { + // scan the placeholder + return readTokenInPlaceholder(scnr, context) || token; + } + else { + return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); + } + } + if (currentType === 8 /* LinkedAlias */) { + emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); + } + context.braceNest = 0; + context.inLinked = false; + return readToken(scnr, context); + } + } + // TODO: We need refactoring of token parsing ... + function readToken(scnr, context) { + let token = { type: 14 /* EOF */ }; + if (context.braceNest > 0) { + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + } + if (context.inLinked) { + return readTokenInLinked(scnr, context) || getEndToken(context); + } + const ch = scnr.currentChar(); + switch (ch) { + case "{" /* BraceLeft */: + return readTokenInPlaceholder(scnr, context) || getEndToken(context); + case "}" /* BraceRight */: + emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); + scnr.next(); + return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); + case "@" /* LinkedAlias */: + return readTokenInLinked(scnr, context) || getEndToken(context); + default: + if (isPluralStart(scnr)) { + token = getToken(context, 1 /* Pipe */, readPlural(scnr)); + // reset + context.braceNest = 0; + context.inLinked = false; + return token; + } + if (isTextStart(scnr)) { + return getToken(context, 0 /* Text */, readText(scnr)); + } + if (ch === "%" /* Modulo */) { + scnr.next(); + return getToken(context, 4 /* Modulo */, "%" /* Modulo */); + } + break; + } + return token; + } + function nextToken() { + const { currentType, offset, startLoc, endLoc } = _context; + _context.lastType = currentType; + _context.lastOffset = offset; + _context.lastStartLoc = startLoc; + _context.lastEndLoc = endLoc; + _context.offset = currentOffset(); + _context.startLoc = currentPosition(); + if (_scnr.currentChar() === EOF) { + return getToken(_context, 14 /* EOF */); + } + return readToken(_scnr, _context); + } + return { + nextToken, + currentOffset, + currentPosition, + context + }; + } + + const ERROR_DOMAIN = 'parser'; + // Backslash backslash, backslash quote, uHHHH, UHHHHHH. + const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; + function fromEscapeSequence(match, codePoint4, codePoint6) { + switch (match) { + case `\\\\`: + return `\\`; + case `\\\'`: + return `\'`; + default: { + const codePoint = parseInt(codePoint4 || codePoint6, 16); + if (codePoint <= 0xd7ff || codePoint >= 0xe000) { + return String.fromCodePoint(codePoint); + } + // invalid ... + // Replace them with U+FFFD REPLACEMENT CHARACTER. + return '�'; + } + } + } + function createParser(options = {}) { + const location = options.location !== false; + const { onError } = options; + function emitError(tokenzer, code, start, offset, ...args) { + const end = tokenzer.currentPosition(); + end.offset += offset; + end.column += offset; + if (onError) { + const loc = createLocation(start, end); + const err = createCompileError(code, loc, { + domain: ERROR_DOMAIN, + args + }); + onError(err); + } + } + function startNode(type, offset, loc) { + const node = { + type, + start: offset, + end: offset + }; + if (location) { + node.loc = { start: loc, end: loc }; + } + return node; + } + function endNode(node, offset, pos, type) { + node.end = offset; + if (type) { + node.type = type; + } + if (location && node.loc) { + node.loc.end = pos; + } + } + function parseText(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(3 /* Text */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseList(tokenizer, index) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(5 /* List */, offset, loc); + node.index = parseInt(index, 10); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseNamed(tokenizer, key) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(4 /* Named */, offset, loc); + node.key = key; + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLiteral(tokenizer, value) { + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc + const node = startNode(9 /* Literal */, offset, loc); + node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); + tokenizer.nextToken(); // skip brach right + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinkedModifier(tokenizer) { + const token = tokenizer.nextToken(); + const context = tokenizer.context(); + const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc + const node = startNode(8 /* LinkedModifier */, offset, loc); + if (token.type !== 12 /* LinkedModifier */) { + // empty modifier + emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0); + node.value = ''; + endNode(node, offset, loc); + return { + nextConsumeToken: token, + node + }; + } + // check token + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.value = token.value || ''; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node + }; + } + function parseLinkedKey(tokenizer, value) { + const context = tokenizer.context(); + const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); + node.value = value; + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseLinked(tokenizer) { + const context = tokenizer.context(); + const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); + let token = tokenizer.nextToken(); + if (token.type === 9 /* LinkedDot */) { + const parsed = parseLinkedModifier(tokenizer); + linkedNode.modifier = parsed.node; + token = parsed.nextConsumeToken || tokenizer.nextToken(); + } + // asset check token + if (token.type !== 10 /* LinkedDelimiter */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + token = tokenizer.nextToken(); + // skip brace left + if (token.type === 2 /* BraceLeft */) { + token = tokenizer.nextToken(); + } + switch (token.type) { + case 11 /* LinkedKey */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseNamed(tokenizer, token.value || ''); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseList(tokenizer, token.value || ''); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + linkedNode.key = parseLiteral(tokenizer, token.value || ''); + break; + default: + // empty key + emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0); + const nextContext = tokenizer.context(); + const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc); + emptyLinkedKeyNode.value = ''; + endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc); + linkedNode.key = emptyLinkedKeyNode; + endNode(linkedNode, nextContext.offset, nextContext.startLoc); + return { + nextConsumeToken: token, + node: linkedNode + }; + } + endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); + return { + node: linkedNode + }; + } + function parseMessage(tokenizer) { + const context = tokenizer.context(); + const startOffset = context.currentType === 1 /* Pipe */ + ? tokenizer.currentOffset() + : context.offset; + const startLoc = context.currentType === 1 /* Pipe */ + ? context.endLoc + : context.startLoc; + const node = startNode(2 /* Message */, startOffset, startLoc); + node.items = []; + let nextToken = null; + do { + const token = nextToken || tokenizer.nextToken(); + nextToken = null; + switch (token.type) { + case 0 /* Text */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseText(tokenizer, token.value || '')); + break; + case 6 /* List */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseList(tokenizer, token.value || '')); + break; + case 5 /* Named */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseNamed(tokenizer, token.value || '')); + break; + case 7 /* Literal */: + if (token.value == null) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token)); + } + node.items.push(parseLiteral(tokenizer, token.value || '')); + break; + case 8 /* LinkedAlias */: + const parsed = parseLinked(tokenizer); + node.items.push(parsed.node); + nextToken = parsed.nextConsumeToken || null; + break; + } + } while (context.currentType !== 14 /* EOF */ && + context.currentType !== 1 /* Pipe */); + // adjust message node loc + const endOffset = context.currentType === 1 /* Pipe */ + ? context.lastOffset + : tokenizer.currentOffset(); + const endLoc = context.currentType === 1 /* Pipe */ + ? context.lastEndLoc + : tokenizer.currentPosition(); + endNode(node, endOffset, endLoc); + return node; + } + function parsePlural(tokenizer, offset, loc, msgNode) { + const context = tokenizer.context(); + let hasEmptyMessage = msgNode.items.length === 0; + const node = startNode(1 /* Plural */, offset, loc); + node.cases = []; + node.cases.push(msgNode); + do { + const msg = parseMessage(tokenizer); + if (!hasEmptyMessage) { + hasEmptyMessage = msg.items.length === 0; + } + node.cases.push(msg); + } while (context.currentType !== 14 /* EOF */); + if (hasEmptyMessage) { + emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + function parseResource(tokenizer) { + const context = tokenizer.context(); + const { offset, startLoc } = context; + const msgNode = parseMessage(tokenizer); + if (context.currentType === 14 /* EOF */) { + return msgNode; + } + else { + return parsePlural(tokenizer, offset, startLoc, msgNode); + } + } + function parse(source) { + const tokenizer = createTokenizer(source, assign({}, options)); + const context = tokenizer.context(); + const node = startNode(0 /* Resource */, context.offset, context.startLoc); + if (location && node.loc) { + node.loc.source = source; + } + node.body = parseResource(tokenizer); + // assert whether achieved to EOF + if (context.currentType !== 14 /* EOF */) { + emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || ''); + } + endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); + return node; + } + return { parse }; + } + function getTokenCaption(token) { + if (token.type === 14 /* EOF */) { + return 'EOF'; + } + const name = (token.value || '').replace(/\r?\n/gu, '\\n'); + return name.length > 10 ? name.slice(0, 9) + '…' : name; + } + + function createTransformer(ast, options = {} // eslint-disable-line + ) { + const _context = { + ast, + helpers: new Set() + }; + const context = () => _context; + const helper = (name) => { + _context.helpers.add(name); + return name; + }; + return { context, helper }; + } + function traverseNodes(nodes, transformer) { + for (let i = 0; i < nodes.length; i++) { + traverseNode(nodes[i], transformer); + } + } + function traverseNode(node, transformer) { + // TODO: if we need pre-hook of transform, should be implemented to here + switch (node.type) { + case 1 /* Plural */: + traverseNodes(node.cases, transformer); + transformer.helper("plural" /* PLURAL */); + break; + case 2 /* Message */: + traverseNodes(node.items, transformer); + break; + case 6 /* Linked */: + const linked = node; + traverseNode(linked.key, transformer); + transformer.helper("linked" /* LINKED */); + break; + case 5 /* List */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("list" /* LIST */); + break; + case 4 /* Named */: + transformer.helper("interpolate" /* INTERPOLATE */); + transformer.helper("named" /* NAMED */); + break; + } + // TODO: if we need post-hook of transform, should be implemented to here + } + // transform AST + function transform(ast, options = {} // eslint-disable-line + ) { + const transformer = createTransformer(ast); + transformer.helper("normalize" /* NORMALIZE */); + // traverse + ast.body && traverseNode(ast.body, transformer); + // set meta information + const context = transformer.context(); + ast.helpers = Array.from(context.helpers); + } + + function createCodeGenerator(ast, options) { + const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options; + const _context = { + source: ast.loc.source, + filename, + code: '', + column: 1, + line: 1, + offset: 0, + map: undefined, + breakLineCode, + needIndent: _needIndent, + indentLevel: 0 + }; + const context = () => _context; + function push(code, node) { + _context.code += code; + } + function _newline(n, withBreakLine = true) { + const _breakLineCode = withBreakLine ? breakLineCode : ''; + push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode); + } + function indent(withNewLine = true) { + const level = ++_context.indentLevel; + withNewLine && _newline(level); + } + function deindent(withNewLine = true) { + const level = --_context.indentLevel; + withNewLine && _newline(level); + } + function newline() { + _newline(_context.indentLevel); + } + const helper = (key) => `_${key}`; + const needIndent = () => _context.needIndent; + return { + context, + push, + indent, + deindent, + newline, + helper, + needIndent + }; + } + function generateLinkedNode(generator, node) { + const { helper } = generator; + generator.push(`${helper("linked" /* LINKED */)}(`); + generateNode(generator, node.key); + if (node.modifier) { + generator.push(`, `); + generateNode(generator, node.modifier); + } + generator.push(`)`); + } + function generateMessageNode(generator, node) { + const { helper, needIndent } = generator; + generator.push(`${helper("normalize" /* NORMALIZE */)}([`); + generator.indent(needIndent()); + const length = node.items.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.items[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push('])'); + } + function generatePluralNode(generator, node) { + const { helper, needIndent } = generator; + if (node.cases.length > 1) { + generator.push(`${helper("plural" /* PLURAL */)}([`); + generator.indent(needIndent()); + const length = node.cases.length; + for (let i = 0; i < length; i++) { + generateNode(generator, node.cases[i]); + if (i === length - 1) { + break; + } + generator.push(', '); + } + generator.deindent(needIndent()); + generator.push(`])`); + } + } + function generateResource(generator, node) { + if (node.body) { + generateNode(generator, node.body); + } + else { + generator.push('null'); + } + } + function generateNode(generator, node) { + const { helper } = generator; + switch (node.type) { + case 0 /* Resource */: + generateResource(generator, node); + break; + case 1 /* Plural */: + generatePluralNode(generator, node); + break; + case 2 /* Message */: + generateMessageNode(generator, node); + break; + case 6 /* Linked */: + generateLinkedNode(generator, node); + break; + case 8 /* LinkedModifier */: + generator.push(JSON.stringify(node.value), node); + break; + case 7 /* LinkedKey */: + generator.push(JSON.stringify(node.value), node); + break; + case 5 /* List */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); + break; + case 4 /* Named */: + generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); + break; + case 9 /* Literal */: + generator.push(JSON.stringify(node.value), node); + break; + case 3 /* Text */: + generator.push(JSON.stringify(node.value), node); + break; + default: + { + throw new Error(`unhandled codegen node type: ${node.type}`); + } + } + } + // generate code from AST + const generate = (ast, options = {} // eslint-disable-line + ) => { + const mode = isString(options.mode) ? options.mode : 'normal'; + const filename = isString(options.filename) + ? options.filename + : 'message.intl'; + const sourceMap = !!options.sourceMap; + // prettier-ignore + const breakLineCode = options.breakLineCode != null + ? options.breakLineCode + : mode === 'arrow' + ? ';' + : '\n'; + const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow'; + const helpers = ast.helpers || []; + const generator = createCodeGenerator(ast, { + mode, + filename, + sourceMap, + breakLineCode, + needIndent + }); + generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); + generator.indent(needIndent); + if (helpers.length > 0) { + generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); + generator.newline(); + } + generator.push(`return `); + generateNode(generator, ast); + generator.deindent(needIndent); + generator.push(`}`); + const { code, map } = generator.context(); + return { + ast, + code, + map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any + }; + }; + + function baseCompile(source, options = {}) { + const assignedOptions = assign({}, options); + // parse source codes + const parser = createParser(assignedOptions); + const ast = parser.parse(source); + // transform ASTs + transform(ast, assignedOptions); + // generate javascript codes + return generate(ast, assignedOptions); + } + + const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' + }; + + let devtools = null; + function setDevToolsHook(hook) { + devtools = hook; + } + 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$1 = { + [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$1(code, ...args) { + return format(warnMessages$1[code], ...args); + } + + /** + * Intlify core-base version + * @internal + */ + const VERSION$1 = '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$1; + 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 + { + 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 isString(ret) ? ret : key; + } + else { + if (isTranslateMissingWarn(missingWarn, key)) { + onWarn(getWarnMessage$1(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 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 || 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, { messages: errorMessages$1 } ); + } + /** @internal */ + const errorMessages$1 = { + [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 (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 !! + { + // 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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!Availabilities.dateTimeFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (!Availabilities.numberFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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); + } + } + + /** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ + const VERSION = '9.1.7'; + /** + * This is only called development env + * istanbul-ignore-next + */ + function initDev() { + { + { + console.info(`You are running a development build of vue-i18n.\n` + + `Make sure to use the production build (*.prod.js) when deploying for production.`); + } + } + } + + const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` + }; + function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); + } + + function createI18nError(code, ...args) { + return createCompileError(code, null, { messages: errorMessages, args } ); + } + const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` + }; + + const DEVTOOLS_META = '__INTLIFY_META__'; + const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); + const DatetimePartsSymbol = makeSymbol('__datetimeParts'); + const NumberPartsSymbol = makeSymbol('__numberParts'); + const EnableEmitter = makeSymbol('__enableEmitter'); + const DisableEmitter = makeSymbol('__disableEmitter'); + const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); + let composerID = 0; + function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, vue.getCurrentInstance() || undefined, type); + }); + } + function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; + } + const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } + } + // for Intlify DevTools + const getMetaInfo = /* #__PURE__*/ () => { + const instance = vue.getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; + }; + /** + * Create composer interface factory + * + * @internal + */ + function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = vue.ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = vue.ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = vue.computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = vue.computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = vue.computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = vue.computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = vue.computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if (__root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + vue.watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + vue.watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; + } + + /** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ + function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if (options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if (options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; + } + /** + * create VueI18n interface factory + * + * @internal + */ + function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; + } + + const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } + }; + + /** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ + const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; + } + }; + function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } + } + + function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; + } + + const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' + ]; + /** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ + const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } + }; + + const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' + ]; + /** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ + const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } + }; + + function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } + } + function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if (modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; + } + function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } + } + function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; + } + + function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if (globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + function getDevtoolsGlobalHook() { + return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; + } + function getTarget() { + // @ts-ignore + return typeof navigator !== 'undefined' + ? window + : typeof global$1 !== 'undefined' + ? global$1 + : {}; + } + + const HOOK_SETUP = 'devtools-plugin:setup'; + + 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 + }); + } + } + + 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 + }; + + const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; + let devtoolsApi; + async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); + } + function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any + treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } + } + function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; + } + const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' + }; + function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); + } + function escapeChar(a) { + return ESC[a] || a; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; + } + function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } + } + function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } + } + function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } + } + function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; + } + function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } + } + function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } + } + + // supports compatibility for legacy vue-i18n APIs + function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; + } + function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; + } + + /** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ + function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = isBoolean(options.legacy) + ? options.legacy + : true; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol('vue-i18n' ); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __legacyMode + ? 'legacy' + : 'composition' + ; + }, + // install plugin + async install(app, ...options) { + { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; + } + /** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ + function useI18n(options = {}) { + const instance = vue.getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; + } + function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; + } + function setupLifeCycle(i18n, target, composer) { + let emitter = null; + vue.onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + vue.onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); + } + const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' + ]; + const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; + function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = vue.isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); + } + + // register message compiler at vue-i18n + registerMessageCompiler(compileToFunction); + // NOTE: experimental !! + { + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); + } + { + initDev(); + } + + exports.DatetimeFormat = DatetimeFormat; + exports.NumberFormat = NumberFormat; + exports.Translation = Translation; + exports.VERSION = VERSION; + exports.createI18n = createI18n; + exports.useI18n = useI18n; + exports.vTDirective = vTDirective; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +}({}, Vue)); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..06dda38884ea0f120dff369b1edc9c63ca151978 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.global.prod.js @@ -0,0 +1,6 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var VueI18n=function(e,t){"use strict";const n="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,r=e=>n?Symbol(e):e,a=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),o=e=>"number"==typeof e&&isFinite(e),s=e=>"[object RegExp]"===_(e),l=e=>v(e)&&0===Object.keys(e).length;function c(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const u=Object.assign;function i(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const f=Object.prototype.hasOwnProperty;function m(e,t){return f.call(e,t)}const p=Array.isArray,g=e=>"function"==typeof e,d=e=>"string"==typeof e,b=e=>"boolean"==typeof e,h=e=>null!==e&&"object"==typeof e,k=Object.prototype.toString,_=e=>k.call(e),v=e=>"[object Object]"===_(e),y=[];y[0]={w:[0],i:[3,0],"[":[4],o:[7]},y[1]={w:[1],".":[2],"[":[4],o:[7]},y[2]={w:[2],i:[3,0],0:[3,0]},y[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},y[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},y[5]={"'":[4,0],o:8,l:[5,0]},y[6]={'"':[4,0],o:8,l:[6,0]};const F=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function L(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function w(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(F.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}const T=new Map;function x(e,t){if(!h(e))return null;let n=T.get(t);if(n||(n=function(e){const t=[];let n,r,a,o,s,l,c,u=-1,i=0,f=0;const m=[];function p(){const t=e[u+1];if(5===i&&"'"===t||6===i&&'"'===t)return u++,a="\\"+t,m[0](),!0}for(m[0]=()=>{void 0===r?r=a:r+=a},m[1]=()=>{void 0!==r&&(t.push(r),r=void 0)},m[2]=()=>{m[0](),f++},m[3]=()=>{if(f>0)f--,i=4,m[0]();else{if(f=0,void 0===r)return!1;if(r=w(r),!1===r)return!1;m[1]()}};null!==i;)if(u++,n=e[u],"\\"!==n||!p()){if(o=L(n),c=y[i],s=c[o]||c.l||8,8===s)return;if(i=s[0],void 0!==s[1]&&(l=m[s[1]],l&&(a=n,!1===l())))return;if(7===i)return t}}(t),n&&T.set(t,n)),!n)return null;const r=n.length;let a=e,o=0;for(;oe,M=e=>"",$=e=>0===e.length?"":e.join(""),O=e=>null==e?"":p(e)||v(e)&&e.toString===k?JSON.stringify(e,null,2):String(e);function I(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function W(e={}){const t=e.locale,n=function(e){const t=o(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(o(e.named.count)||o(e.named.n))?o(e.named.count)?e.named.count:o(e.named.n)?e.named.n:t:t}(e),r=h(e.pluralRules)&&d(t)&&g(e.pluralRules[t])?e.pluralRules[t]:I,a=h(e.pluralRules)&&d(t)&&g(e.pluralRules[t])?I:void 0,s=e.list||[],l=e.named||{};o(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(n,l);function c(t){const n=g(e.messages)?e.messages(t):!!h(e.messages)&&e.messages[t];return n||(e.parent?e.parent.message(t):M)}const u=v(e.processor)&&g(e.processor.normalize)?e.processor.normalize:$,i=v(e.processor)&&g(e.processor.interpolate)?e.processor.interpolate:O,f={list:e=>s[e],named:e=>l[e],plural:e=>e[r(n,e.length,a)],linked:(t,n)=>{const r=c(t)(f);return d(n)?(a=n,e.modifiers?e.modifiers[a]:C)(r):r;var a},message:c,type:v(e.processor)&&d(e.processor.type)?e.processor.type:"text",interpolate:i,normalize:u};return f}function N(e){throw e}function S(e,t,n){const r={start:e,end:t};return null!=n&&(r.source=n),r}const E=" ",j="\n",H=String.fromCharCode(8232),R=String.fromCharCode(8233);function D(e){const t=e;let n=0,r=1,a=1,o=0;const s=e=>"\r"===t[e]&&t[e+1]===j,l=e=>t[e]===R,c=e=>t[e]===H,u=e=>s(e)||(e=>t[e]===j)(e)||l(e)||c(e),i=e=>s(e)||l(e)||c(e)?j:t[e];function f(){return o=0,u(n)&&(r++,a=0),s(n)&&n++,n++,a++,t[n]}return{index:()=>n,line:()=>r,column:()=>a,peekOffset:()=>o,charAt:i,currentChar:()=>i(n),currentPeek:()=>i(n+o),next:f,peek:function(){return s(n+o)&&o++,o++,t[n+o]},reset:function(){n=0,r=1,a=1,o=0},resetPeek:function(e=0){o=e},skipToPeek:function(){const e=n+o;for(;e!==n;)f();o=0}}}const A=void 0;function U(e,t={}){const n=!1!==t.location,r=D(e),a=()=>r.index(),o=()=>{return e=r.line(),t=r.column(),n=r.index(),{line:e,column:t,offset:n};var e,t,n},s=o(),l=a(),c={currentType:14,offset:l,startLoc:s,endLoc:s,lastType:14,lastOffset:l,lastStartLoc:s,lastEndLoc:s,braceNest:0,inLinked:!1,text:""},u=()=>c,{onError:i}=t;function f(e,t,r){e.endLoc=o(),e.currentType=t;const a={type:t};return n&&(a.loc=S(e.startLoc,e.endLoc)),null!=r&&(a.value=r),a}const m=e=>f(e,14);function p(e,t){return e.currentChar()===t?(e.next(),t):(o(),"")}function g(e){let t="";for(;e.currentPeek()===E||e.currentPeek()===j;)t+=e.currentPeek(),e.peek();return t}function d(e){const t=g(e);return e.skipToPeek(),t}function b(e){if(e===A)return!1;const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||95===t}function h(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r=function(e){if(e===A)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}("-"===e.currentPeek()?e.peek():e.currentPeek());return e.resetPeek(),r}function k(e){g(e);const t="|"===e.currentPeek();return e.resetPeek(),t}function _(e,t=!0){const n=(t=!1,r="",a=!1)=>{const o=e.currentPeek();return"{"===o?"%"!==r&&t:"@"!==o&&o?"%"===o?(e.peek(),n(t,"%",!0)):"|"===o?!("%"!==r&&!a)||!(r===E||r===j):o===E?(e.peek(),n(!0,E,a)):o!==j||(e.peek(),n(!0,j,a)):"%"===r||t},r=n();return t&&e.resetPeek(),r}function v(e,t){const n=e.currentChar();return n===A?A:t(n)?(e.next(),n):null}function y(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=97&&t<=122||t>=65&&t<=90||t>=48&&t<=57||95===t||36===t}))}function F(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57}))}function L(e){return v(e,(e=>{const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}))}function w(e){let t="",n="";for(;t=F(e);)n+=t;return n}function T(e){const t=e.currentChar();switch(t){case"\\":case"'":return e.next(),`\\${t}`;case"u":return x(e,t,4);case"U":return x(e,t,6);default:return o(),""}}function x(e,t,n){p(e,t);let r="";for(let t=0;t=1&&o(),e.next(),n=f(t,2,"{"),d(e),t.braceNest++,n;case"}":return t.braceNest>0&&2===t.currentType&&o(),e.next(),n=f(t,3,"}"),t.braceNest--,t.braceNest>0&&d(e),t.inLinked&&0===t.braceNest&&(t.inLinked=!1),n;case"@":return t.braceNest>0&&o(),n=M(e,t)||m(t),t.braceNest=0,n;default:let r=!0,a=!0,s=!0;if(k(e))return t.braceNest>0&&o(),n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(t.braceNest>0&&(5===t.currentType||6===t.currentType||7===t.currentType))return o(),t.braceNest=0,$(e,t);if(r=function(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r=b(e.currentPeek());return e.resetPeek(),r}(e,t))return n=f(t,5,function(e){d(e);let t="",n="";for(;t=y(e);)n+=t;return e.currentChar()===A&&o(),n}(e)),d(e),n;if(a=h(e,t))return n=f(t,6,function(e){d(e);let t="";return"-"===e.currentChar()?(e.next(),t+=`-${w(e)}`):t+=w(e),e.currentChar()===A&&o(),t}(e)),d(e),n;if(s=function(e,t){const{currentType:n}=t;if(2!==n)return!1;g(e);const r="'"===e.currentPeek();return e.resetPeek(),r}(e,t))return n=f(t,7,function(e){d(e),p(e,"'");let t="",n="";const r=e=>"'"!==e&&e!==j;for(;t=v(e,r);)n+="\\"===t?T(e):t;const a=e.currentChar();return a===j||a===A?(o(),a===j&&(e.next(),p(e,"'")),n):(p(e,"'"),n)}(e)),d(e),n;if(!r&&!a&&!s)return n=f(t,13,function(e){d(e);let t="",n="";const r=e=>"{"!==e&&"}"!==e&&e!==E&&e!==j;for(;t=v(e,r);)n+=t;return n}(e)),o(),d(e),n}return n}function M(e,t){const{currentType:n}=t;let r=null;const a=e.currentChar();switch(8!==n&&9!==n&&12!==n&&10!==n||a!==j&&a!==E||o(),a){case"@":return e.next(),r=f(t,8,"@"),t.inLinked=!0,r;case".":return d(e),e.next(),f(t,9,".");case":":return d(e),e.next(),f(t,10,":");default:return k(e)?(r=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,r):function(e,t){const{currentType:n}=t;if(8!==n)return!1;g(e);const r="."===e.currentPeek();return e.resetPeek(),r}(e,t)||function(e,t){const{currentType:n}=t;if(8!==n&&12!==n)return!1;g(e);const r=":"===e.currentPeek();return e.resetPeek(),r}(e,t)?(d(e),M(e,t)):function(e,t){const{currentType:n}=t;if(9!==n)return!1;g(e);const r=b(e.currentPeek());return e.resetPeek(),r}(e,t)?(d(e),f(t,12,function(e){let t="",n="";for(;t=y(e);)n+=t;return n}(e))):function(e,t){const{currentType:n}=t;if(10!==n)return!1;const r=()=>{const t=e.currentPeek();return"{"===t?b(e.peek()):!("@"===t||"%"===t||"|"===t||":"===t||"."===t||t===E||!t)&&(t===j?(e.peek(),r()):b(t))},a=r();return e.resetPeek(),a}(e,t)?(d(e),"{"===a?C(e,t)||r:f(t,11,function(e){const t=(n=!1,r)=>{const a=e.currentChar();return"{"!==a&&"%"!==a&&"@"!==a&&"|"!==a&&a?a===E?r:a===j?(r+=a,e.next(),t(n,r)):(r+=a,e.next(),t(!0,r)):r};return t(!1,"")}(e))):(8===n&&o(),t.braceNest=0,t.inLinked=!1,$(e,t))}}function $(e,t){let n={type:14};if(t.braceNest>0)return C(e,t)||m(t);if(t.inLinked)return M(e,t)||m(t);const r=e.currentChar();switch(r){case"{":return C(e,t)||m(t);case"}":return o(),e.next(),f(t,3,"}");case"@":return M(e,t)||m(t);default:if(k(e))return n=f(t,1,P(e)),t.braceNest=0,t.inLinked=!1,n;if(_(e))return f(t,0,function(e){const t=n=>{const r=e.currentChar();return"{"!==r&&"}"!==r&&"@"!==r&&r?"%"===r?_(e)?(n+=r,e.next(),t(n)):n:"|"===r?n:r===E||r===j?_(e)?(n+=r,e.next(),t(n)):k(e)?n:(n+=r,e.next(),t(n)):(n+=r,e.next(),t(n)):n};return t("")}(e));if("%"===r)return e.next(),f(t,4,"%")}return n}return{nextToken:function(){const{currentType:e,offset:t,startLoc:n,endLoc:s}=c;return c.lastType=e,c.lastOffset=t,c.lastStartLoc=n,c.lastEndLoc=s,c.offset=a(),c.startLoc=o(),r.currentChar()===A?f(c,14):$(r,c)},currentOffset:a,currentPosition:o,context:u}}const z=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;function J(e,t,n){switch(e){case"\\\\":return"\\";case"\\'":return"'";default:{const e=parseInt(t||n,16);return e<=55295||e>=57344?String.fromCodePoint(e):"�"}}}function V(e={}){const t=!1!==e.location,{onError:n}=e;function r(e,n,r){const a={type:e,start:n,end:n};return t&&(a.loc={start:r,end:r}),a}function a(e,n,r,a){e.end=n,a&&(e.type=a),t&&e.loc&&(e.loc.end=r)}function o(e,t){const n=e.context(),o=r(3,n.offset,n.startLoc);return o.value=t,a(o,e.currentOffset(),e.currentPosition()),o}function s(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(5,o,s);return l.index=parseInt(t,10),e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function l(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(4,o,s);return l.key=t,e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function c(e,t){const n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(9,o,s);return l.value=t.replace(z,J),e.nextToken(),a(l,e.currentOffset(),e.currentPosition()),l}function i(e){const t=e.context(),n=r(6,t.offset,t.startLoc);let o=e.nextToken();if(9===o.type){const t=function(e){const t=e.nextToken(),n=e.context(),{lastOffset:o,lastStartLoc:s}=n,l=r(8,o,s);return 12!==t.type?(l.value="",a(l,o,s),{nextConsumeToken:t,node:l}):(null==t.value&&q(t),l.value=t.value||"",a(l,e.currentOffset(),e.currentPosition()),{node:l})}(e);n.modifier=t.node,o=t.nextConsumeToken||e.nextToken()}switch(10!==o.type&&q(o),o=e.nextToken(),2===o.type&&(o=e.nextToken()),o.type){case 11:null==o.value&&q(o),n.key=function(e,t){const n=e.context(),o=r(7,n.offset,n.startLoc);return o.value=t,a(o,e.currentOffset(),e.currentPosition()),o}(e,o.value||"");break;case 5:null==o.value&&q(o),n.key=l(e,o.value||"");break;case 6:null==o.value&&q(o),n.key=s(e,o.value||"");break;case 7:null==o.value&&q(o),n.key=c(e,o.value||"");break;default:const t=e.context(),u=r(7,t.offset,t.startLoc);return u.value="",a(u,t.offset,t.startLoc),n.key=u,a(n,t.offset,t.startLoc),{nextConsumeToken:o,node:n}}return a(n,e.currentOffset(),e.currentPosition()),{node:n}}function f(e){const t=e.context(),n=r(2,1===t.currentType?e.currentOffset():t.offset,1===t.currentType?t.endLoc:t.startLoc);n.items=[];let u=null;do{const t=u||e.nextToken();switch(u=null,t.type){case 0:null==t.value&&q(t),n.items.push(o(e,t.value||""));break;case 6:null==t.value&&q(t),n.items.push(s(e,t.value||""));break;case 5:null==t.value&&q(t),n.items.push(l(e,t.value||""));break;case 7:null==t.value&&q(t),n.items.push(c(e,t.value||""));break;case 8:const r=i(e);n.items.push(r.node),u=r.nextConsumeToken||null}}while(14!==t.currentType&&1!==t.currentType);return a(n,1===t.currentType?t.lastOffset:e.currentOffset(),1===t.currentType?t.lastEndLoc:e.currentPosition()),n}function m(e){const t=e.context(),{offset:n,startLoc:o}=t,s=f(e);return 14===t.currentType?s:function(e,t,n,o){const s=e.context();let l=0===o.items.length;const c=r(1,t,n);c.cases=[],c.cases.push(o);do{const t=f(e);l||(l=0===t.items.length),c.cases.push(t)}while(14!==s.currentType);return a(c,e.currentOffset(),e.currentPosition()),c}(e,n,o,s)}return{parse:function(n){const o=U(n,u({},e)),s=o.context(),l=r(0,s.offset,s.startLoc);return t&&l.loc&&(l.loc.source=n),l.body=m(o),a(l,o.currentOffset(),o.currentPosition()),l}}}function q(e){if(14===e.type)return"EOF";const t=(e.value||"").replace(/\r?\n/gu,"\\n");return t.length>10?t.slice(0,9)+"…":t}function B(e,t){for(let n=0;nn,helper:e=>(n.helpers.add(e),e)}}(e);n.helper("normalize"),e.body&&G(e.body,n);const r=n.context();e.helpers=Array.from(r.helpers)}function K(e,t){const{helper:n}=e;switch(t.type){case 0:!function(e,t){t.body?K(e,t.body):e.push("null")}(e,t);break;case 1:!function(e,t){const{helper:n,needIndent:r}=e;if(t.cases.length>1){e.push(`${n("plural")}([`),e.indent(r());const a=t.cases.length;for(let n=0;n{const n=d(t.mode)?t.mode:"normal",r=d(t.filename)?t.filename:"message.intl",a=t.needIndent?t.needIndent:"arrow"!==n,o=e.helpers||[],s=function(e,t){const{filename:n,breakLineCode:r,needIndent:a}=t,o={source:e.loc.source,filename:n,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:r,needIndent:a,indentLevel:0};function s(e,t){o.code+=e}function l(e,t=!0){const n=t?r:"";s(a?n+" ".repeat(e):n)}return{context:()=>o,push:s,indent:function(e=!0){const t=++o.indentLevel;e&&l(t)},deindent:function(e=!0){const t=--o.indentLevel;e&&l(t)},newline:function(){l(o.indentLevel)},helper:e=>`_${e}`,needIndent:()=>o.needIndent}}(e,{mode:n,filename:r,sourceMap:!!t.sourceMap,breakLineCode:null!=t.breakLineCode?t.breakLineCode:"arrow"===n?";":"\n",needIndent:a});s.push("normal"===n?"function __msg__ (ctx) {":"(ctx) => {"),s.indent(a),o.length>0&&(s.push(`const { ${o.map((e=>`${e}: _${e}`)).join(", ")} } = ctx`),s.newline()),s.push("return "),K(s,e),s.deindent(a),s.push("}");const{code:l,map:c}=s.context();return{ast:e,code:l,map:c?c.toJSON():void 0}})(r,n)}let Q;let X=0;function ee(e={}){const t=d(e.version)?e.version:"9.1.7",n=d(e.locale)?e.locale:"en-US",r=p(e.fallbackLocale)||v(e.fallbackLocale)||d(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:n,a=v(e.messages)?e.messages:{[n]:{}},o=v(e.datetimeFormats)?e.datetimeFormats:{[n]:{}},l=v(e.numberFormats)?e.numberFormats:{[n]:{}},i=u({},e.modifiers||{},{upper:e=>d(e)?e.toUpperCase():e,lower:e=>d(e)?e.toLowerCase():e,capitalize:e=>d(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),f=e.pluralRules||{},m=g(e.missing)?e.missing:null,k=!b(e.missingWarn)&&!s(e.missingWarn)||e.missingWarn,_=!b(e.fallbackWarn)&&!s(e.fallbackWarn)||e.fallbackWarn,y=!!e.fallbackFormat,F=!!e.unresolving,L=g(e.postTranslation)?e.postTranslation:null,w=v(e.processor)?e.processor:null,T=!b(e.warnHtmlMessage)||e.warnHtmlMessage,x=!!e.escapeParameter,P=g(e.messageCompiler)?e.messageCompiler:Q,C=g(e.onWarn)?e.onWarn:c,M=e,$=h(M.__datetimeFormatters)?M.__datetimeFormatters:new Map,O=h(M.__numberFormatters)?M.__numberFormatters:new Map,I=h(M.__meta)?M.__meta:{};X++;return{version:t,cid:X,locale:n,fallbackLocale:r,messages:a,datetimeFormats:o,numberFormats:l,modifiers:i,pluralRules:f,missing:m,missingWarn:k,fallbackWarn:_,fallbackFormat:y,unresolving:F,postTranslation:L,processor:w,warnHtmlMessage:T,escapeParameter:x,messageCompiler:P,onWarn:C,__datetimeFormatters:$,__numberFormatters:O,__meta:I}}function te(e,t,n,r,a){const{missing:o}=e;if(null!==o){const r=o(e,n,t,a);return d(r)?r:t}return t}function ne(e,t,n){const r=e;r.__localeChainCache||(r.__localeChainCache=new Map);let a=r.__localeChainCache.get(n);if(!a){a=[];let e=[n];for(;p(e);)e=re(a,e,t);const o=p(t)?t:v(t)?t.default?t.default:null:t;e=d(o)?[o]:o,p(e)&&re(a,e,!1),r.__localeChainCache.set(n,a)}return a}function re(e,t,n){let r=!0;for(let a=0;ae;let ce=Object.create(null);const ue=()=>"",ie=e=>g(e);function fe(e,...t){const{fallbackFormat:n,postTranslation:r,unresolving:a,fallbackLocale:s,messages:l}=e,[c,u]=pe(...t),f=(b(u.missingWarn),b(u.fallbackWarn),b(u.escapeParameter)?u.escapeParameter:e.escapeParameter),m=!!u.resolvedMessage,k=d(u.default)||b(u.default)?b(u.default)?c:u.default:n?c:"",_=n||""!==k,v=d(u.locale)?u.locale:e.locale;f&&function(e){p(e.list)?e.list=e.list.map((e=>d(e)?i(e):e)):h(e.named)&&Object.keys(e.named).forEach((t=>{d(e.named[t])&&(e.named[t]=i(e.named[t]))}))}(u);let[y,F,L]=m?[c,v,l[v]||{}]:function(e,t,n,r,a,o){const{messages:s}=e,l=ne(e,r,n);let c,u={},i=null;const f="translate";for(let n=0;n{T=!0}));if(T)return y;const C=function(e,t,n){return t(n)}(0,P,W(function(e,t,n,r){const{modifiers:a,pluralRules:s}=e,l={locale:t,modifiers:a,pluralRules:s,messages:r=>{const a=x(n,r);if(d(a)){let n=!1;const o=me(e,r,t,a,r,(()=>{n=!0}));return n?ue:o}return ie(a)?a:ue}};e.processor&&(l.processor=e.processor);r.list&&(l.list=r.list);r.named&&(l.named=r.named);o(r.plural)&&(l.pluralIndex=r.plural);return l}(e,F,L,u)));return r?r(C):C}function me(e,t,n,r,o,s){const{messageCompiler:l,warnHtmlMessage:c}=e;if(ie(r)){const e=r;return e.locale=e.locale||n,e.key=e.key||t,e}const u=l(r,function(e,t,n,r,o,s){return{warnHtmlMessage:o,onError:e=>{throw s&&s(e),e},onCacheKey:e=>((e,t,n)=>a({l:e,k:t,s:n}))(t,n,e)}}(0,n,o,0,c,s));return u.locale=n,u.key=t,u.source=r,u}function pe(...e){const[t,n,r]=e,a={};if(!d(t)&&!o(t)&&!ie(t))throw Error(14);const s=o(t)?String(t):(ie(t),t);return o(n)?a.plural=n:d(n)?a.default=n:v(n)&&!l(n)?a.named=n:p(n)&&(a.list=n),o(r)?a.plural=r:d(r)?a.default=r:v(r)&&u(a,r),[s,a]}function ge(e,...t){const{datetimeFormats:n,unresolving:r,fallbackLocale:a}=e,{__datetimeFormatters:o}=e,[s,c,i,f]=de(...t);b(i.missingWarn);b(i.fallbackWarn);const m=!!i.part,p=d(i.locale)?i.locale:e.locale,g=ne(e,a,p);if(!d(s)||""===s)return new Intl.DateTimeFormat(p).format(c);let h,k={},_=null;for(let t=0;te(r,a,t.getCurrentInstance()||void 0,o)}function Pe(e,t){const{messages:n,__i18n:r}=t,a=v(n)?n:p(r)?{}:{[e]:{}};if(p(r)&&r.forEach((({locale:e,resource:t})=>{e?(a[e]=a[e]||{},Me(t,a[e])):Me(t,a)})),t.flatJson)for(const e in a)m(a,e)&&P(a[e]);return a}const Ce=e=>!h(e)||p(e);function Me(e,t){if(Ce(e)||Ce(t))throw Error(20);for(const n in e)m(e,n)&&(Ce(e[n])||Ce(t[n])?t[n]=e[n]:Me(e[n],t[n]))}function $e(e={}){const{__root:n}=e,r=void 0===n;let a=!b(e.inheritLocale)||e.inheritLocale;const l=t.ref(n&&a?n.locale.value:d(e.locale)?e.locale:"en-US"),c=t.ref(n&&a?n.fallbackLocale.value:d(e.fallbackLocale)||p(e.fallbackLocale)||v(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:l.value),i=t.ref(Pe(l.value,e)),f=t.ref(v(e.datetimeFormats)?e.datetimeFormats:{[l.value]:{}}),m=t.ref(v(e.numberFormats)?e.numberFormats:{[l.value]:{}});let k=n?n.missingWarn:!b(e.missingWarn)&&!s(e.missingWarn)||e.missingWarn,_=n?n.fallbackWarn:!b(e.fallbackWarn)&&!s(e.fallbackWarn)||e.fallbackWarn,y=n?n.fallbackRoot:!b(e.fallbackRoot)||e.fallbackRoot,F=!!e.fallbackFormat,L=g(e.missing)?e.missing:null,w=g(e.missing)?xe(e.missing):null,T=g(e.postTranslation)?e.postTranslation:null,P=!b(e.warnHtmlMessage)||e.warnHtmlMessage,C=!!e.escapeParameter;const M=n?n.modifiers:v(e.modifiers)?e.modifiers:{};let $,O=e.pluralRules||n&&n.pluralRules;$=ee({version:ve,locale:l.value,fallbackLocale:c.value,messages:i.value,datetimeFormats:f.value,numberFormats:m.value,modifiers:M,pluralRules:O,missing:null===w?void 0:w,missingWarn:k,fallbackWarn:_,fallbackFormat:F,unresolving:!0,postTranslation:null===T?void 0:T,warnHtmlMessage:P,escapeParameter:C,__datetimeFormatters:v($)?$.__datetimeFormatters:void 0,__numberFormatters:v($)?$.__numberFormatters:void 0,__v_emitter:v($)?$.__v_emitter:void 0,__meta:{framework:"vue"}}),se($,l.value,c.value);const I=t.computed({get:()=>l.value,set:e=>{l.value=e,$.locale=l.value}}),W=t.computed({get:()=>c.value,set:e=>{c.value=e,$.fallbackLocale=c.value,se($,l.value,e)}}),N=t.computed((()=>i.value)),S=t.computed((()=>f.value)),E=t.computed((()=>m.value));function j(e,t,r,a,s,l){let c;if(c=e($),o(c)&&-1===c){const[e,r]=t();return n&&y?a(n):s(e)}if(l(c))return c;throw Error(14)}function H(...e){return j((t=>fe(t,...e)),(()=>pe(...e)),0,(t=>t.t(...e)),(e=>e),(e=>d(e)))}const R={normalize:function(e){return e.map((e=>d(e)?t.createVNode(t.Text,null,e,0):e))},interpolate:e=>e,type:"vnode"};function D(e){return i.value[e]||{}}Te++,n&&(t.watch(n.locale,(e=>{a&&(l.value=e,$.locale=e,se($,l.value,c.value))})),t.watch(n.fallbackLocale,(e=>{a&&(c.value=e,$.fallbackLocale=e,se($,l.value,c.value))})));return{id:Te,locale:I,fallbackLocale:W,get inheritLocale(){return a},set inheritLocale(e){a=e,e&&n&&(l.value=n.locale.value,c.value=n.fallbackLocale.value,se($,l.value,c.value))},get availableLocales(){return Object.keys(i.value).sort()},messages:N,datetimeFormats:S,numberFormats:E,get modifiers(){return M},get pluralRules(){return O||{}},get isGlobal(){return r},get missingWarn(){return k},set missingWarn(e){k=e,$.missingWarn=k},get fallbackWarn(){return _},set fallbackWarn(e){_=e,$.fallbackWarn=_},get fallbackRoot(){return y},set fallbackRoot(e){y=e},get fallbackFormat(){return F},set fallbackFormat(e){F=e,$.fallbackFormat=F},get warnHtmlMessage(){return P},set warnHtmlMessage(e){P=e,$.warnHtmlMessage=e},get escapeParameter(){return C},set escapeParameter(e){C=e,$.escapeParameter=e},t:H,rt:function(...e){const[t,n,r]=e;if(r&&!h(r))throw Error(15);return H(t,n,u({resolvedMessage:!0},r||{}))},d:function(...e){return j((t=>ge(t,...e)),(()=>de(...e)),0,(t=>t.d(...e)),(()=>""),(e=>d(e)))},n:function(...e){return j((t=>he(t,...e)),(()=>ke(...e)),0,(t=>t.n(...e)),(()=>""),(e=>d(e)))},te:function(e,t){return null!==x(D(d(t)?t:l.value),e)},tm:function(e){const t=function(e){let t=null;const n=ne($,c.value,l.value);for(let r=0;r{let n;const r=t;try{r.processor=R,n=fe(r,...e)}finally{r.processor=null}return n}),(()=>pe(...e)),0,(t=>t[ye](...e)),(e=>[t.createVNode(t.Text,null,e,0)]),(e=>p(e)))},[Le]:function(...e){return j((t=>he(t,...e)),(()=>ke(...e)),0,(t=>t[Le](...e)),(()=>[]),(e=>d(e)||p(e)))},[Fe]:function(...e){return j((t=>ge(t,...e)),(()=>de(...e)),0,(t=>t[Fe](...e)),(()=>[]),(e=>d(e)||p(e)))},[we]:function(e){O=e,$.pluralRules=O}}}function Oe(e={}){const t=$e(function(e){const t=d(e.locale)?e.locale:"en-US",n=d(e.fallbackLocale)||p(e.fallbackLocale)||v(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:t,r=g(e.missing)?e.missing:void 0,a=!b(e.silentTranslationWarn)&&!s(e.silentTranslationWarn)||!e.silentTranslationWarn,o=!b(e.silentFallbackWarn)&&!s(e.silentFallbackWarn)||!e.silentFallbackWarn,l=!b(e.fallbackRoot)||e.fallbackRoot,c=!!e.formatFallbackMessages,i=v(e.modifiers)?e.modifiers:{},f=e.pluralizationRules,m=g(e.postTranslation)?e.postTranslation:void 0,h=!d(e.warnHtmlInMessage)||"off"!==e.warnHtmlInMessage,k=!!e.escapeParameterHtml,_=!b(e.sync)||e.sync;let y=e.messages;if(v(e.sharedMessages)){const t=e.sharedMessages;y=Object.keys(t).reduce(((e,n)=>{const r=e[n]||(e[n]={});return u(r,t[n]),e}),y||{})}const{__i18n:F,__root:L}=e;return{locale:t,fallbackLocale:n,messages:y,flatJson:e.flatJson,datetimeFormats:e.datetimeFormats,numberFormats:e.numberFormats,missing:r,missingWarn:a,fallbackWarn:o,fallbackRoot:l,fallbackFormat:c,modifiers:i,pluralRules:f,postTranslation:m,warnHtmlMessage:h,escapeParameter:k,inheritLocale:_,__i18n:F,__root:L}}(e)),n={id:t.id,get locale(){return t.locale.value},set locale(e){t.locale.value=e},get fallbackLocale(){return t.fallbackLocale.value},set fallbackLocale(e){t.fallbackLocale.value=e},get messages(){return t.messages.value},get datetimeFormats(){return t.datetimeFormats.value},get numberFormats(){return t.numberFormats.value},get availableLocales(){return t.availableLocales},get formatter(){return{interpolate:()=>[]}},set formatter(e){},get missing(){return t.getMissingHandler()},set missing(e){t.setMissingHandler(e)},get silentTranslationWarn(){return b(t.missingWarn)?!t.missingWarn:t.missingWarn},set silentTranslationWarn(e){t.missingWarn=b(e)?!e:e},get silentFallbackWarn(){return b(t.fallbackWarn)?!t.fallbackWarn:t.fallbackWarn},set silentFallbackWarn(e){t.fallbackWarn=b(e)?!e:e},get modifiers(){return t.modifiers},get formatFallbackMessages(){return t.fallbackFormat},set formatFallbackMessages(e){t.fallbackFormat=e},get postTranslation(){return t.getPostTranslationHandler()},set postTranslation(e){t.setPostTranslationHandler(e)},get sync(){return t.inheritLocale},set sync(e){t.inheritLocale=e},get warnHtmlInMessage(){return t.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(e){t.warnHtmlMessage="off"!==e},get escapeParameterHtml(){return t.escapeParameter},set escapeParameterHtml(e){t.escapeParameter=e},get preserveDirectiveContent(){return!0},set preserveDirectiveContent(e){},get pluralizationRules(){return t.pluralRules||{}},__composer:t,t(...e){const[n,r,a]=e,o={};let s=null,l=null;if(!d(n))throw Error(15);const c=n;return d(r)?o.locale=r:p(r)?s=r:v(r)&&(l=r),p(a)?s=a:v(a)&&(l=a),t.t(c,s||l||{},o)},rt:(...e)=>t.rt(...e),tc(...e){const[n,r,a]=e,s={plural:1};let l=null,c=null;if(!d(n))throw Error(15);const u=n;return d(r)?s.locale=r:o(r)?s.plural=r:p(r)?l=r:v(r)&&(c=r),d(a)?s.locale=a:p(a)?l=a:v(a)&&(c=a),t.t(u,l||c||{},s)},te:(e,n)=>t.te(e,n),tm:e=>t.tm(e),getLocaleMessage:e=>t.getLocaleMessage(e),setLocaleMessage(e,n){t.setLocaleMessage(e,n)},mergeLocaleMessage(e,n){t.mergeLocaleMessage(e,n)},d:(...e)=>t.d(...e),getDateTimeFormat:e=>t.getDateTimeFormat(e),setDateTimeFormat(e,n){t.setDateTimeFormat(e,n)},mergeDateTimeFormat(e,n){t.mergeDateTimeFormat(e,n)},n:(...e)=>t.n(...e),getNumberFormat:e=>t.getNumberFormat(e),setNumberFormat(e,n){t.setNumberFormat(e,n)},mergeNumberFormat(e,n){t.mergeNumberFormat(e,n)},getChoiceIndex:(e,t)=>-1,__onComponentInstanceCreated(t){const{componentInstanceCreatedListener:r}=e;r&&r(t,n)}};return n}const Ie={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:e=>"parent"===e||"global"===e,default:"parent"},i18n:{type:Object}},We={name:"i18n-t",props:u({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:e=>o(e)||!isNaN(e)}},Ie),setup(e,n){const{slots:r,attrs:a}=n,o=e.i18n||Ae({useScope:e.scope}),s=Object.keys(r).filter((e=>"_"!==e));return()=>{const r={};e.locale&&(r.locale=e.locale),void 0!==e.plural&&(r.plural=d(e.plural)?+e.plural:e.plural);const l=function({slots:e},t){return 1===t.length&&"default"===t[0]?e.default?e.default():[]:t.reduce(((t,n)=>{const r=e[n];return r&&(t[n]=r()),t}),{})}(n,s),c=o[ye](e.keypath,l,r),i=u({},a);return d(e.tag)||h(e.tag)?t.h(e.tag,i,c):t.h(t.Fragment,i,c)}}};function Ne(e,n,r,a){const{slots:o,attrs:s}=n;return()=>{const n={part:!0};let l={};e.locale&&(n.locale=e.locale),d(e.format)?n.key=e.format:h(e.format)&&(d(e.format.key)&&(n.key=e.format.key),l=Object.keys(e.format).reduce(((t,n)=>r.includes(n)?u({},t,{[n]:e.format[n]}):t),{}));const c=a(e.value,n,l);let i=[n.key];p(c)?i=c.map(((e,t)=>{const n=o[e.type];return n?n({[e.type]:e.value,index:t,parts:c}):[e.value]})):d(c)&&(i=[c]);const f=u({},s);return d(e.tag)||h(e.tag)?t.h(e.tag,f,i):t.h(t.Fragment,f,i)}}const Se=["localeMatcher","style","unit","unitDisplay","currency","currencyDisplay","useGrouping","numberingSystem","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","notation","formatMatcher"],Ee={name:"i18n-n",props:u({value:{type:Number,required:!0},format:{type:[String,Object]}},Ie),setup(e,t){const n=e.i18n||Ae({useScope:"parent"});return Ne(e,t,Se,((...e)=>n[Le](...e)))}},je=["dateStyle","timeStyle","fractionalSecondDigits","calendar","dayPeriod","numberingSystem","localeMatcher","timeZone","hour12","hourCycle","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"],He={name:"i18n-d",props:u({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},Ie),setup(e,t){const n=e.i18n||Ae({useScope:"parent"});return Ne(e,t,je,((...e)=>n[Fe](...e)))}};function Re(e){const t=(t,{instance:n,value:r})=>{if(!n||!n.$)throw Error(22);const a=function(e,t){const n=e;if("composition"===e.mode)return n.__getInstance(t)||e.global;{const r=n.__getInstance(t);return null!=r?r.__composer:e.global.__composer}}(e,n.$),s=function(e){if(d(e))return{path:e};if(v(e)){if(!("path"in e))throw Error(19,"path");return e}throw Error(20)}(r);t.textContent=a.t(...function(e){const{path:t,locale:n,args:r,choice:a,plural:s}=e,l={},c=r||{};d(n)&&(l.locale=n);o(a)&&(l.plural=a);o(s)&&(l.plural=s);return[t,c,l]}(s))};return{beforeMount:t,beforeUpdate:t}}function De(e,t){e.locale=t.locale||e.locale,e.fallbackLocale=t.fallbackLocale||e.fallbackLocale,e.missing=t.missing||e.missing,e.silentTranslationWarn=t.silentTranslationWarn||e.silentFallbackWarn,e.silentFallbackWarn=t.silentFallbackWarn||e.silentFallbackWarn,e.formatFallbackMessages=t.formatFallbackMessages||e.formatFallbackMessages,e.postTranslation=t.postTranslation||e.postTranslation,e.warnHtmlInMessage=t.warnHtmlInMessage||e.warnHtmlInMessage,e.escapeParameterHtml=t.escapeParameterHtml||e.escapeParameterHtml,e.sync=t.sync||e.sync,e.__composer[we](t.pluralizationRules||e.pluralizationRules);const n=Pe(e.locale,{messages:t.messages,__i18n:t.__i18n});return Object.keys(n).forEach((t=>e.mergeLocaleMessage(t,n[t]))),t.datetimeFormats&&Object.keys(t.datetimeFormats).forEach((n=>e.mergeDateTimeFormat(n,t.datetimeFormats[n]))),t.numberFormats&&Object.keys(t.numberFormats).forEach((n=>e.mergeNumberFormat(n,t.numberFormats[n]))),e}function Ae(e={}){const n=t.getCurrentInstance();if(null==n)throw Error(16);if(!n.appContext.app.__VUE_I18N_SYMBOL__)throw Error(17);const r=t.inject(n.appContext.app.__VUE_I18N_SYMBOL__);if(!r)throw Error(22);const a="composition"===r.mode?r.global:r.global.__composer,o=l(e)?"__i18n"in n.type?"local":"global":e.useScope?e.useScope:"local";if("global"===o){let t=h(e.messages)?e.messages:{};"__i18nGlobal"in n.type&&(t=Pe(a.locale.value,{messages:t,__i18n:n.type.__i18nGlobal}));const r=Object.keys(t);if(r.length&&r.forEach((e=>{a.mergeLocaleMessage(e,t[e])})),h(e.datetimeFormats)){const t=Object.keys(e.datetimeFormats);t.length&&t.forEach((t=>{a.mergeDateTimeFormat(t,e.datetimeFormats[t])}))}if(h(e.numberFormats)){const t=Object.keys(e.numberFormats);t.length&&t.forEach((t=>{a.mergeNumberFormat(t,e.numberFormats[t])}))}return a}if("parent"===o){let e=function(e,t){let n=null;const r=t.root;let a=t.parent;for(;null!=a;){const t=e;if("composition"===e.mode)n=t.__getInstance(a);else{const e=t.__getInstance(a);null!=e&&(n=e.__composer)}if(null!=n)break;if(r===a)break;a=a.parent}return n}(r,n);return null==e&&(e=a),e}if("legacy"===r.mode)throw Error(18);const s=r;let c=s.__getInstance(n);if(null==c){const r=n.type,o=u({},e);r.__i18n&&(o.__i18n=r.__i18n),a&&(o.__root=a),c=$e(o),function(e,n,r){t.onMounted((()=>{}),n),t.onUnmounted((()=>{e.__deleteInstance(n)}),n)}(s,n),s.__setInstance(n,c)}return c}const Ue=["locale","fallbackLocale","availableLocales"],ze=["t","rt","d","n","tm"];return Q=function(e,t={}){{const n=(t.onCacheKey||le)(e),r=ce[n];if(r)return r;let a=!1;const o=t.onError||N;t.onError=e=>{a=!0,o(e)};const{code:s}=Z(e,t),l=new Function(`return ${s}`)();return a?l:ce[n]=l}},e.DatetimeFormat=He,e.NumberFormat=Ee,e.Translation=We,e.VERSION=ve,e.createI18n=function(e={}){const n=!b(e.legacy)||e.legacy,a=!!e.globalInjection,o=new Map,s=n?Oe(e):$e(e),l=r(""),c={get mode(){return n?"legacy":"composition"},async install(e,...r){e.__VUE_I18N_SYMBOL__=l,e.provide(e.__VUE_I18N_SYMBOL__,c),!n&&a&&function(e,n){const r=Object.create(null);Ue.forEach((e=>{const a=Object.getOwnPropertyDescriptor(n,e);if(!a)throw Error(22);const o=t.isRef(a.value)?{get:()=>a.value.value,set(e){a.value.value=e}}:{get:()=>a.get&&a.get()};Object.defineProperty(r,e,o)})),e.config.globalProperties.$i18n=r,ze.forEach((t=>{const r=Object.getOwnPropertyDescriptor(n,t);if(!r||!r.value)throw Error(22);Object.defineProperty(e.config.globalProperties,`$${t}`,r)}))}(e,c.global),function(e,t,...n){const r=v(n[0])?n[0]:{},a=!!r.useI18nComponentName;(!b(r.globalInstall)||r.globalInstall)&&(e.component(a?"i18n":We.name,We),e.component(Ee.name,Ee),e.component(He.name,He)),e.directive("t",Re(t))}(e,c,...r),n&&e.mixin(function(e,n,r){return{beforeCreate(){const a=t.getCurrentInstance();if(!a)throw Error(22);const o=this.$options;if(o.i18n){const t=o.i18n;o.__i18n&&(t.__i18n=o.__i18n),t.__root=n,this.$i18n=this===this.$root?De(e,t):Oe(t)}else this.$i18n=o.__i18n?this===this.$root?De(e,o):Oe({__i18n:o.__i18n,__root:n}):e;e.__onComponentInstanceCreated(this.$i18n),r.__setInstance(a,this.$i18n),this.$t=(...e)=>this.$i18n.t(...e),this.$rt=(...e)=>this.$i18n.rt(...e),this.$tc=(...e)=>this.$i18n.tc(...e),this.$te=(e,t)=>this.$i18n.te(e,t),this.$d=(...e)=>this.$i18n.d(...e),this.$n=(...e)=>this.$i18n.n(...e),this.$tm=e=>this.$i18n.tm(e)},mounted(){},beforeUnmount(){const e=t.getCurrentInstance();if(!e)throw Error(22);delete this.$t,delete this.$rt,delete this.$tc,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,r.__deleteInstance(e),delete this.$i18n}}}(s,s.__composer,c))},get global(){return s},__instances:o,__getInstance:e=>o.get(e)||null,__setInstance(e,t){o.set(e,t)},__deleteInstance(e){o.delete(e)}};return c},e.useI18n=Ae,e.vTDirective=Re,Object.defineProperty(e,"__esModule",{value:!0}),e}({},Vue); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..31716d6816199f4ff5d66ebed73c117a3ae8cb2b --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.js @@ -0,0 +1,3724 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; + +/** + * Original Utilities + * written by kazuya kawaguchi + */ +const inBrowser = typeof window !== 'undefined'; +let mark; +let measure; +{ + 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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} +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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; +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; +} + +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; +} + +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; +} + +/** @internal */ +const errorMessages$2 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` +}; +function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$2)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; +} + +const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' +}; + +let devtools = null; +function setDevToolsHook(hook) { + devtools = hook; +} +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$1 = { + [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$1(code, ...args) { + return format(warnMessages$1[code], ...args); +} + +/** + * Intlify core-base version + * @internal + */ +const VERSION$1 = '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; +// 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$1; + 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 + { + 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 isString(ret) ? ret : key; + } + else { + if (isTranslateMissingWarn(missingWarn, key)) { + onWarn(getWarnMessage$1(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); +} + +function createCoreError(code) { + return createCompileError(code, null, { messages: errorMessages$1 } ); +} +/** @internal */ +const errorMessages$1 = { + [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 (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 !! + { + // 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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!Availabilities.dateTimeFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (!Availabilities.numberFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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); + } +} + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +const VERSION = '9.1.7'; +/** + * This is only called development env + * istanbul-ignore-next + */ +function initDev() { + { + { + console.info(`You are running a development build of vue-i18n.\n` + + `Make sure to use the production build (*.prod.js) when deploying for production.`); + } + } +} + +const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` +}; +function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); +} + +function createI18nError(code, ...args) { + return createCompileError(code, null, { messages: errorMessages, args } ); +} +const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` +}; + +const DEVTOOLS_META = '__INTLIFY_META__'; +const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); +const DatetimePartsSymbol = makeSymbol('__datetimeParts'); +const NumberPartsSymbol = makeSymbol('__numberParts'); +const EnableEmitter = makeSymbol('__enableEmitter'); +const DisableEmitter = makeSymbol('__disableEmitter'); +const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); +let composerID = 0; +function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, getCurrentInstance() || undefined, type); + }); +} +function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; +} +const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } +} +// for Intlify DevTools +const getMetaInfo = /* #__PURE__*/ () => { + const instance = getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; +}; +/** + * Create composer interface factory + * + * @internal + */ +function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if (__root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; +} + +/** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ +function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if (options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if (options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; +} +/** + * create VueI18n interface factory + * + * @internal + */ +function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; +} + +const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } +}; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; + } +}; +function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } +} + +function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; +} + +const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' +]; +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } +}; + +const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' +]; +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } +}; + +function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } +} +function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if (modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; +} +function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } +} +function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; +} + +function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if (globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +function getDevtoolsGlobalHook() { + return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; +} +function getTarget() { + // @ts-ignore + return typeof navigator !== 'undefined' + ? window + : typeof global$1 !== 'undefined' + ? global$1 + : {}; +} + +const HOOK_SETUP = 'devtools-plugin:setup'; + +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 + }); + } +} + +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 +}; + +const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; +let devtoolsApi; +async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); +} +function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any +treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } +} +function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; +} +const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' +}; +function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); +} +function escapeChar(a) { + return ESC[a] || a; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; +} +function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } +} +function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } +} +function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } +} +function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; +} +function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } +} +function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } +} + +// supports compatibility for legacy vue-i18n APIs +function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; +} +function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = isBoolean(options.legacy) + ? options.legacy + : true; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol('vue-i18n' ); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __legacyMode + ? 'legacy' + : 'composition' + ; + }, + // install plugin + async install(app, ...options) { + { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; +} +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + let emitter = null; + onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +// NOTE: experimental !! +{ + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); +} +{ + initDev(); +} + +export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..cd8754c1dee975120099823e16b8bbc1b9d71e72 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-browser.prod.js @@ -0,0 +1,6 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import{ref as e,getCurrentInstance as t,computed as a,watch as n,createVNode as r,Text as l,h as o,Fragment as s,inject as i,onMounted as c,onUnmounted as u,isRef as m}from"vue";const f="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,g=e=>f?Symbol(e):e,p=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),b=e=>"number"==typeof e&&isFinite(e),_=e=>"[object RegExp]"===I(e),d=e=>S(e)&&0===Object.keys(e).length;function h(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const v=Object.assign;function k(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const F=Object.prototype.hasOwnProperty;function y(e,t){return F.call(e,t)}const w=Array.isArray,L=e=>"function"==typeof e,M=e=>"string"==typeof e,W=e=>"boolean"==typeof e,$=e=>null!==e&&"object"==typeof e,T=Object.prototype.toString,I=e=>T.call(e),S=e=>"[object Object]"===I(e),E=[];E[0]={w:[0],i:[3,0],"[":[4],o:[7]},E[1]={w:[1],".":[2],"[":[4],o:[7]},E[2]={w:[2],i:[3,0],0:[3,0]},E[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},E[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},E[5]={"'":[4,0],o:8,l:[5,0]},E[6]={'"':[4,0],o:8,l:[6,0]};const O=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function P(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function C(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(O.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}const H=new Map;function N(e,t){if(!$(e))return null;let a=H.get(t);if(a||(a=function(e){const t=[];let a,n,r,l,o,s,i,c=-1,u=0,m=0;const f=[];function g(){const t=e[c+1];if(5===u&&"'"===t||6===u&&'"'===t)return c++,r="\\"+t,f[0](),!0}for(f[0]=()=>{void 0===n?n=r:n+=r},f[1]=()=>{void 0!==n&&(t.push(n),n=void 0)},f[2]=()=>{f[0](),m++},f[3]=()=>{if(m>0)m--,u=4,f[0]();else{if(m=0,void 0===n)return!1;if(n=C(n),!1===n)return!1;f[1]()}};null!==u;)if(c++,a=e[c],"\\"!==a||!g()){if(l=P(a),i=E[u],o=i[l]||i.l||8,8===o)return;if(u=o[0],void 0!==o[1]&&(s=f[o[1]],s&&(r=a,!1===s())))return;if(7===u)return t}}(t),a&&H.set(t,a)),!a)return null;const n=a.length;let r=e,l=0;for(;le,D=e=>"",x=e=>0===e.length?"":e.join(""),U=e=>null==e?"":w(e)||S(e)&&e.toString===T?JSON.stringify(e,null,2):String(e);function z(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function A(e={}){const t=e.locale,a=function(e){const t=b(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(b(e.named.count)||b(e.named.n))?b(e.named.count)?e.named.count:b(e.named.n)?e.named.n:t:t}(e),n=$(e.pluralRules)&&M(t)&&L(e.pluralRules[t])?e.pluralRules[t]:z,r=$(e.pluralRules)&&M(t)&&L(e.pluralRules[t])?z:void 0,l=e.list||[],o=e.named||{};b(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(a,o);function s(t){const a=L(e.messages)?e.messages(t):!!$(e.messages)&&e.messages[t];return a||(e.parent?e.parent.message(t):D)}const i=S(e.processor)&&L(e.processor.normalize)?e.processor.normalize:x,c=S(e.processor)&&L(e.processor.interpolate)?e.processor.interpolate:U,u={list:e=>l[e],named:e=>o[e],plural:e=>e[n(a,e.length,r)],linked:(t,a)=>{const n=s(t)(u);return M(a)?(r=a,e.modifiers?e.modifiers[r]:R)(n):n;var r},message:s,type:S(e.processor)&&M(e.processor.type)?e.processor.type:"text",interpolate:c,normalize:i};return u}let J=0;function V(e={}){const t=M(e.version)?e.version:"9.1.7",a=M(e.locale)?e.locale:"en-US",n=w(e.fallbackLocale)||S(e.fallbackLocale)||M(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:a,r=S(e.messages)?e.messages:{[a]:{}},l=S(e.datetimeFormats)?e.datetimeFormats:{[a]:{}},o=S(e.numberFormats)?e.numberFormats:{[a]:{}},s=v({},e.modifiers||{},{upper:e=>M(e)?e.toUpperCase():e,lower:e=>M(e)?e.toLowerCase():e,capitalize:e=>M(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),i=e.pluralRules||{},c=L(e.missing)?e.missing:null,u=!W(e.missingWarn)&&!_(e.missingWarn)||e.missingWarn,m=!W(e.fallbackWarn)&&!_(e.fallbackWarn)||e.fallbackWarn,f=!!e.fallbackFormat,g=!!e.unresolving,p=L(e.postTranslation)?e.postTranslation:null,b=S(e.processor)?e.processor:null,d=!W(e.warnHtmlMessage)||e.warnHtmlMessage,k=!!e.escapeParameter,F=L(e.messageCompiler)?e.messageCompiler:undefined,y=L(e.onWarn)?e.onWarn:h,T=e,I=$(T.__datetimeFormatters)?T.__datetimeFormatters:new Map,E=$(T.__numberFormatters)?T.__numberFormatters:new Map,O=$(T.__meta)?T.__meta:{};J++;return{version:t,cid:J,locale:a,fallbackLocale:n,messages:r,datetimeFormats:l,numberFormats:o,modifiers:s,pluralRules:i,missing:c,missingWarn:u,fallbackWarn:m,fallbackFormat:f,unresolving:g,postTranslation:p,processor:b,warnHtmlMessage:d,escapeParameter:k,messageCompiler:F,onWarn:y,__datetimeFormatters:I,__numberFormatters:E,__meta:O}}function q(e,t,a,n,r){const{missing:l}=e;if(null!==l){const n=l(e,a,t,r);return M(n)?n:t}return t}function B(e,t,a){const n=e;n.__localeChainCache||(n.__localeChainCache=new Map);let r=n.__localeChainCache.get(a);if(!r){r=[];let e=[a];for(;w(e);)e=G(r,e,t);const l=w(t)?t:S(t)?t.default?t.default:null:t;e=M(l)?[l]:l,w(e)&&G(r,e,!1),n.__localeChainCache.set(a,r)}return r}function G(e,t,a){let n=!0;for(let r=0;r"",X=e=>L(e);function ee(e,...t){const{fallbackFormat:a,postTranslation:n,unresolving:r,fallbackLocale:l,messages:o}=e,[s,i]=ae(...t),c=(W(i.missingWarn),W(i.fallbackWarn),W(i.escapeParameter)?i.escapeParameter:e.escapeParameter),u=!!i.resolvedMessage,m=M(i.default)||W(i.default)?W(i.default)?s:i.default:a?s:"",f=a||""!==m,g=M(i.locale)?i.locale:e.locale;c&&function(e){w(e.list)?e.list=e.list.map((e=>M(e)?k(e):e)):$(e.named)&&Object.keys(e.named).forEach((t=>{M(e.named[t])&&(e.named[t]=k(e.named[t]))}))}(i);let[p,_,d]=u?[s,g,o[g]||{}]:function(e,t,a,n,r,l){const{messages:o}=e,s=B(e,n,a);let i,c={},u=null;const m="translate";for(let a=0;a{v=!0}));if(v)return p;const y=function(e,t,a){return t(a)}(0,F,A(function(e,t,a,n){const{modifiers:r,pluralRules:l}=e,o={locale:t,modifiers:r,pluralRules:l,messages:n=>{const r=N(a,n);if(M(r)){let a=!1;const l=te(e,n,t,r,n,(()=>{a=!0}));return a?Q:l}return X(r)?r:Q}};e.processor&&(o.processor=e.processor);n.list&&(o.list=n.list);n.named&&(o.named=n.named);b(n.plural)&&(o.pluralIndex=n.plural);return o}(e,_,d,i)));return n?n(y):y}function te(e,t,a,n,r,l){const{messageCompiler:o,warnHtmlMessage:s}=e;if(X(n)){const e=n;return e.locale=e.locale||a,e.key=e.key||t,e}const i=o(n,function(e,t,a,n,r,l){return{warnHtmlMessage:r,onError:e=>{throw l&&l(e),e},onCacheKey:e=>((e,t,a)=>p({l:e,k:t,s:a}))(t,a,e)}}(0,a,r,0,s,l));return i.locale=a,i.key=t,i.source=n,i}function ae(...e){const[t,a,n]=e,r={};if(!M(t)&&!b(t)&&!X(t))throw Error(14);const l=b(t)?String(t):(X(t),t);return b(a)?r.plural=a:M(a)?r.default=a:S(a)&&!d(a)?r.named=a:w(a)&&(r.list=a),b(n)?r.plural=n:M(n)?r.default=n:S(n)&&v(r,n),[l,r]}function ne(e,...t){const{datetimeFormats:a,unresolving:n,fallbackLocale:r}=e,{__datetimeFormatters:l}=e,[o,s,i,c]=re(...t);W(i.missingWarn);W(i.fallbackWarn);const u=!!i.part,m=M(i.locale)?i.locale:e.locale,f=B(e,r,m);if(!M(o)||""===o)return new Intl.DateTimeFormat(m).format(s);let g,p={},b=null;for(let t=0;te(n,r,t()||void 0,l)}function _e(e,t){const{messages:a,__i18n:n}=t,r=S(a)?a:w(n)?{}:{[e]:{}};if(w(n)&&n.forEach((({locale:e,resource:t})=>{e?(r[e]=r[e]||{},he(t,r[e])):he(t,r)})),t.flatJson)for(const e in r)y(r,e)&&j(r[e]);return r}const de=e=>!$(e)||w(e);function he(e,t){if(de(e)||de(t))throw Error(20);for(const a in e)y(e,a)&&(de(e[a])||de(t[a])?t[a]=e[a]:he(e[a],t[a]))}function ve(t={}){const{__root:o}=t,s=void 0===o;let i=!W(t.inheritLocale)||t.inheritLocale;const c=e(o&&i?o.locale.value:M(t.locale)?t.locale:"en-US"),u=e(o&&i?o.fallbackLocale.value:M(t.fallbackLocale)||w(t.fallbackLocale)||S(t.fallbackLocale)||!1===t.fallbackLocale?t.fallbackLocale:c.value),m=e(_e(c.value,t)),f=e(S(t.datetimeFormats)?t.datetimeFormats:{[c.value]:{}}),g=e(S(t.numberFormats)?t.numberFormats:{[c.value]:{}});let p=o?o.missingWarn:!W(t.missingWarn)&&!_(t.missingWarn)||t.missingWarn,d=o?o.fallbackWarn:!W(t.fallbackWarn)&&!_(t.fallbackWarn)||t.fallbackWarn,h=o?o.fallbackRoot:!W(t.fallbackRoot)||t.fallbackRoot,k=!!t.fallbackFormat,F=L(t.missing)?t.missing:null,y=L(t.missing)?be(t.missing):null,T=L(t.postTranslation)?t.postTranslation:null,I=!W(t.warnHtmlMessage)||t.warnHtmlMessage,E=!!t.escapeParameter;const O=o?o.modifiers:S(t.modifiers)?t.modifiers:{};let P,C=t.pluralRules||o&&o.pluralRules;P=V({version:"9.1.7",locale:c.value,fallbackLocale:u.value,messages:m.value,datetimeFormats:f.value,numberFormats:g.value,modifiers:O,pluralRules:C,missing:null===y?void 0:y,missingWarn:p,fallbackWarn:d,fallbackFormat:k,unresolving:!0,postTranslation:null===T?void 0:T,warnHtmlMessage:I,escapeParameter:E,__datetimeFormatters:S(P)?P.__datetimeFormatters:void 0,__numberFormatters:S(P)?P.__numberFormatters:void 0,__v_emitter:S(P)?P.__v_emitter:void 0,__meta:{framework:"vue"}}),K(P,c.value,u.value);const H=a({get:()=>c.value,set:e=>{c.value=e,P.locale=c.value}}),j=a({get:()=>u.value,set:e=>{u.value=e,P.fallbackLocale=u.value,K(P,c.value,e)}}),R=a((()=>m.value)),D=a((()=>f.value)),x=a((()=>g.value));function U(e,t,a,n,r,l){let s;if(s=e(P),b(s)&&-1===s){const[e,a]=t();return o&&h?n(o):r(e)}if(l(s))return s;throw Error(14)}function z(...e){return U((t=>ee(t,...e)),(()=>ae(...e)),0,(t=>t.t(...e)),(e=>e),(e=>M(e)))}const A={normalize:function(e){return e.map((e=>M(e)?r(l,null,e,0):e))},interpolate:e=>e,type:"vnode"};function J(e){return m.value[e]||{}}pe++,o&&(n(o.locale,(e=>{i&&(c.value=e,P.locale=e,K(P,c.value,u.value))})),n(o.fallbackLocale,(e=>{i&&(u.value=e,P.fallbackLocale=e,K(P,c.value,u.value))})));return{id:pe,locale:H,fallbackLocale:j,get inheritLocale(){return i},set inheritLocale(e){i=e,e&&o&&(c.value=o.locale.value,u.value=o.fallbackLocale.value,K(P,c.value,u.value))},get availableLocales(){return Object.keys(m.value).sort()},messages:R,datetimeFormats:D,numberFormats:x,get modifiers(){return O},get pluralRules(){return C||{}},get isGlobal(){return s},get missingWarn(){return p},set missingWarn(e){p=e,P.missingWarn=p},get fallbackWarn(){return d},set fallbackWarn(e){d=e,P.fallbackWarn=d},get fallbackRoot(){return h},set fallbackRoot(e){h=e},get fallbackFormat(){return k},set fallbackFormat(e){k=e,P.fallbackFormat=k},get warnHtmlMessage(){return I},set warnHtmlMessage(e){I=e,P.warnHtmlMessage=e},get escapeParameter(){return E},set escapeParameter(e){E=e,P.escapeParameter=e},t:z,rt:function(...e){const[t,a,n]=e;if(n&&!$(n))throw Error(15);return z(t,a,v({resolvedMessage:!0},n||{}))},d:function(...e){return U((t=>ne(t,...e)),(()=>re(...e)),0,(t=>t.d(...e)),(()=>""),(e=>M(e)))},n:function(...e){return U((t=>oe(t,...e)),(()=>se(...e)),0,(t=>t.n(...e)),(()=>""),(e=>M(e)))},te:function(e,t){return null!==N(J(M(t)?t:c.value),e)},tm:function(e){const t=function(e){let t=null;const a=B(P,u.value,c.value);for(let n=0;n{let a;const n=t;try{n.processor=A,a=ee(n,...e)}finally{n.processor=null}return a}),(()=>ae(...e)),0,(t=>t[ue](...e)),(e=>[r(l,null,e,0)]),(e=>w(e)))},[fe]:function(...e){return U((t=>oe(t,...e)),(()=>se(...e)),0,(t=>t[fe](...e)),(()=>[]),(e=>M(e)||w(e)))},[me]:function(...e){return U((t=>ne(t,...e)),(()=>re(...e)),0,(t=>t[me](...e)),(()=>[]),(e=>M(e)||w(e)))},[ge]:function(e){C=e,P.pluralRules=C}}}function ke(e={}){const t=ve(function(e){const t=M(e.locale)?e.locale:"en-US",a=M(e.fallbackLocale)||w(e.fallbackLocale)||S(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:t,n=L(e.missing)?e.missing:void 0,r=!W(e.silentTranslationWarn)&&!_(e.silentTranslationWarn)||!e.silentTranslationWarn,l=!W(e.silentFallbackWarn)&&!_(e.silentFallbackWarn)||!e.silentFallbackWarn,o=!W(e.fallbackRoot)||e.fallbackRoot,s=!!e.formatFallbackMessages,i=S(e.modifiers)?e.modifiers:{},c=e.pluralizationRules,u=L(e.postTranslation)?e.postTranslation:void 0,m=!M(e.warnHtmlInMessage)||"off"!==e.warnHtmlInMessage,f=!!e.escapeParameterHtml,g=!W(e.sync)||e.sync;let p=e.messages;if(S(e.sharedMessages)){const t=e.sharedMessages;p=Object.keys(t).reduce(((e,a)=>{const n=e[a]||(e[a]={});return v(n,t[a]),e}),p||{})}const{__i18n:b,__root:d}=e;return{locale:t,fallbackLocale:a,messages:p,flatJson:e.flatJson,datetimeFormats:e.datetimeFormats,numberFormats:e.numberFormats,missing:n,missingWarn:r,fallbackWarn:l,fallbackRoot:o,fallbackFormat:s,modifiers:i,pluralRules:c,postTranslation:u,warnHtmlMessage:m,escapeParameter:f,inheritLocale:g,__i18n:b,__root:d}}(e)),a={id:t.id,get locale(){return t.locale.value},set locale(e){t.locale.value=e},get fallbackLocale(){return t.fallbackLocale.value},set fallbackLocale(e){t.fallbackLocale.value=e},get messages(){return t.messages.value},get datetimeFormats(){return t.datetimeFormats.value},get numberFormats(){return t.numberFormats.value},get availableLocales(){return t.availableLocales},get formatter(){return{interpolate:()=>[]}},set formatter(e){},get missing(){return t.getMissingHandler()},set missing(e){t.setMissingHandler(e)},get silentTranslationWarn(){return W(t.missingWarn)?!t.missingWarn:t.missingWarn},set silentTranslationWarn(e){t.missingWarn=W(e)?!e:e},get silentFallbackWarn(){return W(t.fallbackWarn)?!t.fallbackWarn:t.fallbackWarn},set silentFallbackWarn(e){t.fallbackWarn=W(e)?!e:e},get modifiers(){return t.modifiers},get formatFallbackMessages(){return t.fallbackFormat},set formatFallbackMessages(e){t.fallbackFormat=e},get postTranslation(){return t.getPostTranslationHandler()},set postTranslation(e){t.setPostTranslationHandler(e)},get sync(){return t.inheritLocale},set sync(e){t.inheritLocale=e},get warnHtmlInMessage(){return t.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(e){t.warnHtmlMessage="off"!==e},get escapeParameterHtml(){return t.escapeParameter},set escapeParameterHtml(e){t.escapeParameter=e},get preserveDirectiveContent(){return!0},set preserveDirectiveContent(e){},get pluralizationRules(){return t.pluralRules||{}},__composer:t,t(...e){const[a,n,r]=e,l={};let o=null,s=null;if(!M(a))throw Error(15);const i=a;return M(n)?l.locale=n:w(n)?o=n:S(n)&&(s=n),w(r)?o=r:S(r)&&(s=r),t.t(i,o||s||{},l)},rt:(...e)=>t.rt(...e),tc(...e){const[a,n,r]=e,l={plural:1};let o=null,s=null;if(!M(a))throw Error(15);const i=a;return M(n)?l.locale=n:b(n)?l.plural=n:w(n)?o=n:S(n)&&(s=n),M(r)?l.locale=r:w(r)?o=r:S(r)&&(s=r),t.t(i,o||s||{},l)},te:(e,a)=>t.te(e,a),tm:e=>t.tm(e),getLocaleMessage:e=>t.getLocaleMessage(e),setLocaleMessage(e,a){t.setLocaleMessage(e,a)},mergeLocaleMessage(e,a){t.mergeLocaleMessage(e,a)},d:(...e)=>t.d(...e),getDateTimeFormat:e=>t.getDateTimeFormat(e),setDateTimeFormat(e,a){t.setDateTimeFormat(e,a)},mergeDateTimeFormat(e,a){t.mergeDateTimeFormat(e,a)},n:(...e)=>t.n(...e),getNumberFormat:e=>t.getNumberFormat(e),setNumberFormat(e,a){t.setNumberFormat(e,a)},mergeNumberFormat(e,a){t.mergeNumberFormat(e,a)},getChoiceIndex:(e,t)=>-1,__onComponentInstanceCreated(t){const{componentInstanceCreatedListener:n}=e;n&&n(t,a)}};return a}const Fe={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:e=>"parent"===e||"global"===e,default:"parent"},i18n:{type:Object}},ye={name:"i18n-t",props:v({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:e=>b(e)||!isNaN(e)}},Fe),setup(e,t){const{slots:a,attrs:n}=t,r=e.i18n||Ee({useScope:e.scope}),l=Object.keys(a).filter((e=>"_"!==e));return()=>{const a={};e.locale&&(a.locale=e.locale),void 0!==e.plural&&(a.plural=M(e.plural)?+e.plural:e.plural);const i=function({slots:e},t){return 1===t.length&&"default"===t[0]?e.default?e.default():[]:t.reduce(((t,a)=>{const n=e[a];return n&&(t[a]=n()),t}),{})}(t,l),c=r[ue](e.keypath,i,a),u=v({},n);return M(e.tag)||$(e.tag)?o(e.tag,u,c):o(s,u,c)}}};function we(e,t,a,n){const{slots:r,attrs:l}=t;return()=>{const t={part:!0};let i={};e.locale&&(t.locale=e.locale),M(e.format)?t.key=e.format:$(e.format)&&(M(e.format.key)&&(t.key=e.format.key),i=Object.keys(e.format).reduce(((t,n)=>a.includes(n)?v({},t,{[n]:e.format[n]}):t),{}));const c=n(e.value,t,i);let u=[t.key];w(c)?u=c.map(((e,t)=>{const a=r[e.type];return a?a({[e.type]:e.value,index:t,parts:c}):[e.value]})):M(c)&&(u=[c]);const m=v({},l);return M(e.tag)||$(e.tag)?o(e.tag,m,u):o(s,m,u)}}const Le=["localeMatcher","style","unit","unitDisplay","currency","currencyDisplay","useGrouping","numberingSystem","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","notation","formatMatcher"],Me={name:"i18n-n",props:v({value:{type:Number,required:!0},format:{type:[String,Object]}},Fe),setup(e,t){const a=e.i18n||Ee({useScope:"parent"});return we(e,t,Le,((...e)=>a[fe](...e)))}},We=["dateStyle","timeStyle","fractionalSecondDigits","calendar","dayPeriod","numberingSystem","localeMatcher","timeZone","hour12","hourCycle","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"],$e={name:"i18n-d",props:v({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},Fe),setup(e,t){const a=e.i18n||Ee({useScope:"parent"});return we(e,t,We,((...e)=>a[me](...e)))}};function Te(e){const t=(t,{instance:a,value:n})=>{if(!a||!a.$)throw Error(22);const r=function(e,t){const a=e;if("composition"===e.mode)return a.__getInstance(t)||e.global;{const n=a.__getInstance(t);return null!=n?n.__composer:e.global.__composer}}(e,a.$),l=function(e){if(M(e))return{path:e};if(S(e)){if(!("path"in e))throw Error(19,"path");return e}throw Error(20)}(n);t.textContent=r.t(...function(e){const{path:t,locale:a,args:n,choice:r,plural:l}=e,o={},s=n||{};M(a)&&(o.locale=a);b(r)&&(o.plural=r);b(l)&&(o.plural=l);return[t,s,o]}(l))};return{beforeMount:t,beforeUpdate:t}}function Ie(e,t){e.locale=t.locale||e.locale,e.fallbackLocale=t.fallbackLocale||e.fallbackLocale,e.missing=t.missing||e.missing,e.silentTranslationWarn=t.silentTranslationWarn||e.silentFallbackWarn,e.silentFallbackWarn=t.silentFallbackWarn||e.silentFallbackWarn,e.formatFallbackMessages=t.formatFallbackMessages||e.formatFallbackMessages,e.postTranslation=t.postTranslation||e.postTranslation,e.warnHtmlInMessage=t.warnHtmlInMessage||e.warnHtmlInMessage,e.escapeParameterHtml=t.escapeParameterHtml||e.escapeParameterHtml,e.sync=t.sync||e.sync,e.__composer[ge](t.pluralizationRules||e.pluralizationRules);const a=_e(e.locale,{messages:t.messages,__i18n:t.__i18n});return Object.keys(a).forEach((t=>e.mergeLocaleMessage(t,a[t]))),t.datetimeFormats&&Object.keys(t.datetimeFormats).forEach((a=>e.mergeDateTimeFormat(a,t.datetimeFormats[a]))),t.numberFormats&&Object.keys(t.numberFormats).forEach((a=>e.mergeNumberFormat(a,t.numberFormats[a]))),e}function Se(e={}){const a=!W(e.legacy)||e.legacy,n=!!e.globalInjection,r=new Map,l=a?ke(e):ve(e),o=g(""),s={get mode(){return a?"legacy":"composition"},async install(e,...r){e.__VUE_I18N_SYMBOL__=o,e.provide(e.__VUE_I18N_SYMBOL__,s),!a&&n&&function(e,t){const a=Object.create(null);Oe.forEach((e=>{const n=Object.getOwnPropertyDescriptor(t,e);if(!n)throw Error(22);const r=m(n.value)?{get:()=>n.value.value,set(e){n.value.value=e}}:{get:()=>n.get&&n.get()};Object.defineProperty(a,e,r)})),e.config.globalProperties.$i18n=a,Pe.forEach((a=>{const n=Object.getOwnPropertyDescriptor(t,a);if(!n||!n.value)throw Error(22);Object.defineProperty(e.config.globalProperties,`$${a}`,n)}))}(e,s.global),function(e,t,...a){const n=S(a[0])?a[0]:{},r=!!n.useI18nComponentName;(!W(n.globalInstall)||n.globalInstall)&&(e.component(r?"i18n":ye.name,ye),e.component(Me.name,Me),e.component($e.name,$e)),e.directive("t",Te(t))}(e,s,...r),a&&e.mixin(function(e,a,n){return{beforeCreate(){const r=t();if(!r)throw Error(22);const l=this.$options;if(l.i18n){const t=l.i18n;l.__i18n&&(t.__i18n=l.__i18n),t.__root=a,this.$i18n=this===this.$root?Ie(e,t):ke(t)}else this.$i18n=l.__i18n?this===this.$root?Ie(e,l):ke({__i18n:l.__i18n,__root:a}):e;e.__onComponentInstanceCreated(this.$i18n),n.__setInstance(r,this.$i18n),this.$t=(...e)=>this.$i18n.t(...e),this.$rt=(...e)=>this.$i18n.rt(...e),this.$tc=(...e)=>this.$i18n.tc(...e),this.$te=(e,t)=>this.$i18n.te(e,t),this.$d=(...e)=>this.$i18n.d(...e),this.$n=(...e)=>this.$i18n.n(...e),this.$tm=e=>this.$i18n.tm(e)},mounted(){},beforeUnmount(){const e=t();if(!e)throw Error(22);delete this.$t,delete this.$rt,delete this.$tc,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,n.__deleteInstance(e),delete this.$i18n}}}(l,l.__composer,s))},get global(){return l},__instances:r,__getInstance:e=>r.get(e)||null,__setInstance(e,t){r.set(e,t)},__deleteInstance(e){r.delete(e)}};return s}function Ee(e={}){const a=t();if(null==a)throw Error(16);if(!a.appContext.app.__VUE_I18N_SYMBOL__)throw Error(17);const n=i(a.appContext.app.__VUE_I18N_SYMBOL__);if(!n)throw Error(22);const r="composition"===n.mode?n.global:n.global.__composer,l=d(e)?"__i18n"in a.type?"local":"global":e.useScope?e.useScope:"local";if("global"===l){let t=$(e.messages)?e.messages:{};"__i18nGlobal"in a.type&&(t=_e(r.locale.value,{messages:t,__i18n:a.type.__i18nGlobal}));const n=Object.keys(t);if(n.length&&n.forEach((e=>{r.mergeLocaleMessage(e,t[e])})),$(e.datetimeFormats)){const t=Object.keys(e.datetimeFormats);t.length&&t.forEach((t=>{r.mergeDateTimeFormat(t,e.datetimeFormats[t])}))}if($(e.numberFormats)){const t=Object.keys(e.numberFormats);t.length&&t.forEach((t=>{r.mergeNumberFormat(t,e.numberFormats[t])}))}return r}if("parent"===l){let e=function(e,t){let a=null;const n=t.root;let r=t.parent;for(;null!=r;){const t=e;if("composition"===e.mode)a=t.__getInstance(r);else{const e=t.__getInstance(r);null!=e&&(a=e.__composer)}if(null!=a)break;if(n===r)break;r=r.parent}return a}(n,a);return null==e&&(e=r),e}if("legacy"===n.mode)throw Error(18);const o=n;let s=o.__getInstance(a);if(null==s){const t=a.type,n=v({},e);t.__i18n&&(n.__i18n=t.__i18n),r&&(n.__root=r),s=ve(n),function(e,t,a){c((()=>{}),t),u((()=>{e.__deleteInstance(t)}),t)}(o,a),o.__setInstance(a,s)}return s}const Oe=["locale","fallbackLocale","availableLocales"],Pe=["t","rt","d","n","tm"];export{$e as DatetimeFormat,Me as NumberFormat,ye as Translation,ce as VERSION,Se as createI18n,Ee as useI18n,Te as vTDirective}; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-bundler.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..1e69644749a335a465faba270a3abd97a07900f6 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-bundler.js @@ -0,0 +1,2224 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, hasOwn, isObject, isBoolean, isString, isRegExp, isFunction, assign, isNumber, warn, createEmitter, isEmptyObject } from '@intlify/shared'; +import { createCompileError, handleFlatJson, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, getLocaleChain, setDevToolsHook } from '@intlify/core-base'; +import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; +import { setupDevtoolsPlugin } from '@vue/devtools-api'; +import { VueDevToolsLabels, VueDevToolsPlaceholders, VueDevToolsTimelineColors } from '@intlify/vue-devtools'; + +/** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ +const VERSION = '9.1.7'; +/** + * This is only called in esm-bundler builds. + * istanbul-ignore-next + */ +function initFeatureFlags() { + let needWarn = false; + if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true; + } + if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_LEGACY_API__ = true; + } + if (typeof __VUE_I18N_PROD_DEVTOOLS__ !== 'boolean') { + needWarn = true; + getGlobalThis().__VUE_I18N_PROD_DEVTOOLS__ = false; + } + if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') { + getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false; + } + if ((process.env.NODE_ENV !== 'production') && typeof true === 'boolean') { + needWarn = true; + } + if ((process.env.NODE_ENV !== 'production') && needWarn) { + console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` + + `configure your bundler to explicitly replace feature flag globals ` + + `with boolean literals to get proper tree-shaking in the final bundle.`); + } +} + +const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` +}; +function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); +} + +function createI18nError(code, ...args) { + return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined); +} +const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` +}; + +const DEVTOOLS_META = '__INTLIFY_META__'; +const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); +const DatetimePartsSymbol = makeSymbol('__datetimeParts'); +const NumberPartsSymbol = makeSymbol('__numberParts'); +const EnableEmitter = makeSymbol('__enableEmitter'); +const DisableEmitter = makeSymbol('__disableEmitter'); +const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); +makeSymbol('__intlifyMeta'); +let composerID = 0; +function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, getCurrentInstance() || undefined, type); + }); +} +function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; +} +const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } +} +// for Intlify DevTools +const getMetaInfo = /* #__PURE__*/ () => { + const instance = getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; +}; +/** + * Create composer interface factory + * + * @internal + */ +function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + else { + ret = fn(_context); + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if ((process.env.NODE_ENV !== 'production') && + __root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; +} + +/** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ +function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if ((process.env.NODE_ENV !== 'production') && options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; +} +/** + * create VueI18n interface factory + * + * @internal + */ +function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + (process.env.NODE_ENV !== 'production') && + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + if ((process.env.NODE_ENV !== 'production')) { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; +} + +const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } +}; + +/** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ +const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; + } +}; +function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } +} + +function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? h(props.tag, assignedAttrs, children) + : h(Fragment, assignedAttrs, children); + }; +} + +const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' +]; +/** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ +const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } +}; + +const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' +]; +/** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ +const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } +}; + +function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } +} +function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; +} +function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } +} +function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; +} + +function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); +} + +const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; +let devtoolsApi; +async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); +} +function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any +treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } +} +function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; +} +const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' +}; +function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); +} +function escapeChar(a) { + return ESC[a] || a; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; +} +function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } +} +function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } +} +function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } +} +function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; +} +function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } +} +function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } +} + +// supports compatibility for legacy vue-i18n APIs +function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; +} +function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; +} + +/** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ +function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy) + ? options.legacy + : __VUE_I18N_LEGACY_API__; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __VUE_I18N_LEGACY_API__ && __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : ''); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __VUE_I18N_LEGACY_API__ + ? __legacyMode + ? 'legacy' + : 'composition' + : 'composition'; + }, + // install plugin + async install(app, ...options) { + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + if (__VUE_I18N_FULL_INSTALL__) { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__VUE_I18N_LEGACY_API__ && __legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; +} +/** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ +function useI18n(options = {}) { + const instance = getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + if ((process.env.NODE_ENV !== 'production')) { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; +} +function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; +} +function setupLifeCycle(i18n, target, composer) { + let emitter = null; + onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && + !false && + target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && + !false && + target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); +} +const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' +]; +const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; +function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); +} + +{ + initFeatureFlags(); +} +// NOTE: experimental !! +if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) { + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); +} +if ((process.env.NODE_ENV !== 'production')) ; + +export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective }; diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.js new file mode 100644 index 0000000000000000000000000000000000000000..e14b45622dca0c5612e9ff5e7bb3d9e40592a61e --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.js @@ -0,0 +1,3737 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var VueI18n = (function (exports, vue) { + 'use strict'; + + /** + * Original Utilities + * written by kazuya kawaguchi + */ + const inBrowser = typeof window !== 'undefined'; + let mark; + let measure; + { + 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, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + 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 isObject = (val) => // eslint-disable-line + val !== null && typeof val === 'object'; + 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; + } + + 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; + } + + 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; + } + + /** @internal */ + const errorMessages$2 = { + // tokenizer error messages + [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, + [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, + [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, + [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, + [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, + [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, + [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, + [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, + [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, + [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, + // parser error messages + [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, + [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`, + [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`, + [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` + }; + function createCompileError(code, loc, options = {}) { + const { domain, messages, args } = options; + const msg = format((messages || errorMessages$2)[code] || '', ...(args || [])) + ; + const error = new SyntaxError(String(msg)); + error.code = code; + if (loc) { + error.location = loc; + } + error.domain = domain; + return error; + } + + const IntlifyDevToolsHooks = { + I18nInit: 'i18n:init', + FunctionTranslate: 'function:translate' + }; + + let devtools = null; + function setDevToolsHook(hook) { + devtools = hook; + } + 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$1 = { + [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$1(code, ...args) { + return format(warnMessages$1[code], ...args); + } + + /** + * Intlify core-base version + * @internal + */ + const VERSION$1 = '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; + // 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$1; + 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 + { + 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 isString(ret) ? ret : key; + } + else { + if (isTranslateMissingWarn(missingWarn, key)) { + onWarn(getWarnMessage$1(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); + } + + function createCoreError(code) { + return createCompileError(code, null, { messages: errorMessages$1 } ); + } + /** @internal */ + const errorMessages$1 = { + [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 (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 !! + { + // 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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (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 (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 (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 (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 (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); + { + 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); + } + }, + 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 (!Availabilities.dateTimeFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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 (!Availabilities.numberFormat) { + onWarn(getWarnMessage$1(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 (locale !== targetLocale && + isTranslateFallbackWarn(fallbackWarn, key)) { + onWarn(getWarnMessage$1(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 (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); + } + } + + /** + * Vue I18n Version + * + * @remarks + * Semver format. Same format as the package.json `version` field. + * + * @VueI18nGeneral + */ + const VERSION = '9.1.7'; + /** + * This is only called development env + * istanbul-ignore-next + */ + function initDev() { + { + { + console.info(`You are running a development build of vue-i18n.\n` + + `Make sure to use the production build (*.prod.js) when deploying for production.`); + } + } + } + + const warnMessages = { + [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, + [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, + [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, + [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, + [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, + [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, + [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` + }; + function getWarnMessage(code, ...args) { + return format(warnMessages[code], ...args); + } + + function createI18nError(code, ...args) { + return createCompileError(code, null, { messages: errorMessages, args } ); + } + const errorMessages = { + [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', + [15 /* INVALID_ARGUMENT */]: 'Invalid argument', + [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', + [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', + [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', + [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', + [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, + [20 /* INVALID_VALUE */]: `Invalid value`, + [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` + }; + + const DEVTOOLS_META = '__INTLIFY_META__'; + const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); + const DatetimePartsSymbol = makeSymbol('__datetimeParts'); + const NumberPartsSymbol = makeSymbol('__numberParts'); + const EnableEmitter = makeSymbol('__enableEmitter'); + const DisableEmitter = makeSymbol('__disableEmitter'); + const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); + let composerID = 0; + function defineCoreMissingHandler(missing) { + return ((ctx, locale, key, type) => { + return missing(locale, key, vue.getCurrentInstance() || undefined, type); + }); + } + function getLocaleMessages(locale, options) { + const { messages, __i18n } = options; + // prettier-ignore + const ret = isPlainObject(messages) + ? messages + : isArray(__i18n) + ? {} + : { [locale]: {} }; + // merge locale messages of i18n custom block + if (isArray(__i18n)) { + __i18n.forEach(({ locale, resource }) => { + if (locale) { + ret[locale] = ret[locale] || {}; + deepCopy(resource, ret[locale]); + } + else { + deepCopy(resource, ret); + } + }); + } + // handle messages for flat json + if (options.flatJson) { + for (const key in ret) { + if (hasOwn(ret, key)) { + handleFlatJson(ret[key]); + } + } + } + return ret; + } + const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function deepCopy(src, des) { + // src and des should both be objects, and non of then can be a array + if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { + throw createI18nError(20 /* INVALID_VALUE */); + } + for (const key in src) { + if (hasOwn(src, key)) { + if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { + // replace with src[key] when: + // src[key] or des[key] is not a object, or + // src[key] or des[key] is a array + des[key] = src[key]; + } + else { + // src[key] and des[key] are both object, merge them + deepCopy(src[key], des[key]); + } + } + } + } + // for Intlify DevTools + const getMetaInfo = /* #__PURE__*/ () => { + const instance = vue.getCurrentInstance(); + return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any + ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any + : null; + }; + /** + * Create composer interface factory + * + * @internal + */ + function createComposer(options = {}) { + const { __root } = options; + const _isGlobal = __root === undefined; + let _inheritLocale = isBoolean(options.inheritLocale) + ? options.inheritLocale + : true; + const _locale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.locale.value + : isString(options.locale) + ? options.locale + : 'en-US'); + const _fallbackLocale = vue.ref( + // prettier-ignore + __root && _inheritLocale + ? __root.fallbackLocale.value + : isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : _locale.value); + const _messages = vue.ref(getLocaleMessages(_locale.value, options)); + const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats) + ? options.datetimeFormats + : { [_locale.value]: {} }); + const _numberFormats = vue.ref(isPlainObject(options.numberFormats) + ? options.numberFormats + : { [_locale.value]: {} }); + // warning suppress options + // prettier-ignore + let _missingWarn = __root + ? __root.missingWarn + : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) + ? options.missingWarn + : true; + // prettier-ignore + let _fallbackWarn = __root + ? __root.fallbackWarn + : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) + ? options.fallbackWarn + : true; + // prettier-ignore + let _fallbackRoot = __root + ? __root.fallbackRoot + : isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + // configure fall back to root + let _fallbackFormat = !!options.fallbackFormat; + // runtime missing + let _missing = isFunction(options.missing) ? options.missing : null; + let _runtimeMissing = isFunction(options.missing) + ? defineCoreMissingHandler(options.missing) + : null; + // postTranslation handler + let _postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : null; + let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) + ? options.warnHtmlMessage + : true; + let _escapeParameter = !!options.escapeParameter; + // custom linked modifiers + // prettier-ignore + const _modifiers = __root + ? __root.modifiers + : isPlainObject(options.modifiers) + ? options.modifiers + : {}; + // pluralRules + let _pluralRules = options.pluralRules || (__root && __root.pluralRules); + // runtime context + // eslint-disable-next-line prefer-const + let _context; + function getCoreContext() { + return createCoreContext({ + version: VERSION, + locale: _locale.value, + fallbackLocale: _fallbackLocale.value, + messages: _messages.value, + datetimeFormats: _datetimeFormats.value, + numberFormats: _numberFormats.value, + modifiers: _modifiers, + pluralRules: _pluralRules, + missing: _runtimeMissing === null ? undefined : _runtimeMissing, + missingWarn: _missingWarn, + fallbackWarn: _fallbackWarn, + fallbackFormat: _fallbackFormat, + unresolving: true, + postTranslation: _postTranslation === null ? undefined : _postTranslation, + warnHtmlMessage: _warnHtmlMessage, + escapeParameter: _escapeParameter, + __datetimeFormatters: isPlainObject(_context) + ? _context.__datetimeFormatters + : undefined, + __numberFormatters: isPlainObject(_context) + ? _context.__numberFormatters + : undefined, + __v_emitter: isPlainObject(_context) + ? _context.__v_emitter + : undefined, + __meta: { framework: 'vue' } + }); + } + _context = getCoreContext(); + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + // track reactivity + function trackReactivityValues() { + return [ + _locale.value, + _fallbackLocale.value, + _messages.value, + _datetimeFormats.value, + _numberFormats.value + ]; + } + // locale + const locale = vue.computed({ + get: () => _locale.value, + set: val => { + _locale.value = val; + _context.locale = _locale.value; + } + }); + // fallbackLocale + const fallbackLocale = vue.computed({ + get: () => _fallbackLocale.value, + set: val => { + _fallbackLocale.value = val; + _context.fallbackLocale = _fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, val); + } + }); + // messages + const messages = vue.computed(() => _messages.value); + // datetimeFormats + const datetimeFormats = vue.computed(() => _datetimeFormats.value); + // numberFormats + const numberFormats = vue.computed(() => _numberFormats.value); + // getPostTranslationHandler + function getPostTranslationHandler() { + return isFunction(_postTranslation) ? _postTranslation : null; + } + // setPostTranslationHandler + function setPostTranslationHandler(handler) { + _postTranslation = handler; + _context.postTranslation = handler; + } + // getMissingHandler + function getMissingHandler() { + return _missing; + } + // setMissingHandler + function setMissingHandler(handler) { + if (handler !== null) { + _runtimeMissing = defineCoreMissingHandler(handler); + } + _missing = handler; + _context.missing = _runtimeMissing; + } + function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any + ) { + return type !== 'translate' || !!arg.resolvedMessage === false; + } + function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { + trackReactivityValues(); // track reactive dependency + // NOTE: experimental !! + let ret; + { + try { + setAdditionalMeta(getMetaInfo()); + ret = fn(_context); + } + finally { + setAdditionalMeta(null); + } + } + if (isNumber(ret) && ret === NOT_REOSLVED) { + const [key, arg2] = argumentParser(); + if (__root && + isString(key) && + isResolvedTranslateMessage(warnType, arg2)) { + if (_fallbackRoot && + (isTranslateFallbackWarn(_fallbackWarn, key) || + isTranslateMissingWarn(_missingWarn, key))) { + warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { + key, + type: warnType + })); + } + // for vue-devtools timeline event + { + const { __v_emitter: emitter } = _context; + if (emitter && _fallbackRoot) { + emitter.emit("fallback" /* FALBACK */, { + type: warnType, + key, + to: 'global', + groupId: `${warnType}:${key}` + }); + } + } + } + return __root && _fallbackRoot + ? fallbackSuccess(__root) + : fallbackFail(key); + } + else if (successCondition(ret)) { + return ret; + } + else { + /* istanbul ignore next */ + throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); + } + } + // t + function t(...args) { + return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val)); + } + // rt + function rt(...args) { + const [arg1, arg2, arg3] = args; + if (arg3 && !isObject(arg3)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]); + } + // d + function d(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // n + function n(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); + } + // for custom processor + function normalize(values) { + return values.map(val => isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val); + } + const interpolate = (val) => val; + const processor = { + normalize, + interpolate, + type: 'vnode' + }; + // transrateVNode, using for `i18n-t` component + function transrateVNode(...args) { + return wrapWithDeps(context => { + let ret; + const _context = context; + try { + _context.processor = processor; + ret = translate(_context, ...args); + } + finally { + _context.processor = null; + } + return ret; + }, () => parseTranslateArgs(...args), 'translate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => isArray(val)); + } + // numberParts, using for `i18n-n` component + function numberParts(...args) { + return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + // datetimeParts, using for `i18n-d` component + function datetimeParts(...args) { + return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); + } + function setPluralRules(rules) { + _pluralRules = rules; + _context.pluralRules = _pluralRules; + } + // te + function te(key, locale) { + const targetLocale = isString(locale) ? locale : _locale.value; + const message = getLocaleMessage(targetLocale); + return resolveValue(message, key) !== null; + } + function resolveMessages(key) { + let messages = null; + const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value); + for (let i = 0; i < locales.length; i++) { + const targetLocaleMessages = _messages.value[locales[i]] || {}; + const messageValue = resolveValue(targetLocaleMessages, key); + if (messageValue != null) { + messages = messageValue; + break; + } + } + return messages; + } + // tm + function tm(key) { + const messages = resolveMessages(key); + // prettier-ignore + return messages != null + ? messages + : __root + ? __root.tm(key) || {} + : {}; + } + // getLocaleMessage + function getLocaleMessage(locale) { + return (_messages.value[locale] || {}); + } + // setLocaleMessage + function setLocaleMessage(locale, message) { + _messages.value[locale] = message; + _context.messages = _messages.value; + } + // mergeLocaleMessage + function mergeLocaleMessage(locale, message) { + _messages.value[locale] = _messages.value[locale] || {}; + deepCopy(message, _messages.value[locale]); + _context.messages = _messages.value; + } + // getDateTimeFormat + function getDateTimeFormat(locale) { + return _datetimeFormats.value[locale] || {}; + } + // setDateTimeFormat + function setDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = format; + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // mergeDateTimeFormat + function mergeDateTimeFormat(locale, format) { + _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format); + _context.datetimeFormats = _datetimeFormats.value; + clearDateTimeFormat(_context, locale, format); + } + // getNumberFormat + function getNumberFormat(locale) { + return _numberFormats.value[locale] || {}; + } + // setNumberFormat + function setNumberFormat(locale, format) { + _numberFormats.value[locale] = format; + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // mergeNumberFormat + function mergeNumberFormat(locale, format) { + _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format); + _context.numberFormats = _numberFormats.value; + clearNumberFormat(_context, locale, format); + } + // for debug + composerID++; + // watch root locale & fallbackLocale + if (__root) { + vue.watch(__root.locale, (val) => { + if (_inheritLocale) { + _locale.value = val; + _context.locale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + vue.watch(__root.fallbackLocale, (val) => { + if (_inheritLocale) { + _fallbackLocale.value = val; + _context.fallbackLocale = val; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }); + } + // define composition API! + const composer = { + id: composerID, + locale, + fallbackLocale, + get inheritLocale() { + return _inheritLocale; + }, + set inheritLocale(val) { + _inheritLocale = val; + if (val && __root) { + _locale.value = __root.locale.value; + _fallbackLocale.value = __root.fallbackLocale.value; + updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); + } + }, + get availableLocales() { + return Object.keys(_messages.value).sort(); + }, + messages, + datetimeFormats, + numberFormats, + get modifiers() { + return _modifiers; + }, + get pluralRules() { + return _pluralRules || {}; + }, + get isGlobal() { + return _isGlobal; + }, + get missingWarn() { + return _missingWarn; + }, + set missingWarn(val) { + _missingWarn = val; + _context.missingWarn = _missingWarn; + }, + get fallbackWarn() { + return _fallbackWarn; + }, + set fallbackWarn(val) { + _fallbackWarn = val; + _context.fallbackWarn = _fallbackWarn; + }, + get fallbackRoot() { + return _fallbackRoot; + }, + set fallbackRoot(val) { + _fallbackRoot = val; + }, + get fallbackFormat() { + return _fallbackFormat; + }, + set fallbackFormat(val) { + _fallbackFormat = val; + _context.fallbackFormat = _fallbackFormat; + }, + get warnHtmlMessage() { + return _warnHtmlMessage; + }, + set warnHtmlMessage(val) { + _warnHtmlMessage = val; + _context.warnHtmlMessage = val; + }, + get escapeParameter() { + return _escapeParameter; + }, + set escapeParameter(val) { + _escapeParameter = val; + _context.escapeParameter = val; + }, + t, + rt, + d, + n, + te, + tm, + getLocaleMessage, + setLocaleMessage, + mergeLocaleMessage, + getDateTimeFormat, + setDateTimeFormat, + mergeDateTimeFormat, + getNumberFormat, + setNumberFormat, + mergeNumberFormat, + getPostTranslationHandler, + setPostTranslationHandler, + getMissingHandler, + setMissingHandler, + [TransrateVNodeSymbol]: transrateVNode, + [NumberPartsSymbol]: numberParts, + [DatetimePartsSymbol]: datetimeParts, + [SetPluralRulesSymbol]: setPluralRules + }; + // for vue-devtools timeline event + { + composer[EnableEmitter] = (emitter) => { + _context.__v_emitter = emitter; + }; + composer[DisableEmitter] = () => { + _context.__v_emitter = undefined; + }; + } + return composer; + } + + /** + * Convert to I18n Composer Options from VueI18n Options + * + * @internal + */ + function convertComposerOptions(options) { + const locale = isString(options.locale) ? options.locale : 'en-US'; + const fallbackLocale = isString(options.fallbackLocale) || + isArray(options.fallbackLocale) || + isPlainObject(options.fallbackLocale) || + options.fallbackLocale === false + ? options.fallbackLocale + : locale; + const missing = isFunction(options.missing) ? options.missing : undefined; + const missingWarn = isBoolean(options.silentTranslationWarn) || + isRegExp(options.silentTranslationWarn) + ? !options.silentTranslationWarn + : true; + const fallbackWarn = isBoolean(options.silentFallbackWarn) || + isRegExp(options.silentFallbackWarn) + ? !options.silentFallbackWarn + : true; + const fallbackRoot = isBoolean(options.fallbackRoot) + ? options.fallbackRoot + : true; + const fallbackFormat = !!options.formatFallbackMessages; + const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; + const pluralizationRules = options.pluralizationRules; + const postTranslation = isFunction(options.postTranslation) + ? options.postTranslation + : undefined; + const warnHtmlMessage = isString(options.warnHtmlInMessage) + ? options.warnHtmlInMessage !== 'off' + : true; + const escapeParameter = !!options.escapeParameterHtml; + const inheritLocale = isBoolean(options.sync) ? options.sync : true; + if (options.formatter) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + } + if (options.preserveDirectiveContent) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + } + let messages = options.messages; + if (isPlainObject(options.sharedMessages)) { + const sharedMessages = options.sharedMessages; + const locales = Object.keys(sharedMessages); + messages = locales.reduce((messages, locale) => { + const message = messages[locale] || (messages[locale] = {}); + assign(message, sharedMessages[locale]); + return messages; + }, (messages || {})); + } + const { __i18n, __root } = options; + const datetimeFormats = options.datetimeFormats; + const numberFormats = options.numberFormats; + const flatJson = options.flatJson; + return { + locale, + fallbackLocale, + messages, + flatJson, + datetimeFormats, + numberFormats, + missing, + missingWarn, + fallbackWarn, + fallbackRoot, + fallbackFormat, + modifiers, + pluralRules: pluralizationRules, + postTranslation, + warnHtmlMessage, + escapeParameter, + inheritLocale, + __i18n, + __root + }; + } + /** + * create VueI18n interface factory + * + * @internal + */ + function createVueI18n(options = {}) { + const composer = createComposer(convertComposerOptions(options)); + // defines VueI18n + const vueI18n = { + // id + id: composer.id, + // locale + get locale() { + return composer.locale.value; + }, + set locale(val) { + composer.locale.value = val; + }, + // fallbackLocale + get fallbackLocale() { + return composer.fallbackLocale.value; + }, + set fallbackLocale(val) { + composer.fallbackLocale.value = val; + }, + // messages + get messages() { + return composer.messages.value; + }, + // datetimeFormats + get datetimeFormats() { + return composer.datetimeFormats.value; + }, + // numberFormats + get numberFormats() { + return composer.numberFormats.value; + }, + // availableLocales + get availableLocales() { + return composer.availableLocales; + }, + // formatter + get formatter() { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + // dummy + return { + interpolate() { + return []; + } + }; + }, + set formatter(val) { + warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); + }, + // missing + get missing() { + return composer.getMissingHandler(); + }, + set missing(handler) { + composer.setMissingHandler(handler); + }, + // silentTranslationWarn + get silentTranslationWarn() { + return isBoolean(composer.missingWarn) + ? !composer.missingWarn + : composer.missingWarn; + }, + set silentTranslationWarn(val) { + composer.missingWarn = isBoolean(val) ? !val : val; + }, + // silentFallbackWarn + get silentFallbackWarn() { + return isBoolean(composer.fallbackWarn) + ? !composer.fallbackWarn + : composer.fallbackWarn; + }, + set silentFallbackWarn(val) { + composer.fallbackWarn = isBoolean(val) ? !val : val; + }, + // modifiers + get modifiers() { + return composer.modifiers; + }, + // formatFallbackMessages + get formatFallbackMessages() { + return composer.fallbackFormat; + }, + set formatFallbackMessages(val) { + composer.fallbackFormat = val; + }, + // postTranslation + get postTranslation() { + return composer.getPostTranslationHandler(); + }, + set postTranslation(handler) { + composer.setPostTranslationHandler(handler); + }, + // sync + get sync() { + return composer.inheritLocale; + }, + set sync(val) { + composer.inheritLocale = val; + }, + // warnInHtmlMessage + get warnHtmlInMessage() { + return composer.warnHtmlMessage ? 'warn' : 'off'; + }, + set warnHtmlInMessage(val) { + composer.warnHtmlMessage = val !== 'off'; + }, + // escapeParameterHtml + get escapeParameterHtml() { + return composer.escapeParameter; + }, + set escapeParameterHtml(val) { + composer.escapeParameter = val; + }, + // preserveDirectiveContent + get preserveDirectiveContent() { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + return true; + }, + set preserveDirectiveContent(val) { + warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); + }, + // pluralizationRules + get pluralizationRules() { + return composer.pluralRules || {}; + }, + // for internal + __composer: composer, + // t + t(...args) { + const [arg1, arg2, arg3] = args; + const options = {}; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + rt(...args) { + return composer.rt(...args); + }, + // tc + tc(...args) { + const [arg1, arg2, arg3] = args; + const options = { plural: 1 }; + let list = null; + let named = null; + if (!isString(arg1)) { + throw createI18nError(15 /* INVALID_ARGUMENT */); + } + const key = arg1; + if (isString(arg2)) { + options.locale = arg2; + } + else if (isNumber(arg2)) { + options.plural = arg2; + } + else if (isArray(arg2)) { + list = arg2; + } + else if (isPlainObject(arg2)) { + named = arg2; + } + if (isString(arg3)) { + options.locale = arg3; + } + else if (isArray(arg3)) { + list = arg3; + } + else if (isPlainObject(arg3)) { + named = arg3; + } + return composer.t(key, list || named || {}, options); + }, + // te + te(key, locale) { + return composer.te(key, locale); + }, + // tm + tm(key) { + return composer.tm(key); + }, + // getLocaleMessage + getLocaleMessage(locale) { + return composer.getLocaleMessage(locale); + }, + // setLocaleMessage + setLocaleMessage(locale, message) { + composer.setLocaleMessage(locale, message); + }, + // mergeLocaleMessage + mergeLocaleMessage(locale, message) { + composer.mergeLocaleMessage(locale, message); + }, + // d + d(...args) { + return composer.d(...args); + }, + // getDateTimeFormat + getDateTimeFormat(locale) { + return composer.getDateTimeFormat(locale); + }, + // setDateTimeFormat + setDateTimeFormat(locale, format) { + composer.setDateTimeFormat(locale, format); + }, + // mergeDateTimeFormat + mergeDateTimeFormat(locale, format) { + composer.mergeDateTimeFormat(locale, format); + }, + // n + n(...args) { + return composer.n(...args); + }, + // getNumberFormat + getNumberFormat(locale) { + return composer.getNumberFormat(locale); + }, + // setNumberFormat + setNumberFormat(locale, format) { + composer.setNumberFormat(locale, format); + }, + // mergeNumberFormat + mergeNumberFormat(locale, format) { + composer.mergeNumberFormat(locale, format); + }, + // getChoiceIndex + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getChoiceIndex(choice, choicesLength) { + warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); + return -1; + }, + // for internal + __onComponentInstanceCreated(target) { + const { componentInstanceCreatedListener } = options; + if (componentInstanceCreatedListener) { + componentInstanceCreatedListener(target, vueI18n); + } + } + }; + // for vue-devtools timeline event + { + vueI18n.__enableEmitter = (emitter) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[EnableEmitter] && __composer[EnableEmitter](emitter); + }; + vueI18n.__disableEmitter = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const __composer = composer; + __composer[DisableEmitter] && __composer[DisableEmitter](); + }; + } + return vueI18n; + } + + const baseFormatProps = { + tag: { + type: [String, Object] + }, + locale: { + type: String + }, + scope: { + type: String, + validator: (val) => val === 'parent' || val === 'global', + default: 'parent' + }, + i18n: { + type: Object + } + }; + + /** + * Translation Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [TranslationProps](component#translationprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Component Interpolation](../guide/advanced/component) + * + * @example + * ```html + *
+ * + * + * {{ $t('tos') }} + * + * + *
+ * ``` + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * const messages = { + * en: { + * tos: 'Term of Service', + * term: 'I accept xxx {0}.' + * }, + * ja: { + * tos: '利用規約', + * term: '私は xxx の{0}に同意します。' + * } + * } + * + * const i18n = createI18n({ + * locale: 'en', + * messages + * }) + * + * const app = createApp({ + * data: { + * url: '/term' + * } + * }).use(i18n).mount('#app') + * ``` + * + * @VueI18nComponent + */ + const Translation = { + /* eslint-disable */ + name: 'i18n-t', + props: assign({ + keypath: { + type: String, + required: true + }, + plural: { + type: [Number, String], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + validator: (val) => isNumber(val) || !isNaN(val) + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const { slots, attrs } = context; + const i18n = props.i18n || + useI18n({ useScope: props.scope }); + const keys = Object.keys(slots).filter(key => key !== '_'); + return () => { + const options = {}; + if (props.locale) { + options.locale = props.locale; + } + if (props.plural !== undefined) { + options.plural = isString(props.plural) ? +props.plural : props.plural; + } + const arg = getInterpolateArg(context, keys); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; + } + }; + function getInterpolateArg({ slots }, keys) { + if (keys.length === 1 && keys[0] === 'default') { + // default slot only + return slots.default ? slots.default() : []; + } + else { + // named slots + return keys.reduce((arg, key) => { + const slot = slots[key]; + if (slot) { + arg[key] = slot(); + } + return arg; + }, {}); + } + } + + function renderFormatter(props, context, slotKeys, partFormatter) { + const { slots, attrs } = context; + return () => { + const options = { part: true }; + let overrides = {}; + if (props.locale) { + options.locale = props.locale; + } + if (isString(props.format)) { + options.key = props.format; + } + else if (isObject(props.format)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isString(props.format.key)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options.key = props.format.key; + } + // Filter out number format options only + overrides = Object.keys(props.format).reduce((options, prop) => { + return slotKeys.includes(prop) + ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any + : options; + }, {}); + } + const parts = partFormatter(...[props.value, options, overrides]); + let children = [options.key]; + if (isArray(parts)) { + children = parts.map((part, index) => { + const slot = slots[part.type]; + return slot + ? slot({ [part.type]: part.value, index, parts }) + : [part.value]; + }); + } + else if (isString(parts)) { + children = [parts]; + } + const assignedAttrs = assign({}, attrs); + // prettier-ignore + return isString(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : isObject(props.tag) + ? vue.h(props.tag, assignedAttrs, children) + : vue.h(vue.Fragment, assignedAttrs, children); + }; + } + + const NUMBER_FORMAT_KEYS = [ + 'localeMatcher', + 'style', + 'unit', + 'unitDisplay', + 'currency', + 'currencyDisplay', + 'useGrouping', + 'numberingSystem', + 'minimumIntegerDigits', + 'minimumFractionDigits', + 'maximumFractionDigits', + 'minimumSignificantDigits', + 'maximumSignificantDigits', + 'notation', + 'formatMatcher' + ]; + /** + * Number Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) + * + * @VueI18nComponent + */ + const NumberFormat = { + /* eslint-disable */ + name: 'i18n-n', + props: assign({ + value: { + type: Number, + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[NumberPartsSymbol](...args)); + } + }; + + const DATETIME_FORMAT_KEYS = [ + 'dateStyle', + 'timeStyle', + 'fractionalSecondDigits', + 'calendar', + 'dayPeriod', + 'numberingSystem', + 'localeMatcher', + 'timeZone', + 'hour12', + 'hourCycle', + 'formatMatcher', + 'weekday', + 'era', + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'timeZoneName' + ]; + /** + * Datetime Format Component + * + * @remarks + * See the following items for property about details + * + * @VueI18nSee [FormattableProps](component#formattableprops) + * @VueI18nSee [BaseFormatProps](component#baseformatprops) + * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) + * + * @VueI18nDanger + * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) + * + * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) + * + * @VueI18nComponent + */ + const DatetimeFormat = { + /* eslint-disable */ + name: 'i18n-d', + props: assign({ + value: { + type: [Number, Date], + required: true + }, + format: { + type: [String, Object] + } + }, baseFormatProps), + /* eslint-enable */ + setup(props, context) { + const i18n = props.i18n || + useI18n({ useScope: 'parent' }); + return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n[DatetimePartsSymbol](...args)); + } + }; + + function getComposer$2(i18n, instance) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + return (i18nInternal.__getInstance(instance) || i18n.global); + } + else { + const vueI18n = i18nInternal.__getInstance(instance); + return vueI18n != null + ? vueI18n.__composer + : i18n.global.__composer; + } + } + function vTDirective(i18n) { + const bind = (el, { instance, value, modifiers }) => { + /* istanbul ignore if */ + if (!instance || !instance.$) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const composer = getComposer$2(i18n, instance.$); + if (modifiers.preserve) { + warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); + } + const parsedValue = parseValue(value); + el.textContent = composer.t(...makeParams(parsedValue)); + }; + return { + beforeMount: bind, + beforeUpdate: bind + }; + } + function parseValue(value) { + if (isString(value)) { + return { path: value }; + } + else if (isPlainObject(value)) { + if (!('path' in value)) { + throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); + } + return value; + } + else { + throw createI18nError(20 /* INVALID_VALUE */); + } + } + function makeParams(value) { + const { path, locale, args, choice, plural } = value; + const options = {}; + const named = args || {}; + if (isString(locale)) { + options.locale = locale; + } + if (isNumber(choice)) { + options.plural = choice; + } + if (isNumber(plural)) { + options.plural = plural; + } + return [path, named, options]; + } + + function apply(app, i18n, ...options) { + const pluginOptions = isPlainObject(options[0]) + ? options[0] + : {}; + const useI18nComponentName = !!pluginOptions.useI18nComponentName; + const globalInstall = isBoolean(pluginOptions.globalInstall) + ? pluginOptions.globalInstall + : true; + if (globalInstall && useI18nComponentName) { + warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { + name: Translation.name + })); + } + if (globalInstall) { + // install components + app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); + app.component(NumberFormat.name, NumberFormat); + app.component(DatetimeFormat.name, DatetimeFormat); + } + // install directive + app.directive('t', vTDirective(i18n)); + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + function getDevtoolsGlobalHook() { + return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; + } + function getTarget() { + // @ts-ignore + return typeof navigator !== 'undefined' + ? window + : typeof global$1 !== 'undefined' + ? global$1 + : {}; + } + + const HOOK_SETUP = 'devtools-plugin:setup'; + + 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 + }); + } + } + + 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 + }; + + const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties'; + let devtoolsApi; + async function enableDevTools(app, i18n) { + return new Promise((resolve, reject) => { + try { + setupDevtoolsPlugin({ + id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, + label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], + packageName: 'vue-i18n', + homepage: 'https://vue-i18n.intlify.dev', + logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png', + componentStateTypes: [VUE_I18N_COMPONENT_TYPES], + app + }, api => { + devtoolsApi = api; + api.on.visitComponentTree(({ componentInstance, treeNode }) => { + updateComponentTreeTags(componentInstance, treeNode, i18n); + }); + api.on.inspectComponent(({ componentInstance, instanceData }) => { + if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) { + if (i18n.mode === 'legacy') { + // ignore global scope on legacy mode + if (componentInstance.vnode.el.__VUE_I18N__ !== + i18n.global.__composer) { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + else { + inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__); + } + } + }); + api.addInspector({ + id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, + label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], + icon: 'language', + treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] + }); + api.on.getInspectorTree(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + registerScope(payload, i18n); + } + }); + api.on.getInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + inspectScope(payload, i18n); + } + }); + api.on.editInspectorState(payload => { + if (payload.app === app && + payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { + editScope(payload, i18n); + } + }); + api.addTimelineLayer({ + id: "vue-i18n-timeline" /* TIMELINE */, + label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */], + color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] + }); + resolve(true); + }); + } + catch (e) { + console.error(e); + reject(false); + } + }); + } + function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any + treeNode, i18n) { + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + if (instance && instance.vnode.el.__VUE_I18N__) { + // add custom tags local scope only + if (instance.vnode.el.__VUE_I18N__ !== global) { + const label = instance.type.name || instance.type.displayName || instance.type.__file; + const tag = { + label: `i18n (${label} Scope)`, + textColor: 0x000000, + backgroundColor: 0xffcd19 + }; + treeNode.tags.push(tag); + } + } + } + function inspectComposer(instanceData, composer) { + const type = VUE_I18N_COMPONENT_TYPES; + instanceData.state.push({ + type, + key: 'locale', + editable: true, + value: composer.locale.value + }); + instanceData.state.push({ + type, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }); + instanceData.state.push({ + type, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }); + instanceData.state.push({ + type, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + }); + instanceData.state.push({ + type, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + }); + instanceData.state.push({ + type, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + }); + instanceData.state.push({ + type, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getLocaleMessageValue(messages) { + const value = {}; + Object.keys(messages).forEach((key) => { + const v = messages[key]; + if (isFunction(v) && 'source' in v) { + value[key] = getMessageFunctionDetails(v); + } + else if (isObject(v)) { + value[key] = getLocaleMessageValue(v); + } + else { + value[key] = v; + } + }); + return value; + } + const ESC = { + '<': '<', + '>': '>', + '"': '"', + '&': '&' + }; + function escape(s) { + return s.replace(/[<>"&]/g, escapeChar); + } + function escapeChar(a) { + return ESC[a] || a; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function getMessageFunctionDetails(func) { + const argString = func.source ? `("${escape(func.source)}")` : `(?)`; + return { + _custom: { + type: 'function', + display: `ƒ ${argString}` + } + }; + } + function registerScope(payload, i18n) { + payload.rootNodes.push({ + id: 'global', + label: 'Global Scope' + }); + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + for (const [keyInstance, instance] of i18n.__instances) { + // prettier-ignore + const composer = i18n.mode === 'composition' + ? instance + : instance.__composer; + if (global === composer) { + continue; + } + const label = keyInstance.type.name || + keyInstance.type.displayName || + keyInstance.type.__file; + payload.rootNodes.push({ + id: composer.id.toString(), + label: `${label} Scope` + }); + } + } + function getComposer$1(nodeId, i18n) { + if (nodeId === 'global') { + return i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + } + else { + const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId); + if (instance) { + return i18n.mode === 'composition' + ? instance + : instance.__composer; + } + else { + return null; + } + } + } + function inspectScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + payload.state = makeScopeInspectState(composer); + } + } + function makeScopeInspectState(composer) { + const state = {}; + const localeType = 'Locale related info'; + const localeStates = [ + { + type: localeType, + key: 'locale', + editable: true, + value: composer.locale.value + }, + { + type: localeType, + key: 'fallbackLocale', + editable: true, + value: composer.fallbackLocale.value + }, + { + type: localeType, + key: 'availableLocales', + editable: false, + value: composer.availableLocales + }, + { + type: localeType, + key: 'inheritLocale', + editable: true, + value: composer.inheritLocale + } + ]; + state[localeType] = localeStates; + const localeMessagesType = 'Locale messages info'; + const localeMessagesStates = [ + { + type: localeMessagesType, + key: 'messages', + editable: false, + value: getLocaleMessageValue(composer.messages.value) + } + ]; + state[localeMessagesType] = localeMessagesStates; + const datetimeFormatsType = 'Datetime formats info'; + const datetimeFormatsStates = [ + { + type: datetimeFormatsType, + key: 'datetimeFormats', + editable: false, + value: composer.datetimeFormats.value + } + ]; + state[datetimeFormatsType] = datetimeFormatsStates; + const numberFormatsType = 'Datetime formats info'; + const numberFormatsStates = [ + { + type: numberFormatsType, + key: 'numberFormats', + editable: false, + value: composer.numberFormats.value + } + ]; + state[numberFormatsType] = numberFormatsStates; + return state; + } + function addTimelineEvent(event, payload) { + if (devtoolsApi) { + let groupId; + if (payload && 'groupId' in payload) { + groupId = payload.groupId; + delete payload.groupId; + } + devtoolsApi.addTimelineEvent({ + layerId: "vue-i18n-timeline" /* TIMELINE */, + event: { + title: event, + groupId, + time: Date.now(), + meta: {}, + data: payload || {}, + logType: event === "compile-error" /* COMPILE_ERROR */ + ? 'error' + : event === "fallback" /* FALBACK */ || + event === "missing" /* MISSING */ + ? 'warning' + : 'default' + } + }); + } + } + function editScope(payload, i18n) { + const composer = getComposer$1(payload.nodeId, i18n); + if (composer) { + const [field] = payload.path; + if (field === 'locale' && isString(payload.state.value)) { + composer.locale.value = payload.state.value; + } + else if (field === 'fallbackLocale' && + (isString(payload.state.value) || + isArray(payload.state.value) || + isObject(payload.state.value))) { + composer.fallbackLocale.value = payload.state.value; + } + else if (field === 'inheritLocale' && isBoolean(payload.state.value)) { + composer.inheritLocale = payload.state.value; + } + } + } + + // supports compatibility for legacy vue-i18n APIs + function defineMixin(vuei18n, composer, i18n) { + return { + beforeCreate() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const options = this.$options; + if (options.i18n) { + const optionsI18n = options.i18n; + if (options.__i18n) { + optionsI18n.__i18n = options.__i18n; + } + optionsI18n.__root = composer; + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, optionsI18n); + } + else { + this.$i18n = createVueI18n(optionsI18n); + } + } + else if (options.__i18n) { + if (this === this.$root) { + this.$i18n = mergeToRoot(vuei18n, options); + } + else { + this.$i18n = createVueI18n({ + __i18n: options.__i18n, + __root: composer + }); + } + } + else { + // set global + this.$i18n = vuei18n; + } + vuei18n.__onComponentInstanceCreated(this.$i18n); + i18n.__setInstance(instance, this.$i18n); + // defines vue-i18n legacy APIs + this.$t = (...args) => this.$i18n.t(...args); + this.$rt = (...args) => this.$i18n.rt(...args); + this.$tc = (...args) => this.$i18n.tc(...args); + this.$te = (key, locale) => this.$i18n.te(key, locale); + this.$d = (...args) => this.$i18n.d(...args); + this.$n = (...args) => this.$i18n.n(...args); + this.$tm = (key) => this.$i18n.tm(key); + }, + mounted() { + /* istanbul ignore if */ + { + this.$el.__VUE_I18N__ = this.$i18n.__composer; + const emitter = (this.__v_emitter = createEmitter()); + const _vueI18n = this.$i18n; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + emitter.on('*', addTimelineEvent); + } + }, + beforeUnmount() { + const instance = vue.getCurrentInstance(); + /* istanbul ignore if */ + if (!instance) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + /* istanbul ignore if */ + { + if (this.__v_emitter) { + this.__v_emitter.off('*', addTimelineEvent); + delete this.__v_emitter; + } + const _vueI18n = this.$i18n; + _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); + delete this.$el.__VUE_I18N__; + } + delete this.$t; + delete this.$rt; + delete this.$tc; + delete this.$te; + delete this.$d; + delete this.$n; + delete this.$tm; + i18n.__deleteInstance(instance); + delete this.$i18n; + } + }; + } + function mergeToRoot(root, options) { + root.locale = options.locale || root.locale; + root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; + root.missing = options.missing || root.missing; + root.silentTranslationWarn = + options.silentTranslationWarn || root.silentFallbackWarn; + root.silentFallbackWarn = + options.silentFallbackWarn || root.silentFallbackWarn; + root.formatFallbackMessages = + options.formatFallbackMessages || root.formatFallbackMessages; + root.postTranslation = options.postTranslation || root.postTranslation; + root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; + root.escapeParameterHtml = + options.escapeParameterHtml || root.escapeParameterHtml; + root.sync = options.sync || root.sync; + root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); + const messages = getLocaleMessages(root.locale, { + messages: options.messages, + __i18n: options.__i18n + }); + Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); + if (options.datetimeFormats) { + Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); + } + if (options.numberFormats) { + Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); + } + return root; + } + + /** + * Vue I18n factory + * + * @param options - An options, see the {@link I18nOptions} + * + * @returns {@link I18n} instance + * + * @remarks + * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. + * + * If you use composition API mode, you need to specify {@link ComposerOptions}. + * + * @VueI18nSee [Getting Started](../guide/) + * @VueI18nSee [Composition API](../guide/advanced/composition) + * + * @example + * case: for Legacy API + * ```js + * import { createApp } from 'vue' + * import { createI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * // ... + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @example + * case: for composition API + * ```js + * import { createApp } from 'vue' + * import { createI18n, useI18n } from 'vue-i18n' + * + * // call with I18n option + * const i18n = createI18n({ + * legacy: false, // you must specify 'legacy: false' option + * locale: 'ja', + * messages: { + * en: { ... }, + * ja: { ... } + * } + * }) + * + * const App = { + * setup() { + * // ... + * const { t } = useI18n({ ... }) + * return { ... , t } + * } + * } + * + * const app = createApp(App) + * + * // install! + * app.use(i18n) + * app.mount('#app') + * ``` + * + * @VueI18nGeneral + */ + function createI18n(options = {}) { + // prettier-ignore + const __legacyMode = isBoolean(options.legacy) + ? options.legacy + : true; + const __globalInjection = !!options.globalInjection; + const __instances = new Map(); + // prettier-ignore + const __global = __legacyMode + ? createVueI18n(options) + : createComposer(options); + const symbol = makeSymbol('vue-i18n' ); + const i18n = { + // mode + get mode() { + // prettier-ignore + return __legacyMode + ? 'legacy' + : 'composition' + ; + }, + // install plugin + async install(app, ...options) { + { + app.__VUE_I18N__ = i18n; + } + // setup global provider + app.__VUE_I18N_SYMBOL__ = symbol; + app.provide(app.__VUE_I18N_SYMBOL__, i18n); + // global method and properties injection for Composition API + if (!__legacyMode && __globalInjection) { + injectGlobalFields(app, i18n.global); + } + // install built-in components and directive + { + apply(app, i18n, ...options); + } + // setup mixin for Legacy API + if (__legacyMode) { + app.mixin(defineMixin(__global, __global.__composer, i18n)); + } + // setup vue-devtools plugin + { + const ret = await enableDevTools(app, i18n); + if (!ret) { + throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); + } + const emitter = createEmitter(); + if (__legacyMode) { + const _vueI18n = __global; + _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = __global; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + } + emitter.on('*', addTimelineEvent); + } + }, + // global accessor + get global() { + return __global; + }, + // @internal + __instances, + // @internal + __getInstance(component) { + return __instances.get(component) || null; + }, + // @internal + __setInstance(component, instance) { + __instances.set(component, instance); + }, + // @internal + __deleteInstance(component) { + __instances.delete(component); + } + }; + return i18n; + } + /** + * Use Composition API for Vue I18n + * + * @param options - An options, see {@link UseI18nOptions} + * + * @returns {@link Composer} instance + * + * @remarks + * This function is mainly used by `setup`. + * + * If options are specified, Composer instance is created for each component and you can be localized on the component. + * + * If options are not specified, you can be localized using the global Composer. + * + * @example + * case: Component resource base localization + * ```html + * + * + * + * ``` + * + * @VueI18nComposition + */ + function useI18n(options = {}) { + const instance = vue.getCurrentInstance(); + if (instance == null) { + throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); + } + if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { + throw createI18nError(17 /* NOT_INSLALLED */); + } + const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__); + /* istanbul ignore if */ + if (!i18n) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + // prettier-ignore + const global = i18n.mode === 'composition' + ? i18n.global + : i18n.global.__composer; + // prettier-ignore + const scope = isEmptyObject(options) + ? ('__i18n' in instance.type) + ? 'local' + : 'global' + : !options.useScope + ? 'local' + : options.useScope; + if (scope === 'global') { + let messages = isObject(options.messages) ? options.messages : {}; + if ('__i18nGlobal' in instance.type) { + messages = getLocaleMessages(global.locale.value, { + messages, + __i18n: instance.type.__i18nGlobal + }); + } + // merge locale messages + const locales = Object.keys(messages); + if (locales.length) { + locales.forEach(locale => { + global.mergeLocaleMessage(locale, messages[locale]); + }); + } + // merge datetime formats + if (isObject(options.datetimeFormats)) { + const locales = Object.keys(options.datetimeFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); + }); + } + } + // merge number formats + if (isObject(options.numberFormats)) { + const locales = Object.keys(options.numberFormats); + if (locales.length) { + locales.forEach(locale => { + global.mergeNumberFormat(locale, options.numberFormats[locale]); + }); + } + } + return global; + } + if (scope === 'parent') { + let composer = getComposer(i18n, instance); + if (composer == null) { + { + warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); + } + composer = global; + } + return composer; + } + // scope 'local' case + if (i18n.mode === 'legacy') { + throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); + } + const i18nInternal = i18n; + let composer = i18nInternal.__getInstance(instance); + if (composer == null) { + const type = instance.type; + const composerOptions = assign({}, options); + if (type.__i18n) { + composerOptions.__i18n = type.__i18n; + } + if (global) { + composerOptions.__root = global; + } + composer = createComposer(composerOptions); + setupLifeCycle(i18nInternal, instance, composer); + i18nInternal.__setInstance(instance, composer); + } + return composer; + } + function getComposer(i18n, target) { + let composer = null; + const root = target.root; + let current = target.parent; + while (current != null) { + const i18nInternal = i18n; + if (i18n.mode === 'composition') { + composer = i18nInternal.__getInstance(current); + } + else { + const vueI18n = i18nInternal.__getInstance(current); + if (vueI18n != null) { + composer = vueI18n + .__composer; + } + } + if (composer != null) { + break; + } + if (root === current) { + break; + } + current = current.parent; + } + return composer; + } + function setupLifeCycle(i18n, target, composer) { + let emitter = null; + vue.onMounted(() => { + // inject composer instance to DOM for intlify-devtools + if (target.vnode.el) { + target.vnode.el.__VUE_I18N__ = composer; + emitter = createEmitter(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[EnableEmitter] && _composer[EnableEmitter](emitter); + emitter.on('*', addTimelineEvent); + } + }, target); + vue.onUnmounted(() => { + // remove composer instance from DOM for intlify-devtools + if (target.vnode.el && + target.vnode.el.__VUE_I18N__) { + emitter && emitter.off('*', addTimelineEvent); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const _composer = composer; + _composer[DisableEmitter] && _composer[DisableEmitter](); + delete target.vnode.el.__VUE_I18N__; + } + i18n.__deleteInstance(target); + }, target); + } + const globalExportProps = [ + 'locale', + 'fallbackLocale', + 'availableLocales' + ]; + const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm']; + function injectGlobalFields(app, composer) { + const i18n = Object.create(null); + globalExportProps.forEach(prop => { + const desc = Object.getOwnPropertyDescriptor(composer, prop); + if (!desc) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + const wrap = vue.isRef(desc.value) // check computed props + ? { + get() { + return desc.value.value; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(val) { + desc.value.value = val; + } + } + : { + get() { + return desc.get && desc.get(); + } + }; + Object.defineProperty(i18n, prop, wrap); + }); + app.config.globalProperties.$i18n = i18n; + globalExportMethods.forEach(method => { + const desc = Object.getOwnPropertyDescriptor(composer, method); + if (!desc || !desc.value) { + throw createI18nError(22 /* UNEXPECTED_ERROR */); + } + Object.defineProperty(app.config.globalProperties, `$${method}`, desc); + }); + } + + // NOTE: experimental !! + { + const target = getGlobalThis(); + target.__INTLIFY__ = true; + setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); + } + { + initDev(); + } + + exports.DatetimeFormat = DatetimeFormat; + exports.NumberFormat = NumberFormat; + exports.Translation = Translation; + exports.VERSION = VERSION; + exports.createI18n = createI18n; + exports.useI18n = useI18n; + exports.vTDirective = vTDirective; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +}({}, Vue)); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.prod.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..5279a7dbbb6765adc7dd13160880dc4c744a2b42 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/dist/vue-i18n.runtime.global.prod.js @@ -0,0 +1,6 @@ +/*! + * vue-i18n v9.1.7 + * (c) 2021 kazuya kawaguchi + * Released under the MIT License. + */ +var VueI18n=function(e,t){"use strict";const a="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,n=e=>a?Symbol(e):e,r=e=>JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),l=e=>"number"==typeof e&&isFinite(e),o=e=>"[object RegExp]"===v(e),s=e=>k(e)&&0===Object.keys(e).length;function i(e,t){"undefined"!=typeof console&&(console.warn("[intlify] "+e),t&&console.warn(t.stack))}const c=Object.assign;function u(e){return e.replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const m=Object.prototype.hasOwnProperty;function f(e,t){return m.call(e,t)}const g=Array.isArray,p=e=>"function"==typeof e,b=e=>"string"==typeof e,d=e=>"boolean"==typeof e,_=e=>null!==e&&"object"==typeof e,h=Object.prototype.toString,v=e=>h.call(e),k=e=>"[object Object]"===v(e),F=[];F[0]={w:[0],i:[3,0],"[":[4],o:[7]},F[1]={w:[1],".":[2],"[":[4],o:[7]},F[2]={w:[2],i:[3,0],0:[3,0]},F[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},F[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},F[5]={"'":[4,0],o:8,l:[5,0]},F[6]={'"':[4,0],o:8,l:[6,0]};const y=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function w(e){if(null==e)return"o";switch(e.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return e;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function M(e){const t=e.trim();return("0"!==e.charAt(0)||!isNaN(parseInt(e)))&&(y.test(t)?function(e){const t=e.charCodeAt(0);return t!==e.charCodeAt(e.length-1)||34!==t&&39!==t?e:e.slice(1,-1)}(t):"*"+t)}const L=new Map;function W(e,t){if(!_(e))return null;let a=L.get(t);if(a||(a=function(e){const t=[];let a,n,r,l,o,s,i,c=-1,u=0,m=0;const f=[];function g(){const t=e[c+1];if(5===u&&"'"===t||6===u&&'"'===t)return c++,r="\\"+t,f[0](),!0}for(f[0]=()=>{void 0===n?n=r:n+=r},f[1]=()=>{void 0!==n&&(t.push(n),n=void 0)},f[2]=()=>{f[0](),m++},f[3]=()=>{if(m>0)m--,u=4,f[0]();else{if(m=0,void 0===n)return!1;if(n=M(n),!1===n)return!1;f[1]()}};null!==u;)if(c++,a=e[c],"\\"!==a||!g()){if(l=w(a),i=F[u],o=i[l]||i.l||8,8===o)return;if(u=o[0],void 0!==o[1]&&(s=f[o[1]],s&&(r=a,!1===s())))return;if(7===u)return t}}(t),a&&L.set(t,a)),!a)return null;const n=a.length;let r=e,l=0;for(;le,$=e=>"",S=e=>0===e.length?"":e.join(""),C=e=>null==e?"":g(e)||k(e)&&e.toString===h?JSON.stringify(e,null,2):String(e);function E(e,t){return e=Math.abs(e),2===t?e?e>1?1:0:1:e?Math.min(e,2):0}function O(e={}){const t=e.locale,a=function(e){const t=l(e.pluralIndex)?e.pluralIndex:-1;return e.named&&(l(e.named.count)||l(e.named.n))?l(e.named.count)?e.named.count:l(e.named.n)?e.named.n:t:t}(e),n=_(e.pluralRules)&&b(t)&&p(e.pluralRules[t])?e.pluralRules[t]:E,r=_(e.pluralRules)&&b(t)&&p(e.pluralRules[t])?E:void 0,o=e.list||[],s=e.named||{};l(e.pluralIndex)&&function(e,t){t.count||(t.count=e),t.n||(t.n=e)}(a,s);function i(t){const a=p(e.messages)?e.messages(t):!!_(e.messages)&&e.messages[t];return a||(e.parent?e.parent.message(t):$)}const c=k(e.processor)&&p(e.processor.normalize)?e.processor.normalize:S,u=k(e.processor)&&p(e.processor.interpolate)?e.processor.interpolate:C,m={list:e=>o[e],named:e=>s[e],plural:e=>e[n(a,e.length,r)],linked:(t,a)=>{const n=i(t)(m);return b(a)?(r=a,e.modifiers?e.modifiers[r]:T)(n):n;var r},message:i,type:k(e.processor)&&b(e.processor.type)?e.processor.type:"text",interpolate:u,normalize:c};return m}let N=0;function P(e={}){const t=b(e.version)?e.version:"9.1.7",a=b(e.locale)?e.locale:"en-US",n=g(e.fallbackLocale)||k(e.fallbackLocale)||b(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:a,r=k(e.messages)?e.messages:{[a]:{}},l=k(e.datetimeFormats)?e.datetimeFormats:{[a]:{}},s=k(e.numberFormats)?e.numberFormats:{[a]:{}},u=c({},e.modifiers||{},{upper:e=>b(e)?e.toUpperCase():e,lower:e=>b(e)?e.toLowerCase():e,capitalize:e=>b(e)?`${e.charAt(0).toLocaleUpperCase()}${e.substr(1)}`:e}),m=e.pluralRules||{},f=p(e.missing)?e.missing:null,h=!d(e.missingWarn)&&!o(e.missingWarn)||e.missingWarn,v=!d(e.fallbackWarn)&&!o(e.fallbackWarn)||e.fallbackWarn,F=!!e.fallbackFormat,y=!!e.unresolving,w=p(e.postTranslation)?e.postTranslation:null,M=k(e.processor)?e.processor:null,L=!d(e.warnHtmlMessage)||e.warnHtmlMessage,W=!!e.escapeParameter,I=p(e.messageCompiler)?e.messageCompiler:undefined,T=p(e.onWarn)?e.onWarn:i,$=e,S=_($.__datetimeFormatters)?$.__datetimeFormatters:new Map,C=_($.__numberFormatters)?$.__numberFormatters:new Map,E=_($.__meta)?$.__meta:{};N++;return{version:t,cid:N,locale:a,fallbackLocale:n,messages:r,datetimeFormats:l,numberFormats:s,modifiers:u,pluralRules:m,missing:f,missingWarn:h,fallbackWarn:v,fallbackFormat:F,unresolving:y,postTranslation:w,processor:M,warnHtmlMessage:L,escapeParameter:W,messageCompiler:I,onWarn:T,__datetimeFormatters:S,__numberFormatters:C,__meta:E}}function H(e,t,a,n,r){const{missing:l}=e;if(null!==l){const n=l(e,a,t,r);return b(n)?n:t}return t}function j(e,t,a){const n=e;n.__localeChainCache||(n.__localeChainCache=new Map);let r=n.__localeChainCache.get(a);if(!r){r=[];let e=[a];for(;g(e);)e=R(r,e,t);const l=g(t)?t:k(t)?t.default?t.default:null:t;e=b(l)?[l]:l,g(e)&&R(r,e,!1),n.__localeChainCache.set(a,r)}return r}function R(e,t,a){let n=!0;for(let r=0;r"",z=e=>p(e);function A(e,...t){const{fallbackFormat:a,postTranslation:n,unresolving:r,fallbackLocale:o,messages:s}=e,[i,c]=q(...t),m=(d(c.missingWarn),d(c.fallbackWarn),d(c.escapeParameter)?c.escapeParameter:e.escapeParameter),f=!!c.resolvedMessage,h=b(c.default)||d(c.default)?d(c.default)?i:c.default:a?i:"",v=a||""!==h,k=b(c.locale)?c.locale:e.locale;m&&function(e){g(e.list)?e.list=e.list.map((e=>b(e)?u(e):e)):_(e.named)&&Object.keys(e.named).forEach((t=>{b(e.named[t])&&(e.named[t]=u(e.named[t]))}))}(c);let[F,y,w]=f?[i,k,s[k]||{}]:function(e,t,a,n,r,l){const{messages:o}=e,s=j(e,n,a);let i,c={},u=null;const m="translate";for(let a=0;a{L=!0}));if(L)return F;const T=function(e,t,a){return t(a)}(0,I,O(function(e,t,a,n){const{modifiers:r,pluralRules:o}=e,s={locale:t,modifiers:r,pluralRules:o,messages:n=>{const r=W(a,n);if(b(r)){let a=!1;const l=J(e,n,t,r,n,(()=>{a=!0}));return a?V:l}return z(r)?r:V}};e.processor&&(s.processor=e.processor);n.list&&(s.list=n.list);n.named&&(s.named=n.named);l(n.plural)&&(s.pluralIndex=n.plural);return s}(e,y,w,c)));return n?n(T):T}function J(e,t,a,n,l,o){const{messageCompiler:s,warnHtmlMessage:i}=e;if(z(n)){const e=n;return e.locale=e.locale||a,e.key=e.key||t,e}const c=s(n,function(e,t,a,n,l,o){return{warnHtmlMessage:l,onError:e=>{throw o&&o(e),e},onCacheKey:e=>((e,t,a)=>r({l:e,k:t,s:a}))(t,a,e)}}(0,a,l,0,i,o));return c.locale=a,c.key=t,c.source=n,c}function q(...e){const[t,a,n]=e,r={};if(!b(t)&&!l(t)&&!z(t))throw Error(14);const o=l(t)?String(t):(z(t),t);return l(a)?r.plural=a:b(a)?r.default=a:k(a)&&!s(a)?r.named=a:g(a)&&(r.list=a),l(n)?r.plural=n:b(n)?r.default=n:k(n)&&c(r,n),[o,r]}function B(e,...t){const{datetimeFormats:a,unresolving:n,fallbackLocale:r}=e,{__datetimeFormatters:l}=e,[o,i,u,m]=G(...t);d(u.missingWarn);d(u.fallbackWarn);const f=!!u.part,g=b(u.locale)?u.locale:e.locale,p=j(e,r,g);if(!b(o)||""===o)return new Intl.DateTimeFormat(g).format(i);let _,h={},v=null;for(let t=0;te(n,r,t.getCurrentInstance()||void 0,l)}function oe(e,t){const{messages:a,__i18n:n}=t,r=k(a)?a:g(n)?{}:{[e]:{}};if(g(n)&&n.forEach((({locale:e,resource:t})=>{e?(r[e]=r[e]||{},ie(t,r[e])):ie(t,r)})),t.flatJson)for(const e in r)f(r,e)&&I(r[e]);return r}const se=e=>!_(e)||g(e);function ie(e,t){if(se(e)||se(t))throw Error(20);for(const a in e)f(e,a)&&(se(e[a])||se(t[a])?t[a]=e[a]:ie(e[a],t[a]))}function ce(e={}){const{__root:a}=e,n=void 0===a;let r=!d(e.inheritLocale)||e.inheritLocale;const s=t.ref(a&&r?a.locale.value:b(e.locale)?e.locale:"en-US"),i=t.ref(a&&r?a.fallbackLocale.value:b(e.fallbackLocale)||g(e.fallbackLocale)||k(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:s.value),u=t.ref(oe(s.value,e)),m=t.ref(k(e.datetimeFormats)?e.datetimeFormats:{[s.value]:{}}),f=t.ref(k(e.numberFormats)?e.numberFormats:{[s.value]:{}});let h=a?a.missingWarn:!d(e.missingWarn)&&!o(e.missingWarn)||e.missingWarn,v=a?a.fallbackWarn:!d(e.fallbackWarn)&&!o(e.fallbackWarn)||e.fallbackWarn,F=a?a.fallbackRoot:!d(e.fallbackRoot)||e.fallbackRoot,y=!!e.fallbackFormat,w=p(e.missing)?e.missing:null,M=p(e.missing)?le(e.missing):null,L=p(e.postTranslation)?e.postTranslation:null,I=!d(e.warnHtmlMessage)||e.warnHtmlMessage,T=!!e.escapeParameter;const $=a?a.modifiers:k(e.modifiers)?e.modifiers:{};let S,C=e.pluralRules||a&&a.pluralRules;S=P({version:X,locale:s.value,fallbackLocale:i.value,messages:u.value,datetimeFormats:m.value,numberFormats:f.value,modifiers:$,pluralRules:C,missing:null===M?void 0:M,missingWarn:h,fallbackWarn:v,fallbackFormat:y,unresolving:!0,postTranslation:null===L?void 0:L,warnHtmlMessage:I,escapeParameter:T,__datetimeFormatters:k(S)?S.__datetimeFormatters:void 0,__numberFormatters:k(S)?S.__numberFormatters:void 0,__v_emitter:k(S)?S.__v_emitter:void 0,__meta:{framework:"vue"}}),U(S,s.value,i.value);const E=t.computed({get:()=>s.value,set:e=>{s.value=e,S.locale=s.value}}),O=t.computed({get:()=>i.value,set:e=>{i.value=e,S.fallbackLocale=i.value,U(S,s.value,e)}}),N=t.computed((()=>u.value)),H=t.computed((()=>m.value)),R=t.computed((()=>f.value));function D(e,t,n,r,o,s){let i;if(i=e(S),l(i)&&-1===i){const[e,n]=t();return a&&F?r(a):o(e)}if(s(i))return i;throw Error(14)}function x(...e){return D((t=>A(t,...e)),(()=>q(...e)),0,(t=>t.t(...e)),(e=>e),(e=>b(e)))}const V={normalize:function(e){return e.map((e=>b(e)?t.createVNode(t.Text,null,e,0):e))},interpolate:e=>e,type:"vnode"};function z(e){return u.value[e]||{}}re++,a&&(t.watch(a.locale,(e=>{r&&(s.value=e,S.locale=e,U(S,s.value,i.value))})),t.watch(a.fallbackLocale,(e=>{r&&(i.value=e,S.fallbackLocale=e,U(S,s.value,i.value))})));return{id:re,locale:E,fallbackLocale:O,get inheritLocale(){return r},set inheritLocale(e){r=e,e&&a&&(s.value=a.locale.value,i.value=a.fallbackLocale.value,U(S,s.value,i.value))},get availableLocales(){return Object.keys(u.value).sort()},messages:N,datetimeFormats:H,numberFormats:R,get modifiers(){return $},get pluralRules(){return C||{}},get isGlobal(){return n},get missingWarn(){return h},set missingWarn(e){h=e,S.missingWarn=h},get fallbackWarn(){return v},set fallbackWarn(e){v=e,S.fallbackWarn=v},get fallbackRoot(){return F},set fallbackRoot(e){F=e},get fallbackFormat(){return y},set fallbackFormat(e){y=e,S.fallbackFormat=y},get warnHtmlMessage(){return I},set warnHtmlMessage(e){I=e,S.warnHtmlMessage=e},get escapeParameter(){return T},set escapeParameter(e){T=e,S.escapeParameter=e},t:x,rt:function(...e){const[t,a,n]=e;if(n&&!_(n))throw Error(15);return x(t,a,c({resolvedMessage:!0},n||{}))},d:function(...e){return D((t=>B(t,...e)),(()=>G(...e)),0,(t=>t.d(...e)),(()=>""),(e=>b(e)))},n:function(...e){return D((t=>Z(t,...e)),(()=>K(...e)),0,(t=>t.n(...e)),(()=>""),(e=>b(e)))},te:function(e,t){return null!==W(z(b(t)?t:s.value),e)},tm:function(e){const t=function(e){let t=null;const a=j(S,i.value,s.value);for(let n=0;n{let a;const n=t;try{n.processor=V,a=A(n,...e)}finally{n.processor=null}return a}),(()=>q(...e)),0,(t=>t[ee](...e)),(e=>[t.createVNode(t.Text,null,e,0)]),(e=>g(e)))},[ae]:function(...e){return D((t=>Z(t,...e)),(()=>K(...e)),0,(t=>t[ae](...e)),(()=>[]),(e=>b(e)||g(e)))},[te]:function(...e){return D((t=>B(t,...e)),(()=>G(...e)),0,(t=>t[te](...e)),(()=>[]),(e=>b(e)||g(e)))},[ne]:function(e){C=e,S.pluralRules=C}}}function ue(e={}){const t=ce(function(e){const t=b(e.locale)?e.locale:"en-US",a=b(e.fallbackLocale)||g(e.fallbackLocale)||k(e.fallbackLocale)||!1===e.fallbackLocale?e.fallbackLocale:t,n=p(e.missing)?e.missing:void 0,r=!d(e.silentTranslationWarn)&&!o(e.silentTranslationWarn)||!e.silentTranslationWarn,l=!d(e.silentFallbackWarn)&&!o(e.silentFallbackWarn)||!e.silentFallbackWarn,s=!d(e.fallbackRoot)||e.fallbackRoot,i=!!e.formatFallbackMessages,u=k(e.modifiers)?e.modifiers:{},m=e.pluralizationRules,f=p(e.postTranslation)?e.postTranslation:void 0,_=!b(e.warnHtmlInMessage)||"off"!==e.warnHtmlInMessage,h=!!e.escapeParameterHtml,v=!d(e.sync)||e.sync;let F=e.messages;if(k(e.sharedMessages)){const t=e.sharedMessages;F=Object.keys(t).reduce(((e,a)=>{const n=e[a]||(e[a]={});return c(n,t[a]),e}),F||{})}const{__i18n:y,__root:w}=e;return{locale:t,fallbackLocale:a,messages:F,flatJson:e.flatJson,datetimeFormats:e.datetimeFormats,numberFormats:e.numberFormats,missing:n,missingWarn:r,fallbackWarn:l,fallbackRoot:s,fallbackFormat:i,modifiers:u,pluralRules:m,postTranslation:f,warnHtmlMessage:_,escapeParameter:h,inheritLocale:v,__i18n:y,__root:w}}(e)),a={id:t.id,get locale(){return t.locale.value},set locale(e){t.locale.value=e},get fallbackLocale(){return t.fallbackLocale.value},set fallbackLocale(e){t.fallbackLocale.value=e},get messages(){return t.messages.value},get datetimeFormats(){return t.datetimeFormats.value},get numberFormats(){return t.numberFormats.value},get availableLocales(){return t.availableLocales},get formatter(){return{interpolate:()=>[]}},set formatter(e){},get missing(){return t.getMissingHandler()},set missing(e){t.setMissingHandler(e)},get silentTranslationWarn(){return d(t.missingWarn)?!t.missingWarn:t.missingWarn},set silentTranslationWarn(e){t.missingWarn=d(e)?!e:e},get silentFallbackWarn(){return d(t.fallbackWarn)?!t.fallbackWarn:t.fallbackWarn},set silentFallbackWarn(e){t.fallbackWarn=d(e)?!e:e},get modifiers(){return t.modifiers},get formatFallbackMessages(){return t.fallbackFormat},set formatFallbackMessages(e){t.fallbackFormat=e},get postTranslation(){return t.getPostTranslationHandler()},set postTranslation(e){t.setPostTranslationHandler(e)},get sync(){return t.inheritLocale},set sync(e){t.inheritLocale=e},get warnHtmlInMessage(){return t.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(e){t.warnHtmlMessage="off"!==e},get escapeParameterHtml(){return t.escapeParameter},set escapeParameterHtml(e){t.escapeParameter=e},get preserveDirectiveContent(){return!0},set preserveDirectiveContent(e){},get pluralizationRules(){return t.pluralRules||{}},__composer:t,t(...e){const[a,n,r]=e,l={};let o=null,s=null;if(!b(a))throw Error(15);const i=a;return b(n)?l.locale=n:g(n)?o=n:k(n)&&(s=n),g(r)?o=r:k(r)&&(s=r),t.t(i,o||s||{},l)},rt:(...e)=>t.rt(...e),tc(...e){const[a,n,r]=e,o={plural:1};let s=null,i=null;if(!b(a))throw Error(15);const c=a;return b(n)?o.locale=n:l(n)?o.plural=n:g(n)?s=n:k(n)&&(i=n),b(r)?o.locale=r:g(r)?s=r:k(r)&&(i=r),t.t(c,s||i||{},o)},te:(e,a)=>t.te(e,a),tm:e=>t.tm(e),getLocaleMessage:e=>t.getLocaleMessage(e),setLocaleMessage(e,a){t.setLocaleMessage(e,a)},mergeLocaleMessage(e,a){t.mergeLocaleMessage(e,a)},d:(...e)=>t.d(...e),getDateTimeFormat:e=>t.getDateTimeFormat(e),setDateTimeFormat(e,a){t.setDateTimeFormat(e,a)},mergeDateTimeFormat(e,a){t.mergeDateTimeFormat(e,a)},n:(...e)=>t.n(...e),getNumberFormat:e=>t.getNumberFormat(e),setNumberFormat(e,a){t.setNumberFormat(e,a)},mergeNumberFormat(e,a){t.mergeNumberFormat(e,a)},getChoiceIndex:(e,t)=>-1,__onComponentInstanceCreated(t){const{componentInstanceCreatedListener:n}=e;n&&n(t,a)}};return a}const me={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:e=>"parent"===e||"global"===e,default:"parent"},i18n:{type:Object}},fe={name:"i18n-t",props:c({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:e=>l(e)||!isNaN(e)}},me),setup(e,a){const{slots:n,attrs:r}=a,l=e.i18n||ke({useScope:e.scope}),o=Object.keys(n).filter((e=>"_"!==e));return()=>{const n={};e.locale&&(n.locale=e.locale),void 0!==e.plural&&(n.plural=b(e.plural)?+e.plural:e.plural);const s=function({slots:e},t){return 1===t.length&&"default"===t[0]?e.default?e.default():[]:t.reduce(((t,a)=>{const n=e[a];return n&&(t[a]=n()),t}),{})}(a,o),i=l[ee](e.keypath,s,n),u=c({},r);return b(e.tag)||_(e.tag)?t.h(e.tag,u,i):t.h(t.Fragment,u,i)}}};function ge(e,a,n,r){const{slots:l,attrs:o}=a;return()=>{const a={part:!0};let s={};e.locale&&(a.locale=e.locale),b(e.format)?a.key=e.format:_(e.format)&&(b(e.format.key)&&(a.key=e.format.key),s=Object.keys(e.format).reduce(((t,a)=>n.includes(a)?c({},t,{[a]:e.format[a]}):t),{}));const i=r(e.value,a,s);let u=[a.key];g(i)?u=i.map(((e,t)=>{const a=l[e.type];return a?a({[e.type]:e.value,index:t,parts:i}):[e.value]})):b(i)&&(u=[i]);const m=c({},o);return b(e.tag)||_(e.tag)?t.h(e.tag,m,u):t.h(t.Fragment,m,u)}}const pe=["localeMatcher","style","unit","unitDisplay","currency","currencyDisplay","useGrouping","numberingSystem","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","notation","formatMatcher"],be={name:"i18n-n",props:c({value:{type:Number,required:!0},format:{type:[String,Object]}},me),setup(e,t){const a=e.i18n||ke({useScope:"parent"});return ge(e,t,pe,((...e)=>a[ae](...e)))}},de=["dateStyle","timeStyle","fractionalSecondDigits","calendar","dayPeriod","numberingSystem","localeMatcher","timeZone","hour12","hourCycle","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"],_e={name:"i18n-d",props:c({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},me),setup(e,t){const a=e.i18n||ke({useScope:"parent"});return ge(e,t,de,((...e)=>a[te](...e)))}};function he(e){const t=(t,{instance:a,value:n})=>{if(!a||!a.$)throw Error(22);const r=function(e,t){const a=e;if("composition"===e.mode)return a.__getInstance(t)||e.global;{const n=a.__getInstance(t);return null!=n?n.__composer:e.global.__composer}}(e,a.$),o=function(e){if(b(e))return{path:e};if(k(e)){if(!("path"in e))throw Error(19,"path");return e}throw Error(20)}(n);t.textContent=r.t(...function(e){const{path:t,locale:a,args:n,choice:r,plural:o}=e,s={},i=n||{};b(a)&&(s.locale=a);l(r)&&(s.plural=r);l(o)&&(s.plural=o);return[t,i,s]}(o))};return{beforeMount:t,beforeUpdate:t}}function ve(e,t){e.locale=t.locale||e.locale,e.fallbackLocale=t.fallbackLocale||e.fallbackLocale,e.missing=t.missing||e.missing,e.silentTranslationWarn=t.silentTranslationWarn||e.silentFallbackWarn,e.silentFallbackWarn=t.silentFallbackWarn||e.silentFallbackWarn,e.formatFallbackMessages=t.formatFallbackMessages||e.formatFallbackMessages,e.postTranslation=t.postTranslation||e.postTranslation,e.warnHtmlInMessage=t.warnHtmlInMessage||e.warnHtmlInMessage,e.escapeParameterHtml=t.escapeParameterHtml||e.escapeParameterHtml,e.sync=t.sync||e.sync,e.__composer[ne](t.pluralizationRules||e.pluralizationRules);const a=oe(e.locale,{messages:t.messages,__i18n:t.__i18n});return Object.keys(a).forEach((t=>e.mergeLocaleMessage(t,a[t]))),t.datetimeFormats&&Object.keys(t.datetimeFormats).forEach((a=>e.mergeDateTimeFormat(a,t.datetimeFormats[a]))),t.numberFormats&&Object.keys(t.numberFormats).forEach((a=>e.mergeNumberFormat(a,t.numberFormats[a]))),e}function ke(e={}){const a=t.getCurrentInstance();if(null==a)throw Error(16);if(!a.appContext.app.__VUE_I18N_SYMBOL__)throw Error(17);const n=t.inject(a.appContext.app.__VUE_I18N_SYMBOL__);if(!n)throw Error(22);const r="composition"===n.mode?n.global:n.global.__composer,l=s(e)?"__i18n"in a.type?"local":"global":e.useScope?e.useScope:"local";if("global"===l){let t=_(e.messages)?e.messages:{};"__i18nGlobal"in a.type&&(t=oe(r.locale.value,{messages:t,__i18n:a.type.__i18nGlobal}));const n=Object.keys(t);if(n.length&&n.forEach((e=>{r.mergeLocaleMessage(e,t[e])})),_(e.datetimeFormats)){const t=Object.keys(e.datetimeFormats);t.length&&t.forEach((t=>{r.mergeDateTimeFormat(t,e.datetimeFormats[t])}))}if(_(e.numberFormats)){const t=Object.keys(e.numberFormats);t.length&&t.forEach((t=>{r.mergeNumberFormat(t,e.numberFormats[t])}))}return r}if("parent"===l){let e=function(e,t){let a=null;const n=t.root;let r=t.parent;for(;null!=r;){const t=e;if("composition"===e.mode)a=t.__getInstance(r);else{const e=t.__getInstance(r);null!=e&&(a=e.__composer)}if(null!=a)break;if(n===r)break;r=r.parent}return a}(n,a);return null==e&&(e=r),e}if("legacy"===n.mode)throw Error(18);const o=n;let i=o.__getInstance(a);if(null==i){const n=a.type,l=c({},e);n.__i18n&&(l.__i18n=n.__i18n),r&&(l.__root=r),i=ce(l),function(e,a,n){t.onMounted((()=>{}),a),t.onUnmounted((()=>{e.__deleteInstance(a)}),a)}(o,a),o.__setInstance(a,i)}return i}const Fe=["locale","fallbackLocale","availableLocales"],ye=["t","rt","d","n","tm"];return e.DatetimeFormat=_e,e.NumberFormat=be,e.Translation=fe,e.VERSION=X,e.createI18n=function(e={}){const a=!d(e.legacy)||e.legacy,r=!!e.globalInjection,l=new Map,o=a?ue(e):ce(e),s=n(""),i={get mode(){return a?"legacy":"composition"},async install(e,...n){e.__VUE_I18N_SYMBOL__=s,e.provide(e.__VUE_I18N_SYMBOL__,i),!a&&r&&function(e,a){const n=Object.create(null);Fe.forEach((e=>{const r=Object.getOwnPropertyDescriptor(a,e);if(!r)throw Error(22);const l=t.isRef(r.value)?{get:()=>r.value.value,set(e){r.value.value=e}}:{get:()=>r.get&&r.get()};Object.defineProperty(n,e,l)})),e.config.globalProperties.$i18n=n,ye.forEach((t=>{const n=Object.getOwnPropertyDescriptor(a,t);if(!n||!n.value)throw Error(22);Object.defineProperty(e.config.globalProperties,`$${t}`,n)}))}(e,i.global),function(e,t,...a){const n=k(a[0])?a[0]:{},r=!!n.useI18nComponentName;(!d(n.globalInstall)||n.globalInstall)&&(e.component(r?"i18n":fe.name,fe),e.component(be.name,be),e.component(_e.name,_e)),e.directive("t",he(t))}(e,i,...n),a&&e.mixin(function(e,a,n){return{beforeCreate(){const r=t.getCurrentInstance();if(!r)throw Error(22);const l=this.$options;if(l.i18n){const t=l.i18n;l.__i18n&&(t.__i18n=l.__i18n),t.__root=a,this.$i18n=this===this.$root?ve(e,t):ue(t)}else this.$i18n=l.__i18n?this===this.$root?ve(e,l):ue({__i18n:l.__i18n,__root:a}):e;e.__onComponentInstanceCreated(this.$i18n),n.__setInstance(r,this.$i18n),this.$t=(...e)=>this.$i18n.t(...e),this.$rt=(...e)=>this.$i18n.rt(...e),this.$tc=(...e)=>this.$i18n.tc(...e),this.$te=(e,t)=>this.$i18n.te(e,t),this.$d=(...e)=>this.$i18n.d(...e),this.$n=(...e)=>this.$i18n.n(...e),this.$tm=e=>this.$i18n.tm(e)},mounted(){},beforeUnmount(){const e=t.getCurrentInstance();if(!e)throw Error(22);delete this.$t,delete this.$rt,delete this.$tc,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,n.__deleteInstance(e),delete this.$i18n}}}(o,o.__composer,i))},get global(){return o},__instances:l,__getInstance:e=>l.get(e)||null,__setInstance(e,t){l.set(e,t)},__deleteInstance(e){l.delete(e)}};return i},e.useI18n=ke,e.vTDirective=he,Object.defineProperty(e,"__esModule",{value:!0}),e}({},Vue); diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/index.js b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7a476844c14cc4b24ee639eebdfeab4cf0d0e2a4 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/index.js @@ -0,0 +1,7 @@ +'use strict' + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./dist/vue-i18n.cjs.prod.js') +} else { + module.exports = require('./dist/vue-i18n.cjs.js') +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/package.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/package.json new file mode 100644 index 0000000000000000000000000000000000000000..44e133c14c5edfd15eeae23d4ec9f7ce891436b0 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/package.json @@ -0,0 +1,69 @@ +{ + "name": "vue-i18n", + "version": "9.1.7", + "description": "Internationalization plugin for Vue.js", + "keywords": [ + "i18n", + "internationalization", + "intlify", + "plugin", + "vue", + "vue.js" + ], + "license": "MIT", + "author": { + "name": "kazuya kawaguchi", + "email": "kawakazu80@gmail.com" + }, + "homepage": "https://github.com/intlify/vue-i18n-next/tree/master/packages/vue-i18n#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/intlify/vue-i18n-next.git", + "directory": "packages/vue-i18n" + }, + "bugs": { + "url": "https://github.com/intlify/vue-i18n-next/issues" + }, + "files": [ + "index.js", + "dist", + "vetur" + ], + "main": "index.js", + "module": "dist/vue-i18n.esm-bundler.js", + "unpkg": "dist/vue-i18n.global.js", + "jsdelivr": "dist/vue-i18n.global.js", + "types": "dist/vue-i18n.d.ts", + "dependencies": { + "@intlify/core-base": "9.1.7", + "@intlify/shared": "9.1.7", + "@intlify/vue-devtools": "9.1.7", + "@vue/devtools-api": "^6.0.0-beta.7" + }, + "devDependencies": { + "@intlify/devtools-if": "9.1.7" + }, + "peerDependencies": { + "vue": "^3.0.0" + }, + "engines": { + "node": ">= 10" + }, + "buildOptions": { + "name": "VueI18n", + "formats": [ + "esm-bundler", + "esm-bundler-runtime", + "esm-browser", + "esm-browser-runtime", + "cjs", + "global", + "global-runtime" + ] + }, + "sideEffects": false, + "vetur": { + "tags": "vetur/tags.json", + "attributes": "vetur/attributes.json" + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/attributes.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/attributes.json new file mode 100644 index 0000000000000000000000000000000000000000..54184ae6acdb42331834eb155e9f7d5d9d43ddda --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/attributes.json @@ -0,0 +1,62 @@ +{ + "i18n-t/keypath": { + "description": "[required]\nThe locale message key can be specified prop", + "type": "string" + }, + "i18n-t/plural": { + "description": "[optional]\nThe Plural Choosing the message number prop", + "type": "number|string" + }, + "i18n-t/locale": { + "description": "[optional]\nThe locale to be used for the component", + "type": "string" + }, + "i18n-t/scope": { + "description": "[optional]\tThe scope to be used in the target component.\nYou can specify either `global` or `parent`", + "type": "string" + }, + "i18n-t/tag": { + "description": "[optional]\nUsed to wrap the content that is distribute in the slot.\nIf omitted, the slot content is treated as Fragments", + "type": "string|object" + }, + "i18n-d/value": { + "description": "[required]\nThe value specified for the target component", + "type": "number|date" + }, + "i18n-d/format": { + "description": "[optional]\nThe format to use in the target component", + "type": "string|object" + }, + "i18n-d/locale": { + "description": "[optional]\nThe locale to be used for the component", + "type": "string" + }, + "i18n-d/scope": { + "description": "[optional]\tThe scope to be used in the target component.\nYou can specify either `global` or `parent`", + "type": "string" + }, + "i18n-d/tag": { + "description": "[optional]\nUsed to wrap the content that is distribute in the slot.\nIf omitted, the slot content is treated as Fragments", + "type": "string|object" + }, + "i18n-n/value": { + "description": "[required]\nThe value specified for the target component", + "type": "number" + }, + "i18n-n/format": { + "description": "[optional]\nThe format to use in the target component", + "type": "string|object" + }, + "i18n-n/locale": { + "description": "[optional]\nThe locale to be used for the component", + "type": "string" + }, + "i18n-n/scope": { + "description": "[optional]\tThe scope to be used in the target component.\nYou can specify either `global` or `parent`", + "type": "string" + }, + "i18n-n/tag": { + "description": "[optional]\nUsed to wrap the content that is distribute in the slot.\nIf omitted, the slot content is treated as Fragments", + "type": "string|object" + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/tags.json b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/tags.json new file mode 100644 index 0000000000000000000000000000000000000000..24e16fc16d651721591e148643cb491f04624f96 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/node_modules/vue-i18n/vetur/tags.json @@ -0,0 +1,14 @@ +{ + "i18n-t": { + "attributes": ["keypath", "locale", "tag", "plural", "scope"], + "description": "This is Translation component that can be used when HTML interpolation is needed.\n\nhttps://vue-i18n.intlify.dev/guide/advanced/component.html#basic-usage" + }, + "i18n-d": { + "attributes": ["value", "format", "locale", "tag", "scope"], + "description": "This is Datetime Format component provides a way to use HTML interpolation in pair with number formatting.\n\nhttps://vue-i18n.intlify.dev/guide/essentials/datetime.html#custom-formatting" + }, + "i18n-n": { + "attributes": ["value", "format", "locale", "tag", "scope"], + "description": "This is Number Format component provides a way to use HTML interpolation in pair with number formatting.\n\nhttps://vue-i18n.intlify.dev/guide/essentials/number.html#custom-formatting" + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/package.json b/packages/vue-cli-plugin-uni/packages/vue3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7ebb5ba1851871088691aac2c800d397185e4fe2 --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/package.json @@ -0,0 +1,15 @@ +{ + "name": "vue3", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "vue-i18n": "^9.1.7" + } +} diff --git a/packages/vue-cli-plugin-uni/packages/vue3/yarn.lock b/packages/vue-cli-plugin-uni/packages/vue3/yarn.lock new file mode 100644 index 0000000000000000000000000000000000000000..298dfcb28343e808b36bba7c7eacb45ed730b8df --- /dev/null +++ b/packages/vue-cli-plugin-uni/packages/vue3/yarn.lock @@ -0,0 +1,79 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@intlify/core-base@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/core-base/-/core-base-9.1.7.tgz#a454a492683690bc3d0abab82605ab5a23645bd0" + integrity sha512-q1W2j81xbHyfKrNcca/CeJyf0Bcx4u9UDu05l7AaiJbqOseTme2o2I3wp1hDDCtmC7k7HgX0sAygyHNJH9swuQ== + 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" + +"@intlify/devtools-if@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/devtools-if/-/devtools-if-9.1.7.tgz#a5df0f33e06c3ead3e53b7f4d4b10a2d52309361" + integrity sha512-/DcN5FUySSkQhDqx5y1RvxfuCXO3Ot/dUEIOs472qbM7Hyb2qif+eXCnwHBzlI4+wEfQVT6L0PiM1a7Er/ro9g== + dependencies: + "@intlify/shared" "9.1.7" + +"@intlify/message-compiler@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/message-compiler/-/message-compiler-9.1.7.tgz#4663fcc2a190f3cc6970e12565c8d6f22beeb719" + integrity sha512-JZNkAhr3O7tnbdbRBcpYfqr/Ai26WTzX0K/lV8Y1KVdOIj/dGiamaffdWUdFiDXUnbJRNbPiOaKxy7Pwip3KxQ== + dependencies: + "@intlify/message-resolver" "9.1.7" + "@intlify/shared" "9.1.7" + source-map "0.6.1" + +"@intlify/message-resolver@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/message-resolver/-/message-resolver-9.1.7.tgz#a95d13866c8de85784358039c8845668152e4162" + integrity sha512-WTK+OaXJYjyquLGhuCyDvU2WHkG+kXzXeHagmVFHn+s118Jf2143zzkLLUrapP5CtZ/csuyjmYg7b3xQRQAmvw== + +"@intlify/runtime@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/runtime/-/runtime-9.1.7.tgz#67e0d6b2fd85a5b0b301a151c2f436f93154c3c6" + integrity sha512-QURPSlzhOVnRwS2XMGpCDsDkP42kfVBh94aAORxh/gVGzdgJip2vagrIFij/J69aEqdB476WJkMhVjP8VSHmiA== + dependencies: + "@intlify/message-compiler" "9.1.7" + "@intlify/message-resolver" "9.1.7" + "@intlify/shared" "9.1.7" + +"@intlify/shared@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/shared/-/shared-9.1.7.tgz#e7d8bc90cb59dc17dd7b4c85a73db16fcb7891fc" + integrity sha512-zt0zlUdalumvT9AjQNxPXA36UgOndUyvBMplh8uRZU0fhWHAwhnJTcf0NaG9Qvr8I1n3HPSs96+kLb/YdwTavQ== + +"@intlify/vue-devtools@9.1.7": + version "9.1.7" + resolved "https://registry.yarnpkg.com/@intlify/vue-devtools/-/vue-devtools-9.1.7.tgz#b08d39bb5f21ba9b1954eab9466e9408129425a7" + integrity sha512-DI5Wc0aOiohtBUGUkKAcryCWbbuaO4/PK4Pa/LaNCsFNxbtgR5qkIDmhBv9xVPYGTUhySXxaDDAMvOpBjhPJjw== + dependencies: + "@intlify/message-resolver" "9.1.7" + "@intlify/runtime" "9.1.7" + "@intlify/shared" "9.1.7" + +"@vue/devtools-api@^6.0.0-beta.7": + version "6.0.0-beta.15" + resolved "https://registry.yarnpkg.com/@vue/devtools-api/-/devtools-api-6.0.0-beta.15.tgz#ad7cb384e062f165bcf9c83732125bffbc2ad83d" + integrity sha512-quBx4Jjpexo6KDiNUGFr/zF/2A4srKM9S9v2uHgMXSU//hjgq1eGzqkIFql8T9gfX5ZaVOUzYBP3jIdIR3PKIA== + +source-map@0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== + +vue-i18n@^9.1.7: + version "9.1.7" + resolved "https://registry.yarnpkg.com/vue-i18n/-/vue-i18n-9.1.7.tgz#6f28dd2135197066508e2e65ab204a019750d773" + integrity sha512-ujuuDanoHqtEd4GejWrbG/fXE9nrP51ElsEGxp0WBHfv+/ki0/wyUqkO+4fLikki2obGtXdviTPH0VNpas5K6g== + dependencies: + "@intlify/core-base" "9.1.7" + "@intlify/shared" "9.1.7" + "@intlify/vue-devtools" "9.1.7" + "@vue/devtools-api" "^6.0.0-beta.7" diff --git a/src/platforms/h5/components/page/pageHead.vue b/src/platforms/h5/components/page/pageHead.vue index 635ce06b7e8461b2bca697788b47ea20d9e5008b..3e475622a977953d86d4b96e0d547a2a9fafff05 100644 --- a/src/platforms/h5/components/page/pageHead.vue +++ b/src/platforms/h5/components/page/pageHead.vue @@ -16,23 +16,25 @@ class="uni-btn-icon" > - +
+ +