svelte-i18n
Advanced tools
Comparing version 2.1.0 to 2.1.1
@@ -0,1 +1,5 @@ | ||
## [2.1.1](https://github.com/kaisermann/svelte-i18n/compare/v2.1.0...v2.1.1) (2019-12-02) | ||
# [2.1.0](https://github.com/kaisermann/svelte-i18n/compare/v2.1.0-alpha.2...v2.1.0) (2019-11-30) | ||
@@ -2,0 +6,0 @@ |
#!/usr/bin/env node | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function _interopNamespace(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach((function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})})),t.default=e,t}var fs=_interopDefault(require("fs")),path=require("path"),program=_interopDefault(require("commander")),glob=_interopDefault(require("tiny-glob")),compiler=require("svelte/compiler"),delve=_interopDefault(require("dlv")),estreeWalker=require("estree-walker");const isNumberString=e=>!Number.isNaN(parseInt(e));function deepSet(e,t,r){const i=t.replace(/\[(\w+)\]/gi,".$1").split(".");return i.reduce((e,t,n)=>t in e?e[t]:n<i.length-1?isNumberString(i[n+1])?e[t]=[]:e[t]={}:e[t]=r,e)}function getObjFromExpression(e){return e.properties.reduce((e,t)=>{if("Literal"===t.value.type&&t.value.value!==Object(t.value.value)){const r=t.key.name;e.meta[r]=t.value.value}return e},{node:e,meta:{}})}const LIB_NAME="svelte-i18n",DEFINE_MESSAGES_METHOD_NAME="defineMessages",FORMAT_METHOD_NAMES=new Set(["format","_","t"]),IGNORED_UTILITIES=new Set(["number","date","time"]);function isFormatCall(e,t){if("CallExpression"!==e.type)return!1;let r;if("MemberExpression"!==e.callee.type||"Identifier"!==e.callee.property.type||IGNORED_UTILITIES.has(e.callee.property.name)?"Identifier"===e.callee.type&&(r=e.callee):r=e.callee.object,!r||"Identifier"!==r.type)return!1;const i=r.name.slice(1);return t.has(i)}function isMessagesDefinitionCall(e,t){return"CallExpression"===e.type&&(e.callee&&"Identifier"===e.callee.type&&e.callee.name===t)}function getLibImportDeclarations(e){return e.instance?e.instance.content.body.filter(e=>"ImportDeclaration"===e.type&&e.source.value===LIB_NAME):[]}function getDefineMessagesSpecifier(e){return e.specifiers.find(e=>"imported"in e&&e.imported.name===DEFINE_MESSAGES_METHOD_NAME)}function getFormatSpecifiers(e){return e.specifiers.filter(e=>"imported"in e&&FORMAT_METHOD_NAMES.has(e.imported.name))}function collectFormatCalls(e){const t=getLibImportDeclarations(e);if(0===t.length)return[];const r=new Set(t.flatMap(e=>getFormatSpecifiers(e).map(e=>e.local.name)));if(0===r.size)return[];const i=[];function n(e){isFormatCall(e,r)&&(i.push(e),this.skip())}return estreeWalker.walk(e.instance,{enter:n}),estreeWalker.walk(e.html,{enter:n}),i}function collectMessageDefinitions(e){const t=[],r=getLibImportDeclarations(e).find(getDefineMessagesSpecifier);if(null==r)return[];const i=getDefineMessagesSpecifier(r).local.name;return estreeWalker.walk(e.instance,{enter(e){if(!1===isMessagesDefinitionCall(e,i))return;const[r]=e.arguments;"ObjectExpression"===r.type&&(t.push(r),this.skip())}}),t.flatMap(e=>e.properties.map(e=>e.value))}function collectMessages(e){const t=compiler.parse(e),r=collectFormatCalls(t);return[...collectMessageDefinitions(t).map(e=>getObjFromExpression(e)),...r.map(e=>{const[t,r]=e.arguments;if("ObjectExpression"===t.type)return getObjFromExpression(t);const i=t,n=i.value;if(r&&"ObjectExpression"===r.type){const e=getObjFromExpression(r);return e.meta.id=n,e}return{node:i,meta:{id:n}}})].filter(Boolean)}function extractMessages(e,{accumulator:t={},shallow:r=!1,overwrite:i=!1}={}){return collectMessages(e).forEach(e=>{let n=e.meta.default;if(void 0===n&&(n=""),r){if(!1===i&&e.meta.id in t)return;t[e.meta.id]=n}else{if(!1===i&&void 0!==delve(t,e.meta.id))return;deepSet(t,e.meta.id,n)}}),t}const{readFile:readFile,writeFile:writeFile,mkdir:mkdir,access:access}=fs.promises,fileExists=e=>access(e).then(()=>!0).catch(()=>!1);program.command("extract <glob> [output]").description("extract all message definitions from files to a json").option("-s, --shallow","extract to a shallow dictionary (ids with dots interpreted as strings, not paths)",!1).option("--overwrite","overwrite the content of the output file instead of just appending new properties",!1).option("-c, --config <dir>",'path to the "svelte.config.js" file',process.cwd()).action(async(e,t,{shallow:r,overwrite:i,config:n})=>{const a=(await glob(e)).filter(e=>e.match(/\.html|svelte$/i)),s=await new Promise((function(e){e(_interopNamespace(require(path.resolve(n,"svelte.config.js"))))})).catch(()=>null);let o={};null!=t&&!1===i&&await fileExists(t)&&(o=await readFile(t).then(e=>JSON.parse(e.toString())).catch(e=>{console.warn(e),o={}}));for await(const e of a){let t=(await readFile(e)).toString();if(s&&s.preprocess){t=(await compiler.preprocess(t,s.preprocess,{filename:e})).code}extractMessages(t,{accumulator:o,shallow:r})}const l=JSON.stringify(o,null," ");if(null==t)return console.log(l);await mkdir(path.dirname(t),{recursive:!0}),await writeFile(t,l)}),program.parse(process.argv); | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function _interopNamespace(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach((function(r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})})),t.default=e,t}var fs=_interopDefault(require("fs")),path=require("path"),program=_interopDefault(require("commander")),glob=_interopDefault(require("tiny-glob")),compiler=require("svelte/compiler"),delve=_interopDefault(require("dlv")),estreeWalker=require("estree-walker"); | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
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 | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __asyncValues(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}}const isNumberString=e=>!Number.isNaN(parseInt(e));function deepSet(e,t,r){const n=t.replace(/\[(\w+)\]/gi,".$1").split(".");return n.reduce((e,t,i)=>t in e?e[t]:i<n.length-1?isNumberString(n[i+1])?e[t]=[]:e[t]={}:e[t]=r,e)}function getObjFromExpression(e){return e.properties.reduce((e,t)=>{if("Literal"===t.value.type&&t.value.value!==Object(t.value.value)){const r=t.key.name;e.meta[r]=t.value.value}return e},{node:e,meta:{}})}const LIB_NAME="svelte-i18n",DEFINE_MESSAGES_METHOD_NAME="defineMessages",FORMAT_METHOD_NAMES=new Set(["format","_","t"]),IGNORED_UTILITIES=new Set(["number","date","time"]);function isFormatCall(e,t){if("CallExpression"!==e.type)return!1;let r;if("MemberExpression"!==e.callee.type||"Identifier"!==e.callee.property.type||IGNORED_UTILITIES.has(e.callee.property.name)?"Identifier"===e.callee.type&&(r=e.callee):r=e.callee.object,!r||"Identifier"!==r.type)return!1;const n=r.name.slice(1);return t.has(n)}function isMessagesDefinitionCall(e,t){return"CallExpression"===e.type&&(e.callee&&"Identifier"===e.callee.type&&e.callee.name===t)}function getLibImportDeclarations(e){return e.instance?e.instance.content.body.filter(e=>"ImportDeclaration"===e.type&&e.source.value===LIB_NAME):[]}function getDefineMessagesSpecifier(e){return e.specifiers.find(e=>"imported"in e&&e.imported.name===DEFINE_MESSAGES_METHOD_NAME)}function getFormatSpecifiers(e){return e.specifiers.filter(e=>"imported"in e&&FORMAT_METHOD_NAMES.has(e.imported.name))}function collectFormatCalls(e){const t=getLibImportDeclarations(e);if(0===t.length)return[];const r=new Set(t.flatMap(e=>getFormatSpecifiers(e).map(e=>e.local.name)));if(0===r.size)return[];const n=[];function i(e){isFormatCall(e,r)&&(n.push(e),this.skip())}return estreeWalker.walk(e.instance,{enter:i}),estreeWalker.walk(e.html,{enter:i}),n}function collectMessageDefinitions(e){const t=[],r=getLibImportDeclarations(e).find(getDefineMessagesSpecifier);if(null==r)return[];const n=getDefineMessagesSpecifier(r).local.name;return estreeWalker.walk(e.instance,{enter(e){if(!1===isMessagesDefinitionCall(e,n))return;const[r]=e.arguments;"ObjectExpression"===r.type&&(t.push(r),this.skip())}}),t.flatMap(e=>e.properties.map(e=>e.value))}function collectMessages(e){const t=compiler.parse(e),r=collectFormatCalls(t);return[...collectMessageDefinitions(t).map(e=>getObjFromExpression(e)),...r.map(e=>{const[t,r]=e.arguments;if("ObjectExpression"===t.type)return getObjFromExpression(t);const n=t,i=n.value;if(r&&"ObjectExpression"===r.type){const e=getObjFromExpression(r);return e.meta.id=i,e}return{node:n,meta:{id:i}}})].filter(Boolean)}function extractMessages(e,{accumulator:t={},shallow:r=!1,overwrite:n=!1}={}){return collectMessages(e).forEach(e=>{let i=e.meta.default;if(void 0===i&&(i=""),r){if(!1===n&&e.meta.id in t)return;t[e.meta.id]=i}else{if(!1===n&&void 0!==delve(t,e.meta.id))return;deepSet(t,e.meta.id,i)}}),t}const{readFile:readFile,writeFile:writeFile,mkdir:mkdir,access:access}=fs.promises,fileExists=e=>access(e).then(()=>!0).catch(()=>!1);program.command("extract <glob> [output]").description("extract all message definitions from files to a json").option("-s, --shallow","extract to a shallow dictionary (ids with dots interpreted as strings, not paths)",!1).option("--overwrite","overwrite the content of the output file instead of just appending new properties",!1).option("-c, --config <dir>",'path to the "svelte.config.js" file',process.cwd()).action(async(e,t,{shallow:r,overwrite:n,config:i})=>{var a,o;const s=(await glob(e)).filter(e=>e.match(/\.html|svelte$/i)),l=await new Promise((function(e){e(_interopNamespace(require(path.resolve(i,"svelte.config.js"))))})).catch(()=>null);let c={};null!=t&&!1===n&&await fileExists(t)&&(c=await readFile(t).then(e=>JSON.parse(e.toString())).catch(e=>{console.warn(e),c={}}));try{for(var u,p=__asyncValues(s);!(u=await p.next()).done;){const e=u.value;let t=(await readFile(e)).toString();if(l&&l.preprocess){t=(await compiler.preprocess(t,l.preprocess,{filename:e})).code}extractMessages(t,{accumulator:c,shallow:r})}}catch(e){a={error:e}}finally{try{u&&!u.done&&(o=p.return)&&await o.call(p)}finally{if(a)throw a.error}}const f=JSON.stringify(c,null," ");if(null==t)return console.log(f);await mkdir(path.dirname(t),{recursive:!0}),await writeFile(t,f)}),program.parse(process.argv); |
@@ -1,1 +0,15 @@ | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var store=require("svelte/store"),delve=_interopDefault(require("dlv")),merge=_interopDefault(require("deepmerge")),IntlMessageFormat=_interopDefault(require("intl-messageformat")),memoize=_interopDefault(require("fast-memoize"));let dictionary;const $dictionary=store.writable({});function getLocaleDictionary(e){return dictionary[e]||null}function hasLocaleDictionary(e){return e in dictionary}function getMessageFromDictionary(e,t){if(hasLocaleDictionary(e)){const o=getLocaleDictionary(e);if(t in o)return o[t];const a=delve(o,t);if(a)return a}return null}function getClosestAvailableLocale(e){return null==e||hasLocaleDictionary(e)?e:getClosestAvailableLocale(getFallbackOf(e))}function addMessages(e,...t){$dictionary.update(o=>(dictionary[e]=merge.all([getLocaleDictionary(e)||{}].concat(t)),o))}const $locales=store.derived([$dictionary],([e])=>Object.keys(e));$dictionary.subscribe(e=>dictionary=e);const $isLoading=store.writable(!1);function capital(e){return e.replace(/(^|\s)\S/,e=>e.toLocaleUpperCase())}function title(e){return e.replace(/(^|\s)\S/g,e=>e.toLocaleUpperCase())}function upper(e){return e.toLocaleUpperCase()}function lower(e){return e.toLocaleLowerCase()}const getFromQueryString=(e,t)=>{const o=e.split("&").find(e=>0===e.indexOf(`${t}=`));return o?o.split("=").pop():null},getFirstMatch=(e,t)=>{const o=t.exec(e);return o&&o[1]||null},getClientLocale=({navigator:e,hash:t,search:o,pathname:a,hostname:n})=>{let r;return"undefined"==typeof window?null:n&&(r=getFirstMatch(window.location.hostname,n))?r:a&&(r=getFirstMatch(window.location.pathname,a))?r:e&&(r=window.navigator.language||window.navigator.languages[0])?r:o&&(r=getFromQueryString(window.location.search.substr(1),o))?r:t&&(r=getFromQueryString(window.location.hash.substr(1),t))?r:null},defaultFormats={number:{scientific:{notation:"scientific"},engineering:{notation:"engineering"},compactLong:{notation:"compact",compactDisplay:"long"},compactShort:{notation:"compact",compactDisplay:"short"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},defaultOptions={fallbackLocale:null,initialLocale:null,loadingDelay:200,formats:defaultFormats,warnOnMissingMessages:!0},options=defaultOptions;function getOptions(){return options}function init(e){const{formats:t,...o}=e,a=e.initialLocale?"string"==typeof e.initialLocale?e.initialLocale:getClientLocale(e.initialLocale)||e.fallbackLocale:e.fallbackLocale;return Object.assign(options,o,{initialLocale:a}),t&&("number"in t&&Object.assign(options.formats.number,t.number),"date"in t&&Object.assign(options.formats.date,t.date),"time"in t&&Object.assign(options.formats.time,t.time)),$locale.set(a)}const loaderQueue={};function createLocaleQueue(e){loaderQueue[e]=new Set}function removeLocaleFromQueue(e){delete loaderQueue[e]}function getLocaleQueue(e){return loaderQueue[e]}function getLocalesQueues(e){return getRelatedLocalesOf(e).reverse().map(e=>{const t=getLocaleQueue(e);return[e,t?[...t]:[]]}).filter(([,e])=>e.length>0)}function hasLocaleQueue(e){return getRelatedLocalesOf(e).reverse().some(getLocaleQueue)}const activeLocaleFlushes={};function flush(e){if(!hasLocaleQueue(e))return;if(e in activeLocaleFlushes)return activeLocaleFlushes[e];const t=getLocalesQueues(e);if(0===t.length)return;const o=setTimeout(()=>$isLoading.set(!0),getOptions().loadingDelay);return activeLocaleFlushes[e]=Promise.all(t.map(([e,t])=>Promise.all(t.map(e=>e())).then(t=>{removeLocaleFromQueue(e),t=t.map(e=>e.default||e),addMessages(e,...t)}))).then(()=>{clearTimeout(o),$isLoading.set(!1),delete activeLocaleFlushes[e]}),activeLocaleFlushes[e]}function registerLocaleLoader(e,t){getLocaleQueue(e)||createLocaleQueue(e);const o=getLocaleQueue(e);getLocaleQueue(e).has(t)||(hasLocaleDictionary(e)||$dictionary.update(t=>(t[e]={},t)),o.add(t))}let current;const $locale=store.writable(null);function isFallbackLocaleOf(e,t){return 0===t.indexOf(e)&&e!==t}function isRelatedLocale(e,t){return e===t||isFallbackLocaleOf(e,t)||isFallbackLocaleOf(t,e)}function getFallbackOf(e){const t=e.lastIndexOf("-");if(t>0)return e.slice(0,t);const{fallbackLocale:o}=getOptions();return o&&!isRelatedLocale(e,o)?o:null}function getRelatedLocalesOf(e){const t=e.split("-").map((e,t,o)=>o.slice(0,t+1).join("-")),{fallbackLocale:o}=getOptions();return o&&!isRelatedLocale(e,o)?t.concat(getRelatedLocalesOf(o)):t}function getCurrentLocale(){return current}$locale.subscribe(e=>{current=e,"undefined"!=typeof window&&document.documentElement.setAttribute("lang",e)});const localeSet=$locale.set;$locale.set=e=>getClosestAvailableLocale(e)&&hasLocaleQueue(e)?flush(e).then(()=>localeSet(e)):localeSet(e),$locale.update=e=>localeSet(e(current));const lookupCache={},addToCache=(e,t,o)=>o?(t in lookupCache||(lookupCache[t]={}),e in lookupCache[t]||(lookupCache[t][e]=o),o):o,lookupMessage=(e,t)=>{if(null==t)return null;if(t in lookupCache&&e in lookupCache[t])return lookupCache[t][e];const o=getMessageFromDictionary(t,e);return o||addToCache(e,t,lookupMessage(e,getFallbackOf(t)))},getIntlFormatterOptions=(e,t)=>{const o=getOptions().formats;if(e in o&&t in o[e])return o[e][t];throw new Error(`[svelte-i18n] Unknown "${t}" ${e} format.`)},getNumberFormatter=memoize(({locale:e,format:t,...o}={})=>{if(null==(e=e||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format numbers');return t&&(o=getIntlFormatterOptions("number",t)),new Intl.NumberFormat(e,o)}),getDateFormatter=memoize(({locale:e,format:t,...o}={})=>{if(null==(e=e||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format dates');return t?o=getIntlFormatterOptions("date",t):0===Object.keys(o).length&&(o=getIntlFormatterOptions("date","short")),new Intl.DateTimeFormat(e,o)}),getTimeFormatter=memoize(({locale:e,format:t,...o}={})=>{if(null==(e=e||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format time values');return t?o=getIntlFormatterOptions("time",t):0===Object.keys(o).length&&(o=getIntlFormatterOptions("time","short")),new Intl.DateTimeFormat(e,o)}),getMessageFormatter=memoize((e,t)=>new IntlMessageFormat(e,t,getOptions().formats)),formatMessage=(e,t={})=>{"object"==typeof e&&(e=(t=e).id);const{values:o,locale:a=getCurrentLocale(),default:n}=t;if(null==a)throw new Error("[svelte-i18n] Cannot format a message without first setting the initial locale.");const r=lookupMessage(e,a);return r?o?getMessageFormatter(r,a).format(o):r:(getOptions().warnOnMissingMessages&&console.warn(`[svelte-i18n] The message "${e}" was not found in "${getRelatedLocalesOf(a).join('", "')}".${hasLocaleQueue(getCurrentLocale())?"\n\nNote: there are at least one loader still registered to this locale that wasn't executed.":""}`),n||e)};formatMessage.time=(e,t)=>getTimeFormatter(t).format(e),formatMessage.date=(e,t)=>getDateFormatter(t).format(e),formatMessage.number=(e,t)=>getNumberFormatter(t).format(e),formatMessage.capital=(e,t)=>capital(formatMessage(e,t)),formatMessage.title=(e,t)=>title(formatMessage(e,t)),formatMessage.upper=(e,t)=>upper(formatMessage(e,t)),formatMessage.lower=(e,t)=>lower(formatMessage(e,t));const $format=store.derived([$locale,$dictionary],()=>formatMessage);function defineMessages(e){return e}function waitLocale(e){return flush(e||getCurrentLocale()||getOptions().initialLocale)}exports._=$format,exports.addMessages=addMessages,exports.defineMessages=defineMessages,exports.dictionary=$dictionary,exports.format=$format,exports.init=init,exports.isLoading=$isLoading,exports.locale=$locale,exports.locales=$locales,exports.register=registerLocaleLoader,exports.t=$format,exports.waitLocale=waitLocale; | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var store=require("svelte/store"),delve=_interopDefault(require("dlv")),merge=_interopDefault(require("deepmerge")),IntlMessageFormat=_interopDefault(require("intl-messageformat")),memoize=_interopDefault(require("fast-memoize"));let dictionary;const $dictionary=store.writable({});function getLocaleDictionary(e){return dictionary[e]||null}function hasLocaleDictionary(e){return e in dictionary}function getMessageFromDictionary(e,t){if(hasLocaleDictionary(e)){const o=getLocaleDictionary(e);if(t in o)return o[t];const a=delve(o,t);if(a)return a}return null}function getClosestAvailableLocale(e){return null==e||hasLocaleDictionary(e)?e:getClosestAvailableLocale(getFallbackOf(e))}function addMessages(e,...t){$dictionary.update(o=>(dictionary[e]=merge.all([getLocaleDictionary(e)||{}].concat(t)),o))}const $locales=store.derived([$dictionary],([e])=>Object.keys(e));$dictionary.subscribe(e=>dictionary=e);const $isLoading=store.writable(!1); | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
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 | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */function __rest(e,t){var o={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(o[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(o[a[r]]=e[a[r]])}return o}function capital(e){return e.replace(/(^|\s)\S/,e=>e.toLocaleUpperCase())}function title(e){return e.replace(/(^|\s)\S/g,e=>e.toLocaleUpperCase())}function upper(e){return e.toLocaleUpperCase()}function lower(e){return e.toLocaleLowerCase()}const getFromQueryString=(e,t)=>{const o=e.split("&").find(e=>0===e.indexOf(`${t}=`));return o?o.split("=").pop():null},getFirstMatch=(e,t)=>{const o=t.exec(e);return o&&o[1]||null},getClientLocale=({navigator:e,hash:t,search:o,pathname:a,hostname:r})=>{let n;return"undefined"==typeof window?null:r&&(n=getFirstMatch(window.location.hostname,r))?n:a&&(n=getFirstMatch(window.location.pathname,a))?n:e&&(n=window.navigator.language||window.navigator.languages[0])?n:o&&(n=getFromQueryString(window.location.search.substr(1),o))?n:t&&(n=getFromQueryString(window.location.hash.substr(1),t))?n:null},defaultFormats={number:{scientific:{notation:"scientific"},engineering:{notation:"engineering"},compactLong:{notation:"compact",compactDisplay:"long"},compactShort:{notation:"compact",compactDisplay:"short"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},defaultOptions={fallbackLocale:null,initialLocale:null,loadingDelay:200,formats:defaultFormats,warnOnMissingMessages:!0},options=defaultOptions;function getOptions(){return options}function init(e){const{formats:t}=e,o=__rest(e,["formats"]),a=e.initialLocale?"string"==typeof e.initialLocale?e.initialLocale:getClientLocale(e.initialLocale)||e.fallbackLocale:e.fallbackLocale;return Object.assign(options,o,{initialLocale:a}),t&&("number"in t&&Object.assign(options.formats.number,t.number),"date"in t&&Object.assign(options.formats.date,t.date),"time"in t&&Object.assign(options.formats.time,t.time)),$locale.set(a)}const loaderQueue={};function createLocaleQueue(e){loaderQueue[e]=new Set}function removeLocaleFromQueue(e){delete loaderQueue[e]}function getLocaleQueue(e){return loaderQueue[e]}function getLocalesQueues(e){return getRelatedLocalesOf(e).reverse().map(e=>{const t=getLocaleQueue(e);return[e,t?[...t]:[]]}).filter(([,e])=>e.length>0)}function hasLocaleQueue(e){return getRelatedLocalesOf(e).reverse().some(getLocaleQueue)}const activeLocaleFlushes={};function flush(e){if(!hasLocaleQueue(e))return;if(e in activeLocaleFlushes)return activeLocaleFlushes[e];const t=getLocalesQueues(e);if(0===t.length)return;const o=setTimeout(()=>$isLoading.set(!0),getOptions().loadingDelay);return activeLocaleFlushes[e]=Promise.all(t.map(([e,t])=>Promise.all(t.map(e=>e())).then(t=>{removeLocaleFromQueue(e),t=t.map(e=>e.default||e),addMessages(e,...t)}))).then(()=>{clearTimeout(o),$isLoading.set(!1),delete activeLocaleFlushes[e]}),activeLocaleFlushes[e]}function registerLocaleLoader(e,t){getLocaleQueue(e)||createLocaleQueue(e);const o=getLocaleQueue(e);getLocaleQueue(e).has(t)||(hasLocaleDictionary(e)||$dictionary.update(t=>(t[e]={},t)),o.add(t))}let current;const $locale=store.writable(null);function isFallbackLocaleOf(e,t){return 0===t.indexOf(e)&&e!==t}function isRelatedLocale(e,t){return e===t||isFallbackLocaleOf(e,t)||isFallbackLocaleOf(t,e)}function getFallbackOf(e){const t=e.lastIndexOf("-");if(t>0)return e.slice(0,t);const{fallbackLocale:o}=getOptions();return o&&!isRelatedLocale(e,o)?o:null}function getRelatedLocalesOf(e){const t=e.split("-").map((e,t,o)=>o.slice(0,t+1).join("-")),{fallbackLocale:o}=getOptions();return o&&!isRelatedLocale(e,o)?t.concat(getRelatedLocalesOf(o)):t}function getCurrentLocale(){return current}$locale.subscribe(e=>{current=e,"undefined"!=typeof window&&document.documentElement.setAttribute("lang",e)});const localeSet=$locale.set;$locale.set=e=>getClosestAvailableLocale(e)&&hasLocaleQueue(e)?flush(e).then(()=>localeSet(e)):localeSet(e),$locale.update=e=>localeSet(e(current));const lookupCache={},addToCache=(e,t,o)=>o?(t in lookupCache||(lookupCache[t]={}),e in lookupCache[t]||(lookupCache[t][e]=o),o):o,lookupMessage=(e,t)=>{if(null==t)return null;if(t in lookupCache&&e in lookupCache[t])return lookupCache[t][e];const o=getMessageFromDictionary(t,e);return o||addToCache(e,t,lookupMessage(e,getFallbackOf(t)))},getIntlFormatterOptions=(e,t)=>{const o=getOptions().formats;if(e in o&&t in o[e])return o[e][t];throw new Error(`[svelte-i18n] Unknown "${t}" ${e} format.`)},getNumberFormatter=memoize((e={})=>{var{locale:t,format:o}=e,a=__rest(e,["locale","format"]);if(null==(t=t||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format numbers');return o&&(a=getIntlFormatterOptions("number",o)),new Intl.NumberFormat(t,a)}),getDateFormatter=memoize((e={})=>{var{locale:t,format:o}=e,a=__rest(e,["locale","format"]);if(null==(t=t||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format dates');return o?a=getIntlFormatterOptions("date",o):0===Object.keys(a).length&&(a=getIntlFormatterOptions("date","short")),new Intl.DateTimeFormat(t,a)}),getTimeFormatter=memoize((e={})=>{var{locale:t,format:o}=e,a=__rest(e,["locale","format"]);if(null==(t=t||getCurrentLocale()))throw new Error('[svelte-i18n] A "locale" must be set to format time values');return o?a=getIntlFormatterOptions("time",o):0===Object.keys(a).length&&(a=getIntlFormatterOptions("time","short")),new Intl.DateTimeFormat(t,a)}),getMessageFormatter=memoize((e,t)=>new IntlMessageFormat(e,t,getOptions().formats)),formatMessage=(e,t={})=>{"object"==typeof e&&(e=(t=e).id);const{values:o,locale:a=getCurrentLocale(),default:r}=t;if(null==a)throw new Error("[svelte-i18n] Cannot format a message without first setting the initial locale.");const n=lookupMessage(e,a);return n?o?getMessageFormatter(n,a).format(o):n:(getOptions().warnOnMissingMessages&&console.warn(`[svelte-i18n] The message "${e}" was not found in "${getRelatedLocalesOf(a).join('", "')}".${hasLocaleQueue(getCurrentLocale())?"\n\nNote: there are at least one loader still registered to this locale that wasn't executed.":""}`),r||e)};formatMessage.time=(e,t)=>getTimeFormatter(t).format(e),formatMessage.date=(e,t)=>getDateFormatter(t).format(e),formatMessage.number=(e,t)=>getNumberFormatter(t).format(e),formatMessage.capital=(e,t)=>capital(formatMessage(e,t)),formatMessage.title=(e,t)=>title(formatMessage(e,t)),formatMessage.upper=(e,t)=>upper(formatMessage(e,t)),formatMessage.lower=(e,t)=>lower(formatMessage(e,t));const $format=store.derived([$locale,$dictionary],()=>formatMessage);function defineMessages(e){return e}function waitLocale(e){return flush(e||getCurrentLocale()||getOptions().initialLocale)}exports._=$format,exports.addMessages=addMessages,exports.defineMessages=defineMessages,exports.dictionary=$dictionary,exports.format=$format,exports.init=init,exports.isLoading=$isLoading,exports.locale=$locale,exports.locales=$locales,exports.register=registerLocaleLoader,exports.t=$format,exports.waitLocale=waitLocale; |
{ | ||
"name": "svelte-i18n", | ||
"version": "2.1.0", | ||
"version": "2.1.1", | ||
"main": "dist/i18n.js", | ||
@@ -5,0 +5,0 @@ "module": "dist/i18n.mjs", |
@@ -11,4 +11,4 @@ [![npm version](https://badge.fury.io/js/svelte-i18n.svg)](https://badge.fury.io/js/svelte-i18n) ![](https://github.com/kaisermann/svelte-i18n/workflows/CI/badge.svg) | ||
- Node: `>= 11.15.0` | ||
- Browsers: `Chrome 38+`, `Edge 12+`, `Firefox 13+`, `Opera 25+`, `Safari 8+`. | ||
- Node: `>= 11.15.0` | ||
- Browsers: `Chrome 38+`, `Edge 16+`, `Firefox 13+`, `Opera 25+`, `Safari 8+`. | ||
@@ -32,16 +32,16 @@ ```svelte | ||
{ | ||
"page": { | ||
"home": { | ||
"title": "Homepage", | ||
"nav": "Home" | ||
}, | ||
"about": { | ||
"title": "About", | ||
"nav": "About" | ||
}, | ||
"contact": { | ||
"title": "Contact", | ||
"nav": "Contact Us" | ||
} | ||
} | ||
"page": { | ||
"home": { | ||
"title": "Homepage", | ||
"nav": "Home" | ||
}, | ||
"about": { | ||
"title": "About", | ||
"nav": "About" | ||
}, | ||
"contact": { | ||
"title": "Contact", | ||
"nav": "Contact Us" | ||
} | ||
} | ||
} | ||
@@ -48,0 +48,0 @@ ``` |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
31123
117
1