@vuepress/plugin-redirect 2.0.0-rc.122 → 2.0.0-rc.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/RedirectModal-DopLrY65.d.ts +34 -0
- package/lib/behavior-D5-7wmJ-.d.ts +52 -0
- package/lib/cli/index.d.ts +1 -0
- package/lib/cli/index.js +2 -19
- package/lib/cli/index.js.map +1 -1
- package/lib/client/components/RedirectModal.d.ts +2 -61
- package/lib/client/components/RedirectModal.js +2 -2
- package/lib/client/components/RedirectModal.js.map +1 -1
- package/lib/client/config.d.ts +7 -4
- package/lib/client/config.js +2 -2
- package/lib/client/config.js.map +1 -1
- package/lib/client/index.d.ts +22 -14
- package/lib/client/index.js +1 -2
- package/lib/getRedirectHTML-C9SBJAfB.js +19 -0
- package/lib/getRedirectHTML-C9SBJAfB.js.map +1 -0
- package/lib/locales-CrXL-ZZP.d.ts +36 -0
- package/lib/node/index.d.ts +38 -107
- package/lib/node/index.js +20 -32
- package/lib/node/index.js.map +1 -1
- package/lib/normalizePath-DCapcto5.js +2 -0
- package/lib/normalizePath-DCapcto5.js.map +1 -0
- package/lib/setupRedirect-DB0Ip2i-.js +2 -0
- package/lib/setupRedirect-DB0Ip2i-.js.map +1 -0
- package/lib/useRedirectInfo-BhfN7KrZ.js +2 -0
- package/lib/useRedirectInfo-BhfN7KrZ.js.map +1 -0
- package/package.json +30 -23
- package/lib/client/behavior-BgEQhx7R.d.ts +0 -50
- package/lib/client/index.js.map +0 -1
- package/lib/client/setupRedirect-BBJERz7T.js +0 -2
- package/lib/client/setupRedirect-BBJERz7T.js.map +0 -1
- package/lib/client/useRedirectInfo-BzhIENgm.js +0 -2
- package/lib/client/useRedirectInfo-BzhIENgm.js.map +0 -1
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { t as RedirectBehaviorConfig } from "./behavior-D5-7wmJ-.js";
|
|
2
|
+
import { t as RedirectPluginLocaleData } from "./locales-CrXL-ZZP.js";
|
|
3
|
+
import * as vue from "vue";
|
|
4
|
+
import { PropType, VNode } from "vue";
|
|
5
|
+
import { ExactLocaleConfig } from "@vuepress/helper/client";
|
|
6
|
+
import "@vuepress/helper/transition/fade-in-scale-up.css";
|
|
7
|
+
import "./client/styles/redirect-modal.css";
|
|
8
|
+
|
|
9
|
+
//#region src/client/types.d.ts
|
|
10
|
+
type RedirectPluginLocaleConfig = ExactLocaleConfig<RedirectPluginLocaleData>;
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/client/components/RedirectModal.d.ts
|
|
13
|
+
declare const _default: vue.DefineComponent<vue.ExtractPropTypes<{
|
|
14
|
+
config: {
|
|
15
|
+
type: PropType<RedirectBehaviorConfig>;
|
|
16
|
+
required: true;
|
|
17
|
+
};
|
|
18
|
+
locales: {
|
|
19
|
+
type: PropType<RedirectPluginLocaleConfig>;
|
|
20
|
+
required: true;
|
|
21
|
+
};
|
|
22
|
+
}>, () => VNode | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
|
|
23
|
+
config: {
|
|
24
|
+
type: PropType<RedirectBehaviorConfig>;
|
|
25
|
+
required: true;
|
|
26
|
+
};
|
|
27
|
+
locales: {
|
|
28
|
+
type: PropType<RedirectPluginLocaleConfig>;
|
|
29
|
+
required: true;
|
|
30
|
+
};
|
|
31
|
+
}>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { _default as t };
|
|
34
|
+
//# sourceMappingURL=RedirectModal-DopLrY65.d.ts.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//#region src/shared/behavior.d.ts
|
|
2
|
+
interface RedirectBehaviorOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Whether enable locales redirection
|
|
5
|
+
*
|
|
6
|
+
* 是否启用语言重定向
|
|
7
|
+
*
|
|
8
|
+
* @default false
|
|
9
|
+
*/
|
|
10
|
+
autoLocale?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Whether fallback to other locales user defined
|
|
13
|
+
*
|
|
14
|
+
* 是否回退到用户定义的其他语言
|
|
15
|
+
*
|
|
16
|
+
* @default true
|
|
17
|
+
*/
|
|
18
|
+
localeFallback?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Behavior when a locale version is not available for current link
|
|
21
|
+
*
|
|
22
|
+
* @description `"homepage"` and `"404"` is only available when a locale is assigned to current language
|
|
23
|
+
*
|
|
24
|
+
* 当前链接没有可用的语言版本时的行为
|
|
25
|
+
*
|
|
26
|
+
* @description 只有当语言分配给当前语言时,`"homepage"` 和 `"404"` 才可用
|
|
27
|
+
*
|
|
28
|
+
* @default "defaultLocale"
|
|
29
|
+
*/
|
|
30
|
+
defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
|
|
31
|
+
/**
|
|
32
|
+
* Default locale path
|
|
33
|
+
*
|
|
34
|
+
* @description the first locale will be used if absent
|
|
35
|
+
*
|
|
36
|
+
* 默认语言路径
|
|
37
|
+
*
|
|
38
|
+
* @description 如果缺失,则使用第一个语言
|
|
39
|
+
*/
|
|
40
|
+
defaultLocale?: string;
|
|
41
|
+
}
|
|
42
|
+
interface RedirectBehaviorConfig extends Required<RedirectBehaviorOptions> {
|
|
43
|
+
/**
|
|
44
|
+
* Locale language config
|
|
45
|
+
*
|
|
46
|
+
* 多语言语言配置
|
|
47
|
+
*/
|
|
48
|
+
config: Record<string, string[]>;
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { RedirectBehaviorOptions as n, RedirectBehaviorConfig as t };
|
|
52
|
+
//# sourceMappingURL=behavior-D5-7wmJ-.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/lib/cli/index.js
CHANGED
|
@@ -1,20 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{removeEndingSlash as
|
|
3
|
-
|
|
4
|
-
<head>
|
|
5
|
-
<meta charset="UTF-8">
|
|
6
|
-
<meta name="robots" content="noindex">
|
|
7
|
-
<meta http-equiv="refresh" content="0; url=${e}">
|
|
8
|
-
<link rel="canonical" href="${e}">
|
|
9
|
-
<title>Redirecting...</title>
|
|
10
|
-
<script>
|
|
11
|
-
const anchor = window.location.hash.slice(1);
|
|
12
|
-
window.location.replace(\`${e}\${anchor? \`#\${anchor}\`: ""}\`);
|
|
13
|
-
<\/script>
|
|
14
|
-
</head>
|
|
15
|
-
<body>
|
|
16
|
-
<p>Redirecting...</p>
|
|
17
|
-
</body>
|
|
18
|
-
</html>
|
|
19
|
-
`,i=C("vp-redirect");i.summary("Generate redirect site").description("Generate redirect site for current VuePress project").option("--hostname <hostname>","Hostname to redirect to (E.g.: https://new.example.com/)","/").option("-c, --config [config]","Set path to config file").option("--cache [cache]","Set the directory of the cache files").option("--temp [temp]","Set the directory of the temporary files").option("--clean-cache","Clean the cache files before generation").option("--clean-temp","Clean the temporary files before generation").argument("<source>","Source directory of VuePress project").argument("[output]","Output folder (default: .vuepress/redirect relative to source folder)").action(async(e,s,r)=>{process.env.NODE_ENV??="production",t.existsSync(e)||i.error(`Source directory ${e} does not exist!`);const c=w(e,{}),u=r.config?y(r.config):$(c.source),{userConfig:p}=await S(u),l=b({defaultAppConfig:{cache:r.cache,temp:r.temp},cliAppConfig:c,userConfig:p});if(l===null)return;const o=P(l);o.use(A(p,c.source)),r.cleanTemp===!0&&(n.info("Cleaning temp..."),await t.remove(o.dir.temp())),r.cleanCache===!0&&(n.info("Cleaning cache..."),await t.remove(o.dir.cache()));const m=s?a.join(process.cwd(),s):a.join(o.dir.source(),".vuepress","redirect");await t.emptyDir(m),n.info("Initializing VuePress and preparing data..."),await o.init(),n.info("Generating redirect pages..."),await Promise.all(o.pages.map(f=>{const g=`${v(r.hostname)}${o.siteData.base}${h(f.path)}`,d=a.join(m,h(f.path.replace(/\/$/,"/index.html")));return t.ensureDir(a.dirname(d)).then(()=>t.writeFile(d,E(g)))}))}),i.version(x.version),i.showHelpAfterError("add --help for additional information"),await i.parseAsync();
|
|
20
|
-
//# sourceMappingURL=index.js.map
|
|
2
|
+
import{t as e}from"../getRedirectHTML-C9SBJAfB.js";import{removeEndingSlash as t,removeLeadingSlash as n}from"@vuepress/helper";import{createCommand as r}from"commander";import{loadUserConfig as i,resolveAppConfig as a,resolveCliAppConfig as o,resolveUserConfigConventionalPath as s,resolveUserConfigPath as c,transformUserConfigToPlugin as l}from"vuepress/cli";import{createBuildApp as u}from"vuepress/core";import{fs as d,logger as f,path as p}from"vuepress/utils";var m=`2.0.0-rc.124`;const h=r(`vp-redirect`);h.summary(`Generate redirect site`).description(`Generate redirect site for current VuePress project`).option(`--hostname <hostname>`,`Hostname to redirect to (E.g.: https://new.example.com/)`,`/`).option(`-c, --config [config]`,`Set path to config file`).option(`--cache [cache]`,`Set the directory of the cache files`).option(`--temp [temp]`,`Set the directory of the temporary files`).option(`--clean-cache`,`Clean the cache files before generation`).option(`--clean-temp`,`Clean the temporary files before generation`).argument(`<source>`,`Source directory of VuePress project`).argument(`[output]`,`Output folder (default: .vuepress/redirect relative to source folder)`).action(async(r,m,g)=>{process.env.NODE_ENV??=`production`,d.existsSync(r)||h.error(`Source directory ${r} does not exist!`);let _=o(r,{}),{userConfig:v}=await i(g.config?c(g.config):s(_.source)),y=a({defaultAppConfig:{cache:g.cache,temp:g.temp},cliAppConfig:_,userConfig:v});if(y==null)return;let b=u(y);b.use(l(v,_.source)),g.cleanTemp===!0&&(f.info(`Cleaning temp...`),await d.remove(b.dir.temp())),g.cleanCache===!0&&(f.info(`Cleaning cache...`),await d.remove(b.dir.cache()));let x=m?p.join(process.cwd(),m):p.join(b.dir.source(),`.vuepress`,`redirect`);await d.emptyDir(x),f.info(`Initializing VuePress and preparing data...`),await b.init(),f.info(`Generating redirect pages...`),await Promise.all(b.pages.map(r=>{let i=`${t(g.hostname)}${b.siteData.base}${n(r.path)}`,a=p.join(x,n(r.path.replace(/\/$/,`/index.html`)));return d.ensureDir(p.dirname(a)).then(()=>d.writeFile(a,e(i)))}))}),h.version(m),h.showHelpAfterError(`add --help for additional information`),await h.parseAsync();export{};
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
package/lib/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","
|
|
1
|
+
{"version":3,"file":"index.js","names":["pkg.version"],"sources":["../../package.json","../../src/cli/index.ts"],"sourcesContent":["","#!/usr/bin/env node\nimport { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper'\nimport { createCommand } from 'commander'\nimport {\n loadUserConfig,\n resolveAppConfig,\n resolveCliAppConfig,\n resolveUserConfigConventionalPath,\n resolveUserConfigPath,\n transformUserConfigToPlugin,\n} from 'vuepress/cli'\nimport { createBuildApp } from 'vuepress/core'\nimport { fs, logger, path } from 'vuepress/utils'\nimport pkg from '../../package.json' with { type: 'json' }\nimport { getRedirectHTML } from '../node/generate/getRedirectHTML.js'\n\ninterface RedirectCommandOptions {\n hostname: string\n config?: string\n cache?: string\n temp?: string\n cleanCache?: boolean\n cleanTemp?: boolean\n}\n\nconst program = createCommand('vp-redirect')\n\nprogram\n .summary('Generate redirect site')\n .description('Generate redirect site for current VuePress project')\n .option(\n '--hostname <hostname>',\n 'Hostname to redirect to (E.g.: https://new.example.com/)',\n '/',\n )\n .option('-c, --config [config]', 'Set path to config file')\n .option('--cache [cache]', 'Set the directory of the cache files')\n .option('--temp [temp]', 'Set the directory of the temporary files')\n .option('--clean-cache', 'Clean the cache files before generation')\n .option('--clean-temp', 'Clean the temporary files before generation')\n .argument('<source>', 'Source directory of VuePress project')\n .argument(\n '[output]',\n 'Output folder (default: .vuepress/redirect relative to source folder)',\n )\n .action(\n async (\n sourceDir: string,\n output: string | undefined,\n commandOptions: RedirectCommandOptions,\n ) => {\n // ensure NODE_ENV is set\n process.env.NODE_ENV ??= 'production'\n\n if (!fs.existsSync(sourceDir))\n program.error(`Source directory ${sourceDir} does not exist!`)\n\n // resolve app config from cli options\n const cliAppConfig = resolveCliAppConfig(sourceDir, {})\n\n // resolve user config file\n const userConfigPath = commandOptions.config\n ? resolveUserConfigPath(commandOptions.config)\n : resolveUserConfigConventionalPath(cliAppConfig.source)\n\n const { userConfig } = await loadUserConfig(userConfigPath)\n\n // resolve the final app config to use\n const appConfig = resolveAppConfig({\n defaultAppConfig: {\n cache: commandOptions.cache,\n temp: commandOptions.temp,\n },\n cliAppConfig,\n userConfig,\n })\n\n if (appConfig == null) return\n\n // create vuepress app\n const app = createBuildApp(appConfig)\n\n // use user-config plugin\n app.use(transformUserConfigToPlugin(userConfig, cliAppConfig.source))\n\n // clean temp and cache\n if (commandOptions.cleanTemp === true) {\n logger.info('Cleaning temp...')\n await fs.remove(app.dir.temp())\n }\n if (commandOptions.cleanCache === true) {\n logger.info('Cleaning cache...')\n await fs.remove(app.dir.cache())\n }\n\n const outputFolder = output\n ? path.join(process.cwd(), output)\n : path.join(app.dir.source(), '.vuepress', 'redirect')\n\n // empty output directory\n await fs.emptyDir(outputFolder)\n\n logger.info('Initializing VuePress and preparing data...')\n\n // initialize vuepress app to get pages\n await app.init()\n\n logger.info('Generating redirect pages...')\n\n // redirect all pages\n await Promise.all(\n app.pages.map((page) => {\n const redirectUrl = `${removeEndingSlash(commandOptions.hostname)}${\n app.siteData.base\n }${removeLeadingSlash(page.path)}`\n const destLocation = path.join(\n outputFolder,\n removeLeadingSlash(page.path.replace(/\\/$/, '/index.html')),\n )\n\n return fs\n .ensureDir(path.dirname(destLocation))\n .then(() =>\n fs.writeFile(destLocation, getRedirectHTML(redirectUrl)),\n )\n }),\n )\n },\n )\n\nprogram.version(pkg.version)\nprogram.showHelpAfterError('add --help for additional information')\n\nawait program.parseAsync()\n"],"mappings":";weCyBA,MAAM,EAAU,EAAc,cAAc,CAE5C,EACG,QAAQ,yBAAyB,CACjC,YAAY,sDAAsD,CAClE,OACC,wBACA,2DACA,IACD,CACA,OAAO,wBAAyB,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B,EAAK,KAAK,QAAQ,MAAO,cAAc,CAAC,CAC5D,CAED,OAAO,EACJ,UAAU,EAAK,QAAQ,EAAa,CAAC,CACrC,SACC,EAAG,UAAU,EAAc,EAAgB,EAAY,CAAC,CACzD,EACH,CACH,EAEJ,CAEH,EAAQ,QAAQA,EAAY,CAC5B,EAAQ,mBAAmB,wCAAwC,CAEnE,MAAM,EAAQ,YAAY"}
|
|
@@ -1,61 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import { R as RedirectBehaviorConfig } from '../behavior-BgEQhx7R.js';
|
|
4
|
-
import { ExactLocaleConfig } from '@vuepress/helper/client';
|
|
5
|
-
|
|
6
|
-
interface RedirectPluginLocaleData {
|
|
7
|
-
/**
|
|
8
|
-
* Language name
|
|
9
|
-
*
|
|
10
|
-
* 语言名称
|
|
11
|
-
*/
|
|
12
|
-
name: string;
|
|
13
|
-
/**
|
|
14
|
-
* Switch hint
|
|
15
|
-
*
|
|
16
|
-
* 切换提示
|
|
17
|
-
*/
|
|
18
|
-
hint: string;
|
|
19
|
-
/**
|
|
20
|
-
* Switch button text
|
|
21
|
-
*
|
|
22
|
-
* 切换按钮文字
|
|
23
|
-
*/
|
|
24
|
-
switch: string;
|
|
25
|
-
/**
|
|
26
|
-
* Cancel button text
|
|
27
|
-
*
|
|
28
|
-
* 取消按钮文字
|
|
29
|
-
*/
|
|
30
|
-
cancel: string;
|
|
31
|
-
/**
|
|
32
|
-
* remember hint text
|
|
33
|
-
*
|
|
34
|
-
* 记住提示文本
|
|
35
|
-
*/
|
|
36
|
-
remember: string;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
type RedirectPluginLocaleConfig = ExactLocaleConfig<RedirectPluginLocaleData>;
|
|
40
|
-
|
|
41
|
-
declare const _default: vue.DefineComponent<vue.ExtractPropTypes<{
|
|
42
|
-
config: {
|
|
43
|
-
type: PropType<RedirectBehaviorConfig>;
|
|
44
|
-
required: true;
|
|
45
|
-
};
|
|
46
|
-
locales: {
|
|
47
|
-
type: PropType<RedirectPluginLocaleConfig>;
|
|
48
|
-
required: true;
|
|
49
|
-
};
|
|
50
|
-
}>, () => VNode | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
|
|
51
|
-
config: {
|
|
52
|
-
type: PropType<RedirectBehaviorConfig>;
|
|
53
|
-
required: true;
|
|
54
|
-
};
|
|
55
|
-
locales: {
|
|
56
|
-
type: PropType<RedirectPluginLocaleConfig>;
|
|
57
|
-
required: true;
|
|
58
|
-
};
|
|
59
|
-
}>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
|
|
60
|
-
|
|
61
|
-
export { _default as default };
|
|
1
|
+
import { t as _default } from "../../RedirectModal-DopLrY65.js";
|
|
2
|
+
export { _default as default };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useScrollLock as
|
|
2
|
-
//# sourceMappingURL=RedirectModal.js.map
|
|
1
|
+
import{n as e,r as t,t as n}from"../../useRedirectInfo-BhfN7KrZ.js";import{useScrollLock as r}from"@vueuse/core";import{TransitionGroup as i,computed as a,defineComponent as o,h as s,nextTick as c,onBeforeUnmount as l,onMounted as u,ref as d,watch as f}from"vue";import{useData as p,useRouter as m}from"vuepress/client";import"@vuepress/helper/transition/fade-in-scale-up.css";import"../styles/redirect-modal.css";var h=o({name:`RedirectModal`,props:{config:{type:Object,required:!0},locales:{type:Object,required:!0}},setup(o){let h=m(),{routeLocale:g,routePath:_}=p(),v=n(o.config),y=d(),b=r(y),x=d(!1),S=a(()=>{if(!v.value)return null;let{lang:e,localePath:t}=v.value,n=[o.locales[t],o.locales[g.value]];return{hint:n.map(({hint:t})=>t.replace(`$1`,e)),switch:n.map(({switch:t})=>t.replace(`$1`,e)).join(` / `),cancel:n.map(({cancel:e})=>e).join(` / `),remember:n.map(({remember:e})=>e).join(` / `)}}),C=()=>{t.value[g.value]=!0,x.value&&(e.value[g.value]=!0),b.value=!1};return f(_,()=>{b.value=!1}),u(async()=>{y.value=document.body,await c(),v.value&&!t.value[g.value]&&!e.value[g.value]&&(b.value=!0)}),l(()=>{b.value=!1}),()=>s(i,{name:`fade-in-scale-up`},()=>b.value?s(`div`,{key:`mask`,class:`redirect-modal-mask`},s(`div`,{key:`popup`,class:`redirect-modal-wrapper`},[s(`div`,{class:`redirect-modal-content`},S.value?.hint.map(e=>s(`p`,e))),s(`div`,{class:`redirect-modal-hint`},[s(`input`,{id:`remember-redirect`,type:`checkbox`,value:x.value,onChange:()=>{x.value=!x.value}}),s(`label`,{for:`remember-redirect`},S.value?.remember)]),s(`button`,{type:`button`,class:`redirect-modal-action primary`,onClick:()=>{C(),h.replace(_.value.replace(g.value,v.value.localePath))}},S.value?.switch),s(`button`,{type:`button`,class:`redirect-modal-action`,onClick:()=>{C()}},S.value?.cancel)])):null)}});export{h as default};
|
|
2
|
+
//# sourceMappingURL=RedirectModal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RedirectModal.js","sources":["../../../src/client/components/RedirectModal.ts"],"sourcesContent":["import { useScrollLock } from '@vueuse/core'\nimport type { PropType, VNode } from 'vue'\nimport {\n TransitionGroup,\n computed,\n defineComponent,\n h,\n nextTick,\n onBeforeUnmount,\n onMounted,\n ref,\n watch,\n} from 'vue'\nimport { useData, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { useRedirectInfo } from '../composables/index.js'\nimport type { RedirectPluginLocaleConfig } from '../types.js'\nimport { statusLocalStorage, statusSessionStorage } from '../utils/index.js'\n\nimport '@vuepress/helper/transition/fade-in-scale-up.css'\nimport '../styles/redirect-modal.css'\n\nexport default defineComponent({\n name: 'RedirectModal',\n\n props: {\n config: {\n type: Object as PropType<RedirectBehaviorConfig>,\n required: true,\n },\n\n locales: {\n type: Object as PropType<RedirectPluginLocaleConfig>,\n required: true,\n },\n },\n\n setup(props) {\n const router = useRouter()\n const { routeLocale, routePath } = useData()\n const redirectInfo = useRedirectInfo(props.config)\n\n const body = ref<HTMLElement>()\n // lock body scroll when modal is displayed\n const showModal = useScrollLock(body)\n const shouldRemember = ref(false)\n\n const locale = computed(() => {\n if (!redirectInfo.value) return null\n\n const { lang, localePath } = redirectInfo.value\n const locales = [\n props.locales[localePath],\n props.locales[routeLocale.value],\n ]\n\n return {\n hint: locales.map(({ hint }) => hint.replace('$1', lang)),\n switch: locales\n .map(({ switch: switchText }) => switchText.replace('$1', lang))\n .join(' / '),\n cancel: locales.map(({ cancel }) => cancel).join(' / '),\n remember: locales.map(({ remember }) => remember).join(' / '),\n }\n })\n\n const updateState = (): void => {\n statusSessionStorage.value[routeLocale.value] = true\n if (shouldRemember.value)
|
|
1
|
+
{"version":3,"file":"RedirectModal.js","names":[],"sources":["../../../src/client/components/RedirectModal.ts"],"sourcesContent":["import { useScrollLock } from '@vueuse/core'\nimport type { PropType, VNode } from 'vue'\nimport {\n TransitionGroup,\n computed,\n defineComponent,\n h,\n nextTick,\n onBeforeUnmount,\n onMounted,\n ref,\n watch,\n} from 'vue'\nimport { useData, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { useRedirectInfo } from '../composables/index.js'\nimport type { RedirectPluginLocaleConfig } from '../types.js'\nimport { statusLocalStorage, statusSessionStorage } from '../utils/index.js'\n\nimport '@vuepress/helper/transition/fade-in-scale-up.css'\nimport '../styles/redirect-modal.css'\n\nexport default defineComponent({\n name: 'RedirectModal',\n\n props: {\n config: {\n type: Object as PropType<RedirectBehaviorConfig>,\n required: true,\n },\n\n locales: {\n type: Object as PropType<RedirectPluginLocaleConfig>,\n required: true,\n },\n },\n\n setup(props) {\n const router = useRouter()\n const { routeLocale, routePath } = useData()\n const redirectInfo = useRedirectInfo(props.config)\n\n const body = ref<HTMLElement>()\n // lock body scroll when modal is displayed\n const showModal = useScrollLock(body)\n const shouldRemember = ref(false)\n\n const locale = computed(() => {\n if (!redirectInfo.value) return null\n\n const { lang, localePath } = redirectInfo.value\n const locales = [\n props.locales[localePath],\n props.locales[routeLocale.value],\n ]\n\n return {\n hint: locales.map(({ hint }) => hint.replace('$1', lang)),\n switch: locales\n .map(({ switch: switchText }) => switchText.replace('$1', lang))\n .join(' / '),\n cancel: locales.map(({ cancel }) => cancel).join(' / '),\n remember: locales.map(({ remember }) => remember).join(' / '),\n }\n })\n\n const updateState = (): void => {\n statusSessionStorage.value[routeLocale.value] = true\n if (shouldRemember.value)\n statusLocalStorage.value[routeLocale.value] = true\n\n showModal.value = false\n }\n\n watch(routePath, () => {\n showModal.value = false\n })\n\n onMounted(async () => {\n body.value = document.body\n\n await nextTick()\n\n if (\n redirectInfo.value &&\n !statusSessionStorage.value[routeLocale.value] &&\n !statusLocalStorage.value[routeLocale.value]\n )\n showModal.value = true\n })\n\n onBeforeUnmount(() => {\n showModal.value = false\n })\n\n return (): VNode | null =>\n h(TransitionGroup, { name: 'fade-in-scale-up' }, () =>\n showModal.value\n ? h(\n 'div',\n { key: 'mask', class: 'redirect-modal-mask' },\n h(\n 'div',\n {\n key: 'popup',\n class: 'redirect-modal-wrapper',\n },\n [\n h(\n 'div',\n { class: 'redirect-modal-content' },\n locale.value?.hint.map((text) => h('p', text)),\n ),\n h('div', { class: 'redirect-modal-hint' }, [\n h('input', {\n id: 'remember-redirect',\n type: 'checkbox',\n value: shouldRemember.value,\n onChange: () => {\n shouldRemember.value = !shouldRemember.value\n },\n }),\n h(\n 'label',\n { for: 'remember-redirect' },\n locale.value?.remember,\n ),\n ]),\n h(\n 'button',\n {\n type: 'button',\n class: 'redirect-modal-action primary',\n onClick: () => {\n updateState()\n void router.replace(\n routePath.value.replace(\n routeLocale.value,\n redirectInfo.value!.localePath,\n ),\n )\n },\n },\n locale.value?.switch,\n ),\n h(\n 'button',\n {\n type: 'button',\n class: 'redirect-modal-action',\n onClick: () => {\n updateState()\n },\n },\n locale.value?.cancel,\n ),\n ],\n ),\n )\n : null,\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IAAK,OAAQ,MAAO,sBAAuB,CAC7C,EACE,MACA,CACE,IAAK,QACL,MAAO,yBACR,CACD,CACE,EACE,MACA,CAAE,MAAO,yBAA0B,CACnC,EAAO,OAAO,KAAK,IAAK,GAAS,EAAE,IAAK,EAAK,CAAC,CAC/C,CACD,EAAE,MAAO,CAAE,MAAO,sBAAuB,CAAE,CACzC,EAAE,QAAS,CACT,GAAI,oBACJ,KAAM,WACN,MAAO,EAAe,MACtB,aAAgB,CACd,EAAe,MAAQ,CAAC,EAAe,OAE1C,CAAC,CACF,EACE,QACA,CAAE,IAAK,oBAAqB,CAC5B,EAAO,OAAO,SACf,CACF,CAAC,CACF,EACE,SACA,CACE,KAAM,SACN,MAAO,gCACP,YAAe,CACb,GAAa,CACR,EAAO,QACV,EAAU,MAAM,QACd,EAAY,MACZ,EAAa,MAAO,WACrB,CACF,EAEJ,CACD,EAAO,OAAO,OACf,CACD,EACE,SACA,CACE,KAAM,SACN,MAAO,wBACP,YAAe,CACb,GAAa,EAEhB,CACD,EAAO,OAAO,OACf,CACF,CACF,CACF,CACD,KACL,EAEN,CAAC"}
|
package/lib/client/config.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import { t as RedirectBehaviorConfig } from "../behavior-D5-7wmJ-.js";
|
|
2
|
+
import * as vuepress_client0 from "vuepress/client";
|
|
3
|
+
import "./styles/vars.css";
|
|
3
4
|
|
|
5
|
+
//#region src/client/config.d.ts
|
|
4
6
|
declare const config: RedirectBehaviorConfig;
|
|
5
|
-
declare const _default:
|
|
6
|
-
|
|
7
|
+
declare const _default: vuepress_client0.ClientConfig;
|
|
8
|
+
//#endregion
|
|
7
9
|
export { config, _default as default };
|
|
10
|
+
//# sourceMappingURL=config.d.ts.map
|
package/lib/client/config.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
//# sourceMappingURL=config.js.map
|
|
1
|
+
import{n as e,t}from"../setupRedirect-DB0Ip2i-.js";import{h as n}from"vue";import{defineClientConfig as r}from"vuepress/client";import i from"@vuepress/plugin-redirect/modal";import"./styles/vars.css";const a=__REDIRECT_CONFIG__;var o=r({setup(){__REDIRECT_DIRECT__&&t(a),__VUEPRESS_DEV__&&e(a)},...__REDIRECT_MODAL__?{rootComponents:[()=>n(i,{config:a,locales:__REDIRECT_LOCALES__})]}:{}});export{a as config,o as default};
|
|
2
|
+
//# sourceMappingURL=config.js.map
|
package/lib/client/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sources":["../../src/client/config.ts"],"sourcesContent":["import RedirectModal from '@vuepress/plugin-redirect/modal'\nimport { h } from 'vue'\nimport { defineClientConfig } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { setupDevServerRedirect, setupRedirect } from './composables/index.js'\nimport type { RedirectPluginLocaleConfig } from './types.js'\n\nimport './styles/vars.css'\n\ndeclare const __REDIRECT_CONFIG__: RedirectBehaviorConfig\ndeclare const __REDIRECT_LOCALES__: RedirectPluginLocaleConfig\ndeclare const __REDIRECT_DIRECT__: boolean\ndeclare const __REDIRECT_MODAL__: boolean\n\nexport const config = __REDIRECT_CONFIG__\n\nexport default defineClientConfig({\n setup() {\n if (__REDIRECT_DIRECT__) setupRedirect(config)\n if (__VUEPRESS_DEV__) setupDevServerRedirect(config)\n },\n ...(__REDIRECT_MODAL__\n ? {\n rootComponents: [\n () =>\n h(RedirectModal, {\n config,\n locales: __REDIRECT_LOCALES__,\n }),\n ],\n }\n : {}),\n})\n"],"
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../src/client/config.ts"],"sourcesContent":["import RedirectModal from '@vuepress/plugin-redirect/modal'\nimport { h } from 'vue'\nimport type { VNode } from 'vue'\nimport { defineClientConfig } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { setupDevServerRedirect, setupRedirect } from './composables/index.js'\nimport type { RedirectPluginLocaleConfig } from './types.js'\n\nimport './styles/vars.css'\n\ndeclare const __REDIRECT_CONFIG__: RedirectBehaviorConfig\ndeclare const __REDIRECT_LOCALES__: RedirectPluginLocaleConfig\ndeclare const __REDIRECT_DIRECT__: boolean\ndeclare const __REDIRECT_MODAL__: boolean\n\nexport const config = __REDIRECT_CONFIG__\n\nexport default defineClientConfig({\n setup() {\n if (__REDIRECT_DIRECT__) setupRedirect(config)\n if (__VUEPRESS_DEV__) setupDevServerRedirect(config)\n },\n ...(__REDIRECT_MODAL__\n ? {\n rootComponents: [\n (): VNode =>\n h(RedirectModal, {\n config,\n locales: __REDIRECT_LOCALES__,\n }),\n ],\n }\n : {}),\n})\n"],"mappings":"yMAeA,MAAa,EAAS,oBAEtB,IAAA,EAAe,EAAmB,CAChC,OAAQ,CACF,qBAAqB,EAAc,EAAO,CAC1C,kBAAkB,EAAuB,EAAO,EAEtD,GAAI,mBACA,CACE,eAAgB,KAEZ,EAAE,EAAe,CACf,SACA,QAAS,qBACV,CAAC,CACL,CACF,CACD,EAAE,CACP,CAAC"}
|
package/lib/client/index.d.ts
CHANGED
|
@@ -1,21 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { ComputedRef } from
|
|
4
|
-
import '@vuepress/helper/client';
|
|
5
|
-
|
|
6
|
-
declare const setupDevServerRedirect: ({ autoLocale, config, defaultBehavior, defaultLocale: defaultLocalePath, localeFallback, }: RedirectBehaviorConfig) => void;
|
|
1
|
+
import { t as RedirectBehaviorConfig } from "../behavior-D5-7wmJ-.js";
|
|
2
|
+
import { t as _default } from "../RedirectModal-DopLrY65.js";
|
|
3
|
+
import { ComputedRef } from "vue";
|
|
7
4
|
|
|
5
|
+
//#region src/client/composables/setupDevServerRedirect.d.ts
|
|
6
|
+
declare const setupDevServerRedirect: ({
|
|
7
|
+
autoLocale,
|
|
8
|
+
config,
|
|
9
|
+
defaultBehavior,
|
|
10
|
+
defaultLocale: defaultLocalePath,
|
|
11
|
+
localeFallback
|
|
12
|
+
}: RedirectBehaviorConfig) => void;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/client/composables/setupRedirect.d.ts
|
|
8
15
|
interface LocaleInfo {
|
|
9
|
-
|
|
10
|
-
|
|
16
|
+
lang: string;
|
|
17
|
+
localePath: string;
|
|
11
18
|
}
|
|
12
19
|
declare const setupRedirect: (behaviorConfig: RedirectBehaviorConfig) => void;
|
|
13
|
-
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/client/composables/useRedirectInfo.d.ts
|
|
14
22
|
interface RedirectInfo {
|
|
15
|
-
|
|
16
|
-
|
|
23
|
+
lang: string;
|
|
24
|
+
localePath: string;
|
|
17
25
|
}
|
|
18
26
|
declare const useRedirectInfo: (behaviorConfig: RedirectBehaviorConfig) => ComputedRef<RedirectInfo | null>;
|
|
19
|
-
|
|
20
|
-
export { setupDevServerRedirect, setupRedirect, useRedirectInfo };
|
|
21
|
-
|
|
27
|
+
//#endregion
|
|
28
|
+
export { LocaleInfo, RedirectInfo, _default as RedirectModal, setupDevServerRedirect, setupRedirect, useRedirectInfo };
|
|
29
|
+
//# sourceMappingURL=index.d.ts.map
|
package/lib/client/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
import{n as e,t}from"../setupRedirect-DB0Ip2i-.js";import{t as n}from"../useRedirectInfo-BhfN7KrZ.js";import r from"./components/RedirectModal.js";export{r as RedirectModal,e as setupDevServerRedirect,t as setupRedirect,n as useRedirectInfo};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const e=e=>`<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="robots" content="noindex">
|
|
6
|
+
<meta http-equiv="refresh" content="0; url=${e}">
|
|
7
|
+
<link rel="canonical" href="${e}">
|
|
8
|
+
<title>Redirecting...</title>
|
|
9
|
+
<script>
|
|
10
|
+
const anchor = window.location.hash.slice(1);
|
|
11
|
+
window.location.replace(\`${e}\${anchor? \`#\${anchor}\`: ""}\`);
|
|
12
|
+
<\/script>
|
|
13
|
+
</head>
|
|
14
|
+
<body>
|
|
15
|
+
<p>Redirecting...</p>
|
|
16
|
+
</body>
|
|
17
|
+
</html>
|
|
18
|
+
`;export{e as t};
|
|
19
|
+
//# sourceMappingURL=getRedirectHTML-C9SBJAfB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getRedirectHTML-C9SBJAfB.js","names":[],"sources":["../src/node/generate/getRedirectHTML.ts"],"sourcesContent":["export const getRedirectHTML = (redirectUrl: string): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <meta http-equiv=\"refresh\" content=\"0; url=${redirectUrl}\">\n <link rel=\"canonical\" href=\"${redirectUrl}\">\n <title>Redirecting...</title>\n <script>\n const anchor = window.location.hash.slice(1);\n window.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n"],"mappings":"AAAA,MAAa,EAAmB,GAAgC;;;;;+CAKjB,EAAY;gCAC3B,EAAY;;;;gCAIZ,EAAY"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/shared/locales.d.ts
|
|
2
|
+
interface RedirectPluginLocaleData {
|
|
3
|
+
/**
|
|
4
|
+
* Language name
|
|
5
|
+
*
|
|
6
|
+
* 语言名称
|
|
7
|
+
*/
|
|
8
|
+
name: string;
|
|
9
|
+
/**
|
|
10
|
+
* Switch hint
|
|
11
|
+
*
|
|
12
|
+
* 切换提示
|
|
13
|
+
*/
|
|
14
|
+
hint: string;
|
|
15
|
+
/**
|
|
16
|
+
* Switch button text
|
|
17
|
+
*
|
|
18
|
+
* 切换按钮文字
|
|
19
|
+
*/
|
|
20
|
+
switch: string;
|
|
21
|
+
/**
|
|
22
|
+
* Cancel button text
|
|
23
|
+
*
|
|
24
|
+
* 取消按钮文字
|
|
25
|
+
*/
|
|
26
|
+
cancel: string;
|
|
27
|
+
/**
|
|
28
|
+
* remember hint text
|
|
29
|
+
*
|
|
30
|
+
* 记住提示文本
|
|
31
|
+
*/
|
|
32
|
+
remember: string;
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
export { RedirectPluginLocaleData as t };
|
|
36
|
+
//# sourceMappingURL=locales-CrXL-ZZP.d.ts.map
|
package/lib/node/index.d.ts
CHANGED
|
@@ -1,113 +1,44 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { n as RedirectBehaviorOptions } from "../behavior-D5-7wmJ-.js";
|
|
2
|
+
import { t as RedirectPluginLocaleData } from "../locales-CrXL-ZZP.js";
|
|
3
|
+
import { App, LocaleConfig, PluginFunction } from "vuepress/core";
|
|
4
|
+
import { PageFrontmatter } from "vuepress";
|
|
3
5
|
|
|
6
|
+
//#region src/node/types/frontmatter.d.ts
|
|
4
7
|
interface RedirectPluginFrontmatter extends PageFrontmatter {
|
|
5
|
-
|
|
6
|
-
|
|
8
|
+
redirectFrom?: string[] | string;
|
|
9
|
+
redirectTo?: string;
|
|
7
10
|
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Whether enable locales redirection
|
|
12
|
-
*
|
|
13
|
-
* 是否启用语言重定向
|
|
14
|
-
*
|
|
15
|
-
* @default false
|
|
16
|
-
*/
|
|
17
|
-
autoLocale?: boolean;
|
|
18
|
-
/**
|
|
19
|
-
* Whether fallback to other locales user defined
|
|
20
|
-
*
|
|
21
|
-
* 是否回退到用户定义的其他语言
|
|
22
|
-
*
|
|
23
|
-
* @default true
|
|
24
|
-
*/
|
|
25
|
-
localeFallback?: boolean;
|
|
26
|
-
/**
|
|
27
|
-
* Behavior when a locale version is not available for current link
|
|
28
|
-
*
|
|
29
|
-
* @description `"homepage"` and `"404"` is only available when a locale is assigned to current language
|
|
30
|
-
*
|
|
31
|
-
* 当前链接没有可用的语言版本时的行为
|
|
32
|
-
*
|
|
33
|
-
* @description 只有当语言分配给当前语言时,`"homepage"` 和 `"404"` 才可用
|
|
34
|
-
*
|
|
35
|
-
* @default "defaultLocale"
|
|
36
|
-
*/
|
|
37
|
-
defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
|
|
38
|
-
/**
|
|
39
|
-
* Default locale path
|
|
40
|
-
*
|
|
41
|
-
* @description the first locale will be used if absent
|
|
42
|
-
*
|
|
43
|
-
* 默认语言路径
|
|
44
|
-
*
|
|
45
|
-
* @description 如果缺失,则使用第一个语言
|
|
46
|
-
*/
|
|
47
|
-
defaultLocale?: string;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
interface RedirectPluginLocaleData {
|
|
51
|
-
/**
|
|
52
|
-
* Language name
|
|
53
|
-
*
|
|
54
|
-
* 语言名称
|
|
55
|
-
*/
|
|
56
|
-
name: string;
|
|
57
|
-
/**
|
|
58
|
-
* Switch hint
|
|
59
|
-
*
|
|
60
|
-
* 切换提示
|
|
61
|
-
*/
|
|
62
|
-
hint: string;
|
|
63
|
-
/**
|
|
64
|
-
* Switch button text
|
|
65
|
-
*
|
|
66
|
-
* 切换按钮文字
|
|
67
|
-
*/
|
|
68
|
-
switch: string;
|
|
69
|
-
/**
|
|
70
|
-
* Cancel button text
|
|
71
|
-
*
|
|
72
|
-
* 取消按钮文字
|
|
73
|
-
*/
|
|
74
|
-
cancel: string;
|
|
75
|
-
/**
|
|
76
|
-
* remember hint text
|
|
77
|
-
*
|
|
78
|
-
* 记住提示文本
|
|
79
|
-
*/
|
|
80
|
-
remember: string;
|
|
81
|
-
}
|
|
82
|
-
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/node/types/options.d.ts
|
|
83
13
|
interface RedirectPluginOptions extends RedirectBehaviorOptions {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Redirect mapping
|
|
16
|
+
*
|
|
17
|
+
* 重定向映射
|
|
18
|
+
*/
|
|
19
|
+
config?: Record<string, string> | ((app: App) => Record<string, string>);
|
|
20
|
+
/**
|
|
21
|
+
* Whether switch locales
|
|
22
|
+
*
|
|
23
|
+
* 是否启用重定向语言
|
|
24
|
+
*/
|
|
25
|
+
switchLocale?: 'direct' | 'modal' | false;
|
|
26
|
+
/**
|
|
27
|
+
* Locale language config
|
|
28
|
+
*
|
|
29
|
+
* 多语言语言配置
|
|
30
|
+
*/
|
|
31
|
+
localeConfig?: Record<string, string[] | string>;
|
|
32
|
+
/**
|
|
33
|
+
* Locales config
|
|
34
|
+
*
|
|
35
|
+
* 多语言选项
|
|
36
|
+
*/
|
|
37
|
+
locales?: LocaleConfig<RedirectPluginLocaleData>;
|
|
108
38
|
}
|
|
109
|
-
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/node/redirectPlugin.d.ts
|
|
110
41
|
declare const redirectPlugin: (options?: RedirectPluginOptions) => PluginFunction;
|
|
111
|
-
|
|
112
|
-
export { redirectPlugin };
|
|
113
|
-
|
|
42
|
+
//#endregion
|
|
43
|
+
export { RedirectPluginFrontmatter, RedirectPluginOptions, redirectPlugin };
|
|
44
|
+
//# sourceMappingURL=index.d.ts.map
|
package/lib/node/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{Logger as
|
|
2
|
-
`}))},
|
|
1
|
+
import{t as e}from"../getRedirectHTML-C9SBJAfB.js";import{t}from"../normalizePath-DCapcto5.js";import{Logger as n,addViteSsrNoExternal as r,deepAssign as i,entries as a,fromEntries as o,getFullLocaleConfig as s,getModulePath as c,isArray as l,isFunction as u,isLinkAbsolute as d,isLinkHttp as f,isPlainObject as p,keys as m,removeEndingSlash as h,removeLeadingSlash as g}from"@vuepress/helper";import{createPage as _}from"vuepress/core";import{colors as v,fs as y,getDirname as b,path as x}from"vuepress/utils";const S=async e=>{e.pages.every(({path:e})=>e!==`/`)&&e.pages.push(await _(e,{path:`/`,frontmatter:{title:`Home`},content:`Redirecting to the correct locale...
|
|
2
|
+
`}))},C=`@vuepress/plugin-redirect`,w=new n(C),T=({config:e,defaultBehavior:t,defaultLocale:n,localeFallback:r},i,a)=>`<!doctype html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8">
|
|
@@ -7,14 +7,14 @@ import{Logger as y,removeEndingSlash as s,entries as h,removeLeadingSlash as u,i
|
|
|
7
7
|
<title>Redirecting...</title>
|
|
8
8
|
<script>
|
|
9
9
|
const { hash, origin, pathname } = window.location;
|
|
10
|
-
const routePath = pathname.slice(${
|
|
10
|
+
const routePath = pathname.slice(${a.length});
|
|
11
11
|
const { languages } = window.navigator;
|
|
12
12
|
const anchor = hash.slice(1);
|
|
13
13
|
|
|
14
|
-
const config = ${JSON.stringify(
|
|
14
|
+
const config = ${JSON.stringify(e)};
|
|
15
15
|
const availableLocales = ${JSON.stringify(i)};
|
|
16
|
-
const defaultLocale = ${i.includes(
|
|
17
|
-
const defaultBehavior = ${JSON.stringify(
|
|
16
|
+
const defaultLocale = ${i.includes(n)?JSON.stringify(n):`availableLocales.pop()`};
|
|
17
|
+
const defaultBehavior = ${JSON.stringify(t)}
|
|
18
18
|
|
|
19
19
|
let matchedLocalePath = null;
|
|
20
20
|
|
|
@@ -23,18 +23,19 @@ import{Logger as y,removeEndingSlash as s,entries as h,removeLeadingSlash as u,i
|
|
|
23
23
|
for (const lang of languages)
|
|
24
24
|
for (const [localePath, langs] of Object.entries(config))
|
|
25
25
|
if (langs.includes(lang)) {
|
|
26
|
-
${
|
|
26
|
+
${r?` if (!availableLocales.includes(localePath))
|
|
27
27
|
continue;
|
|
28
|
-
|
|
28
|
+
`:``}\
|
|
29
|
+
matchedLocalePath = localePath;
|
|
29
30
|
break findLanguage;
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
// default link
|
|
33
|
-
const defaultLink = defaultLocale? \`\${origin}${
|
|
34
|
+
const defaultLink = defaultLocale? \`\${origin}${h(a)}\${defaultLocale}\${routePath}\${anchor? \`#\${anchor}\`: ""}\`: null;
|
|
34
35
|
|
|
35
36
|
// a locale matches
|
|
36
37
|
if (matchedLocalePath) {
|
|
37
|
-
const localeLink = \`\${origin}${
|
|
38
|
+
const localeLink = \`\${origin}${h(a)}\${matchedLocalePath}\${routePath}\${anchor? \`#\${anchor}\`: ""}\`;
|
|
38
39
|
|
|
39
40
|
if (availableLocales.includes(matchedLocalePath)) {
|
|
40
41
|
location.href = localeLink;
|
|
@@ -43,7 +44,7 @@ ${n?` if (!availableLocales.includes(localePath))
|
|
|
43
44
|
else {
|
|
44
45
|
// locale homepage
|
|
45
46
|
if (defaultBehavior === "homepage") {
|
|
46
|
-
location.href = \`\${origin}${
|
|
47
|
+
location.href = \`\${origin}${h(a)}\${matchedLocalePath}\`;
|
|
47
48
|
}
|
|
48
49
|
// default locale page
|
|
49
50
|
else if (defaultBehavior === "defaultLocale" && defaultLink) {
|
|
@@ -60,7 +61,7 @@ ${n?` if (!availableLocales.includes(localePath))
|
|
|
60
61
|
location.href = defaultLink;
|
|
61
62
|
}
|
|
62
63
|
else {
|
|
63
|
-
location.href = \`\${origin}${
|
|
64
|
+
location.href = \`\${origin}${h(a)}/404.html\`;
|
|
64
65
|
}
|
|
65
66
|
<\/script>
|
|
66
67
|
</head>
|
|
@@ -68,23 +69,10 @@ ${n?` if (!availableLocales.includes(localePath))
|
|
|
68
69
|
<p>Redirecting...</p>
|
|
69
70
|
</body>
|
|
70
71
|
</html>
|
|
71
|
-
`,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
<title>Redirecting...</title>
|
|
79
|
-
<script>
|
|
80
|
-
const anchor = window.location.hash.slice(1);
|
|
81
|
-
window.location.replace(\`${a}\${anchor? \`#\${anchor}\`: ""}\`);
|
|
82
|
-
<\/script>
|
|
83
|
-
</head>
|
|
84
|
-
<body>
|
|
85
|
-
<p>Redirecting...</p>
|
|
86
|
-
</body>
|
|
87
|
-
</html>
|
|
88
|
-
`,B=async(a,e,c="")=>{const n=c?s(k(c)?c:`https://${c}`):"",{succeed:i}=m.load("Generating redirect files");await Promise.all(h(e).map(async([t,o])=>{const l=a.dir.dest(u(t));if(!r.existsSync(l)){const v=f(o)?`${n}${a.siteData.base}${u(o)}`:o;await r.ensureDir(p.dirname(l)),await r.writeFile(l,T(v))}})),i()},I=["defaultLocale","homepage","404"],N=(a,e)=>{const{locales:c}=a.siteData,n=P(g(h(c).filter(([i,{lang:t}])=>t?!0:(m.error(`Missing ${C.magenta("lang")} option for locale "${i}", this locale will be ignored!`),!1)).map(([i,{lang:t}])=>[i,[t]])),$(e.localeConfig)?g(h(e.localeConfig).map(([i,t])=>[i,w(t)?t:[t]])):{});return{config:n,autoLocale:e.autoLocale??!1,defaultLocale:e.defaultLocale||R(n).pop(),localeFallback:e.localeFallback??!0,defaultBehavior:e.defaultBehavior&&I.includes(e.defaultBehavior)?e.defaultBehavior:"defaultLocale"}},O=/#.*$/u,d=(a,e=!1)=>(e?a.replace(O,""):a).replace(/\/(?:README\.md)?$/i,"/index.html").replace(/(?:\.(?:md|html))?$/,".html"),x=(a,e)=>{const c=z(e.config)?e.config(a):$(e.config)?e.config:{};return{...g(a.pages.map(({frontmatter:n,path:i})=>w(n.redirectFrom)?n.redirectFrom.map(t=>[d(t,!0),i]):n.redirectFrom?[[d(n.redirectFrom,!0),i]]:[]).flat()),...g(h(c).map(([n,i])=>[d(n,!0),d(i)]))}},H=({frontmatter:a},e)=>{const{base:c}=e.siteData,{redirectTo:n}=a;if(n){const i=d(f(n)?`${c}${u(n)}`:n);(a.head??=[]).unshift(["script",{},`{const anchor = window.location.hash.slice(1);window.location.replace(\`${i}\${anchor? \`#\${anchor}\`: ""}\`);}`])}},U=[[["en","en-US"],{name:"English",hint:"Your primary language is $1, do you want to switch to it?",switch:"Switch to $1",cancel:"Cancel",remember:"Remember my choice"}],[["zh","zh-CN","zh-Hans"],{name:"简体中文",hint:"你的首选语言是 $1,是否切换到该语言?",switch:"切换到 $1",cancel:"取消",remember:"记住我的选择"}],[["zh-TW","zh-Hant"],{name:"繁體中文",hint:"你的首選語言是 $1,是否切換到該語言?",switch:"切換到 $1",cancel:"取消",remember:"記住我的選擇"}],[["de","de-DE"],{name:"Deutsch",hint:"Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?",switch:"Zu $1 wechseln",cancel:"Abbrechen",remember:"Meine Wahl merken"}],[["de-AT"],{name:"Deutsch (Österreich)",hint:"Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?",switch:"Zu $1 wechseln",cancel:"Abbrechen",remember:"Meine Wahl merken"}],[["vi","vi-VN"],{name:"Tiếng Việt",hint:"Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?",switch:"Chuyển sang $1",cancel:"Hủy",remember:"Nhớ lựa chọn của tôi"}],[["uk"],{name:"Українська",hint:"Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?",switch:"Переключитися на $1",cancel:"Скасувати",remember:"Запам’ятати мій вибір"}],[["ru","ru-RU"],{name:"Русский",hint:"Ваш основной язык - $1, вы хотите переключиться на него?",switch:"Переключиться на $1",cancel:"Отмена",remember:"Запомнить мой выбор"}],[["br"],{name:"Português (Brasil)",hint:"A língua principal é $1, deseja mudar para ela?",switch:"Mudar para $1",cancel:"Cancelar",remember:"Lembrar minha escolha"}],[["pl","pl-PL"],{name:"Polski",hint:"Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?",switch:"Przełącz na $1",cancel:"Anuluj",remember:"Zapamiętaj moje wybory"}],[["sk","sk-SK"],{name:"Slovenčina",hint:"Vašou hlavnou jazykom je $1, chcete prepnúť naň?",switch:"Prepnúť na $1",cancel:"Zrušiť",remember:"Zapamätať si moju voľbu"}],[["fr","fr-FR"],{name:"Français",hint:"Votre langue principale est $1, voulez-vous la changer ?",switch:"Changer pour $1",cancel:"Annuler",remember:"Se souvenir de mon choix"}],[["tr","tr-TR"],{name:"Türkçe",hint:"Ana diliniz $1, ona geçmek ister misiniz?",switch:"$1'e geç",cancel:"İptal",remember:"Seçimimi hatırla"}],[["fi","fi-FI"],{name:"Suomi",hint:"Pääkielenäsi on $1, haluatko vaihtaa siihen?",switch:"Vaihda $1:een",cancel:"Peruuta",remember:"Muista valintani"}],[["hu","hu-HU"],{name:"Magyar",hint:"A fő nyelvét $1, szeretné váltani?",switch:"Váltás $1",cancel:"Mégse",remember:"Emlékezzen a választásomra"}],[["id","id-ID"],{name:"Bahasa Indonesia",hint:"Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?",switch:"Beralih ke $1",cancel:"Batal",remember:"Ingat pilihan saya"}],[["nl","nl-NL"],{name:"Nederlands",hint:"Uw primaire taal is $1, wilt u overschakelen?",switch:"Overschakelen naar $1",cancel:"Annuleren",remember:"Onthoud mijn keuze"}],[["ja","ja-JP"],{name:"日本語",hint:"あなたの主要な言語は $1 です。それに切り替えますか?",switch:"$1 に切り替える",cancel:"キャンセル",remember:"選択を記憶する"}],[["ko","ko-KO"],{name:"한국어",hint:"당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?",switch:"$1로 전환",cancel:"취소",remember:"내 선택 기억하기"}],[["es","es-ES"],{name:"Español",hint:"Su idioma principal es $1, ¿desea cambiarlo?",switch:"Cambiar a $1",cancel:"Cancelar",remember:"Recordar mi elección"}],[["/pt"],{name:"Português",hint:"Sua língua principal é $1, deseja mudar para ela?",switch:"Mudar para $1",cancel:"Cancelar",remember:"Lembrar minha escolha"}]],{url:V}=import.meta,L=_(V),J=(a={})=>e=>{e.env.isDebug&&m.info("Options:",a);const c=N(e,a);let n=null;return{name:b,alias:{"@vuepress/plugin-redirect/modal":a.switchLocale==="modal"?p.resolve(L,"../client/components/RedirectModal.js"):E("@vuepress/helper/noopComponent",import.meta)},define:{__REDIRECT_CONFIG__:c,__REDIRECT_DIRECT__:a.switchLocale==="direct",__REDIRECT_MODAL__:a.switchLocale==="modal",__REDIRECT_LOCALES__:D({app:e,name:"redirect",config:a.locales,default:U})},extendsBundlerOptions:i=>{S(i,e,"@vuepress/helper")},extendsPage:i=>{H(i,e)},onInitialized:async()=>{n=x(e,a),e.env.isDebug&&m.info("Redirect Map:",n),a.autoLocale&&e.env.isDebug&&await j(e)},onPrepared:async()=>{await e.writeTemp("redirect/map.js",`export const redirectMap = ${e.env.isDev?JSON.stringify(n,null,2):"{}"};
|
|
89
|
-
`),e.env.isDev&&(n=null)},onGenerated:async()=>{await B(e,n),a.autoLocale&&await M(e,c)},clientConfigFile:p.join(L,"../client/config.js")}};export{J as redirectPlugin};
|
|
90
|
-
//# sourceMappingURL=index.js.map
|
|
72
|
+
`,E=async(e,t)=>{let n=new Set(e.pages.filter(({pathLocale:e})=>e===`/`).map(({path:e})=>e)),r={};e.pages.filter(({pathLocale:e})=>e!==`/`).forEach(({path:e,pathLocale:t})=>{let i=e.replace(t,`/`).replace(/\/$/,`/index.html`);n.has(i)||(r[i]??=[]).push(t)});let{succeed:i}=w.load(`Generating locale redirect files`);await Promise.all(a(r).map(async([n,r])=>{let i=e.dir.dest(g(n));y.existsSync(i)||(await y.ensureDir(x.dirname(i)),await y.writeFile(i,T(t,r,e.siteData.base)))})),i()},D=async(t,n,r=``)=>{let i=r?h(f(r)?r:`https://${r}`):``,{succeed:o}=w.load(`Generating redirect files`);await Promise.all(a(n).map(async([n,r])=>{let a=t.dir.dest(g(n));if(!y.existsSync(a)){let n=d(r)?`${i}${t.siteData.base}${g(r)}`:r;await y.ensureDir(x.dirname(a)),await y.writeFile(a,e(n))}})),o()},O=[`defaultLocale`,`homepage`,`404`],k=(e,t)=>{let{locales:n}=e.siteData,r=i(o(a(n).filter(([e,{lang:t}])=>t?!0:(w.error(`Missing ${v.magenta(`lang`)} option for locale "${e}", this locale will be ignored!`),!1)).map(([e,{lang:t}])=>[e,[t]])),p(t.localeConfig)?o(a(t.localeConfig).map(([e,t])=>[e,l(t)?t:[t]])):{});return{config:r,autoLocale:t.autoLocale??!1,defaultLocale:t.defaultLocale||m(r).pop(),localeFallback:t.localeFallback??!0,defaultBehavior:t.defaultBehavior&&O.includes(t.defaultBehavior)?t.defaultBehavior:`defaultLocale`}},A=(e,n)=>{let r=u(n.config)?n.config(e):p(n.config)?n.config:{};return{...o(e.pages.flatMap(({frontmatter:e,path:n})=>l(e.redirectFrom)?e.redirectFrom.map(e=>[t(e,!0),n]):e.redirectFrom?[[t(e.redirectFrom,!0),n]]:[])),...o(a(r).map(([e,n])=>[t(e,!0),t(n)]))}},j=({frontmatter:e},n)=>{let{base:r}=n.siteData,{redirectTo:i}=e;if(i){let n=t(d(i)?`${r}${g(i)}`:i);(e.head??=[]).unshift([`script`,{},`{\
|
|
73
|
+
const anchor = window.location.hash.slice(1);\
|
|
74
|
+
window.location.replace(\`${n}\${anchor? \`#\${anchor}\`: ""}\`);\
|
|
75
|
+
}`])}},M=[[[`en`,`en-US`],{name:`English`,hint:`Your primary language is $1, do you want to switch to it?`,switch:`Switch to $1`,cancel:`Cancel`,remember:`Remember my choice`}],[[`zh`,`zh-CN`,`zh-Hans`],{name:`简体中文`,hint:`你的首选语言是 $1,是否切换到该语言?`,switch:`切换到 $1`,cancel:`取消`,remember:`记住我的选择`}],[[`zh-TW`,`zh-Hant`],{name:`繁體中文`,hint:`你的首選語言是 $1,是否切換到該語言?`,switch:`切換到 $1`,cancel:`取消`,remember:`記住我的選擇`}],[[`de`,`de-DE`],{name:`Deutsch`,hint:`Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?`,switch:`Zu $1 wechseln`,cancel:`Abbrechen`,remember:`Meine Wahl merken`}],[[`de-AT`],{name:`Deutsch (Österreich)`,hint:`Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?`,switch:`Zu $1 wechseln`,cancel:`Abbrechen`,remember:`Meine Wahl merken`}],[[`vi`,`vi-VN`],{name:`Tiếng Việt`,hint:`Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?`,switch:`Chuyển sang $1`,cancel:`Hủy`,remember:`Nhớ lựa chọn của tôi`}],[[`uk`],{name:`Українська`,hint:`Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?`,switch:`Переключитися на $1`,cancel:`Скасувати`,remember:`Запам’ятати мій вибір`}],[[`ru`,`ru-RU`],{name:`Русский`,hint:`Ваш основной язык - $1, вы хотите переключиться на него?`,switch:`Переключиться на $1`,cancel:`Отмена`,remember:`Запомнить мой выбор`}],[[`br`],{name:`Português (Brasil)`,hint:`A língua principal é $1, deseja mudar para ela?`,switch:`Mudar para $1`,cancel:`Cancelar`,remember:`Lembrar minha escolha`}],[[`pl`,`pl-PL`],{name:`Polski`,hint:`Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?`,switch:`Przełącz na $1`,cancel:`Anuluj`,remember:`Zapamiętaj moje wybory`}],[[`sk`,`sk-SK`],{name:`Slovenčina`,hint:`Vašou hlavnou jazykom je $1, chcete prepnúť naň?`,switch:`Prepnúť na $1`,cancel:`Zrušiť`,remember:`Zapamätať si moju voľbu`}],[[`fr`,`fr-FR`],{name:`Français`,hint:`Votre langue principale est $1, voulez-vous la changer ?`,switch:`Changer pour $1`,cancel:`Annuler`,remember:`Se souvenir de mon choix`}],[[`tr`,`tr-TR`],{name:`Türkçe`,hint:`Ana diliniz $1, ona geçmek ister misiniz?`,switch:`$1'e geç`,cancel:`İptal`,remember:`Seçimimi hatırla`}],[[`fi`,`fi-FI`],{name:`Suomi`,hint:`Pääkielenäsi on $1, haluatko vaihtaa siihen?`,switch:`Vaihda $1:een`,cancel:`Peruuta`,remember:`Muista valintani`}],[[`hu`,`hu-HU`],{name:`Magyar`,hint:`A fő nyelvét $1, szeretné váltani?`,switch:`Váltás $1`,cancel:`Mégse`,remember:`Emlékezzen a választásomra`}],[[`id`,`id-ID`],{name:`Bahasa Indonesia`,hint:`Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?`,switch:`Beralih ke $1`,cancel:`Batal`,remember:`Ingat pilihan saya`}],[[`nl`,`nl-NL`],{name:`Nederlands`,hint:`Uw primaire taal is $1, wilt u overschakelen?`,switch:`Overschakelen naar $1`,cancel:`Annuleren`,remember:`Onthoud mijn keuze`}],[[`ja`,`ja-JP`],{name:`日本語`,hint:`あなたの主要な言語は $1 です。それに切り替えますか?`,switch:`$1 に切り替える`,cancel:`キャンセル`,remember:`選択を記憶する`}],[[`ko`,`ko-KO`],{name:`한국어`,hint:`당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?`,switch:`$1로 전환`,cancel:`취소`,remember:`내 선택 기억하기`}],[[`es`,`es-ES`],{name:`Español`,hint:`Su idioma principal es $1, ¿desea cambiarlo?`,switch:`Cambiar a $1`,cancel:`Cancelar`,remember:`Recordar mi elección`}],[[`/pt`],{name:`Português`,hint:`Sua língua principal é $1, deseja mudar para ela?`,switch:`Mudar para $1`,cancel:`Cancelar`,remember:`Lembrar minha escolha`}]],{url:N}=import.meta,P=b(N),F=(e={})=>t=>{t.env.isDebug&&w.info(`Options:`,e);let n=k(t,e),i=null;return{name:C,alias:{"@vuepress/plugin-redirect/modal":e.switchLocale===`modal`?x.resolve(P,`../client/components/RedirectModal.js`):c(`@vuepress/helper/noopComponent`,import.meta)},define:{__REDIRECT_CONFIG__:n,__REDIRECT_DIRECT__:e.switchLocale===`direct`,__REDIRECT_MODAL__:e.switchLocale===`modal`,__REDIRECT_LOCALES__:s({app:t,name:`redirect`,config:e.locales,default:M})},extendsBundlerOptions:e=>{r(e,t,`@vuepress/helper`)},extendsPage:e=>{j(e,t)},onInitialized:async()=>{i=A(t,e),t.env.isDebug&&w.info(`Redirect Map:`,i),e.autoLocale&&t.env.isDebug&&await S(t)},onPrepared:async()=>{await t.writeTemp(`redirect/map.js`,`\
|
|
76
|
+
export const redirectMap = ${t.env.isDev?JSON.stringify(i,null,2):`{}`};
|
|
77
|
+
`),t.env.isDev&&(i=null)},onGenerated:async()=>{await D(t,i),e.autoLocale&&await E(t,n)},clientConfigFile:x.join(P,`../client/config.js`)}};export{F as redirectPlugin};
|
|
78
|
+
//# sourceMappingURL=index.js.map
|
package/lib/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/node/ensureRootHomePage.ts","../../src/node/logger.ts","../../src/node/generate/getLocaleRedirectHTML.ts","../../src/node/generate/generateAutoLocaleRedirectFiles.ts","../../src/node/generate/getRedirectHTML.ts","../../src/node/generate/generateRedirectFiles.ts","../../src/node/getRedirectLocaleConfig.ts","../../src/shared/normalizePath.ts","../../src/node/getRedirectMap.ts","../../src/node/handleRedirectTo.ts","../../src/node/locales.ts","../../src/node/redirectPlugin.ts"],"sourcesContent":["import type { App } from 'vuepress/core'\nimport { createPage } from 'vuepress/core'\n\nexport const ensureRootHomePage = async (app: App): Promise<void> => {\n if (\n // root homepage not exists\n app.pages.every(({ path }) => path !== '/')\n ) {\n app.pages.push(\n await createPage(app, {\n path: '/',\n frontmatter: { title: 'Home' },\n // set markdown content\n content: `\\\nRedirecting to the correct locale...\n`,\n }),\n )\n }\n}\n","import { Logger } from '@vuepress/helper'\n\nexport const PLUGIN_NAME = '@vuepress/plugin-redirect'\n\nexport const logger = new Logger(PLUGIN_NAME)\n","import { removeEndingSlash } from '@vuepress/helper'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport const getLocaleRedirectHTML = (\n {\n config,\n defaultBehavior,\n defaultLocale,\n localeFallback,\n }: RedirectBehaviorConfig,\n availableLocales: string[],\n base: string,\n): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <title>Redirecting...</title>\n <script>\n const { hash, origin, pathname } = window.location;\n const routePath = pathname.slice(${base.length});\n const { languages } = window.navigator;\n const anchor = hash.slice(1);\n\n const config = ${JSON.stringify(config)};\n const availableLocales = ${JSON.stringify(availableLocales)};\n const defaultLocale = ${\n availableLocales.includes(defaultLocale)\n ? JSON.stringify(defaultLocale)\n : 'availableLocales.pop()'\n };\n const defaultBehavior = ${JSON.stringify(defaultBehavior)}\n\n let matchedLocalePath = null;\n\n // get matched locale\n findLanguage:\n for (const lang of languages)\n for (const [localePath, langs] of Object.entries(config))\n if (langs.includes(lang)) {\n${\n localeFallback\n ? `\\\n if (!availableLocales.includes(localePath))\n continue;\n`\n : ``\n}\\\n matchedLocalePath = localePath;\n break findLanguage;\n }\n\n // default link\n const defaultLink = defaultLocale? \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${defaultLocale}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`: null;\n\n // a locale matches\n if (matchedLocalePath) {\n const localeLink = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`;\n\n if (availableLocales.includes(matchedLocalePath)) {\n location.href = localeLink;\n }\n // the page does not exist\n else {\n // locale homepage\n if (defaultBehavior === \"homepage\") {\n location.href = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\`;\n }\n // default locale page\n else if (defaultBehavior === \"defaultLocale\" && defaultLink) {\n location.href = defaultLink;\n }\n // as is to get a 404 page of that locale\n else {\n location.href = localeLink;\n }\n }\n }\n // we have a default page\n else if (defaultLink) {\n location.href = defaultLink;\n }\n else {\n location.href = \\`\\${origin}${removeEndingSlash(base)}/404.html\\`;\n }\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","import { entries, removeLeadingSlash } from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { logger } from '../logger.js'\nimport { getLocaleRedirectHTML } from './getLocaleRedirectHTML.js'\n\nexport const generateAutoLocaleRedirectFiles = async (\n app: App,\n localeOptions: RedirectBehaviorConfig,\n): Promise<void> => {\n const rootPaths = app.pages\n .filter(({ pathLocale }) => pathLocale === '/')\n .map(({ path: pagePath }) => pagePath)\n const localeRedirectMap: Record<string, string[]> = {}\n\n app.pages\n .filter(({ pathLocale }) => pathLocale !== '/')\n .forEach(({ path: pagePath, pathLocale }) => {\n const rootPath = pagePath\n .replace(pathLocale, '/')\n .replace(/\\/$/, '/index.html')\n\n if (!rootPaths.includes(rootPath))\n (localeRedirectMap[rootPath] ??= []).push(pathLocale)\n })\n\n const { succeed } = logger.load('Generating locale redirect files')\n\n await Promise.all(\n entries(localeRedirectMap).map(async ([rootPath, availableLocales]) => {\n const filePath = app.dir.dest(removeLeadingSlash(rootPath))\n\n if (!fs.existsSync(filePath)) {\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(\n filePath,\n getLocaleRedirectHTML(\n localeOptions,\n availableLocales,\n app.siteData.base,\n ),\n )\n }\n }),\n )\n\n succeed()\n}\n","export const getRedirectHTML = (redirectUrl: string): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <meta http-equiv=\"refresh\" content=\"0; url=${redirectUrl}\">\n <link rel=\"canonical\" href=\"${redirectUrl}\">\n <title>Redirecting...</title>\n <script>\n const anchor = window.location.hash.slice(1);\n window.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","import {\n entries,\n isLinkAbsolute,\n isLinkHttp,\n removeEndingSlash,\n removeLeadingSlash,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport { logger } from '../logger.js'\nimport { getRedirectHTML } from './getRedirectHTML.js'\n\nexport const generateRedirectFiles = async (\n app: App,\n config: Record<string, string>,\n hostname = '',\n): Promise<void> => {\n const resolvedHostname = hostname\n ? removeEndingSlash(isLinkHttp(hostname) ? hostname : `https://${hostname}`)\n : ''\n\n const { succeed } = logger.load('Generating redirect files')\n\n await Promise.all(\n entries(config).map(async ([from, to]) => {\n const filePath = app.dir.dest(removeLeadingSlash(from))\n\n if (!fs.existsSync(filePath)) {\n const redirectUrl = isLinkAbsolute(to)\n ? `${resolvedHostname}${app.siteData.base}${removeLeadingSlash(to)}`\n : to\n\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(filePath, getRedirectHTML(redirectUrl))\n }\n }),\n )\n\n succeed()\n}\n","import {\n deepAssign,\n entries,\n fromEntries,\n isArray,\n isPlainObject,\n keys,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { colors } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst AVAILABLE_FALLBACK = ['defaultLocale', 'homepage', '404'] as const\n\nexport const getRedirectBehaviorConfig = (\n app: App,\n options: RedirectPluginOptions,\n): RedirectBehaviorConfig => {\n const { locales } = app.siteData\n\n const config = deepAssign(\n fromEntries(\n entries(locales)\n .filter(([key, { lang }]) => {\n if (!lang) {\n logger.error(\n `Missing ${colors.magenta(\n 'lang',\n )} option for locale \"${key}\", this locale will be ignored!`,\n )\n\n return false\n }\n\n return true\n })\n .map(([key, { lang }]) => [key, [lang!]]),\n ),\n isPlainObject(options.localeConfig)\n ? fromEntries(\n entries(options.localeConfig).map(([routePath, lang]) => [\n routePath,\n isArray(lang) ? lang : [lang],\n ]),\n )\n : {},\n )\n\n return {\n config,\n autoLocale: options.autoLocale ?? false,\n defaultLocale: options.defaultLocale || keys(config).pop()!,\n localeFallback: options.localeFallback ?? true,\n defaultBehavior:\n options.defaultBehavior &&\n AVAILABLE_FALLBACK.includes(options.defaultBehavior)\n ? options.defaultBehavior\n : 'defaultLocale',\n }\n}\n","const HASH_REGEXP = /#.*$/u\n\nexport const normalizePath = (path: string, removeHash = false): string =>\n (removeHash ? path.replace(HASH_REGEXP, '') : path)\n .replace(/\\/(?:README\\.md)?$/i, '/index.html')\n .replace(/(?:\\.(?:md|html))?$/, '.html')\n","import {\n entries,\n fromEntries,\n isArray,\n isFunction,\n isPlainObject,\n} from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type {\n RedirectPluginFrontmatter,\n RedirectPluginOptions,\n} from './types/index.js'\n\nexport const getRedirectMap = (\n app: App,\n options: RedirectPluginOptions,\n): Record<string, string> => {\n const config = isFunction(options.config)\n ? options.config(app)\n : isPlainObject(options.config)\n ? options.config\n : {}\n\n return {\n ...fromEntries(\n (app.pages as Page<Record<string, never>, RedirectPluginFrontmatter>[])\n .map<\n [string, string][]\n >(({ frontmatter, path }) => (isArray(frontmatter.redirectFrom) ? frontmatter.redirectFrom.map((from) => [normalizePath(from, true), path]) : frontmatter.redirectFrom ? [[normalizePath(frontmatter.redirectFrom, true), path]] : []))\n .flat(),\n ),\n ...fromEntries(\n entries(config).map(([from, to]) => [\n normalizePath(from, true),\n normalizePath(to),\n ]),\n ),\n }\n}\n","import { isLinkAbsolute, removeLeadingSlash } from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type { RedirectPluginFrontmatter } from './types/index.js'\n\nexport const handleRedirectTo = ({ frontmatter }: Page, app: App): void => {\n const { base } = app.siteData\n const { redirectTo } = frontmatter as RedirectPluginFrontmatter\n\n if (redirectTo) {\n const redirectUrl = normalizePath(\n isLinkAbsolute(redirectTo)\n ? `${base}${removeLeadingSlash(redirectTo)}`\n : redirectTo,\n )\n\n ;(frontmatter.head ??= []).unshift([\n 'script',\n {},\n `{\\\nconst anchor = window.location.hash.slice(1);\\\nwindow.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\\\n}`,\n ])\n }\n}\n","import type { DefaultLocaleInfo } from '@vuepress/helper'\nimport type { RedirectPluginLocaleData } from '../shared/index.js'\n\n/**\n * Default locale info for `@vuepress/plugin-redirect`\n */\nexport const redirectLocaleInfo: DefaultLocaleInfo<RedirectPluginLocaleData> = [\n [\n ['en', 'en-US'],\n {\n name: 'English',\n hint: 'Your primary language is $1, do you want to switch to it?',\n switch: 'Switch to $1',\n cancel: 'Cancel',\n remember: 'Remember my choice',\n },\n ],\n [\n ['zh', 'zh-CN', 'zh-Hans'],\n {\n name: '简体中文',\n hint: '你的首选语言是 $1,是否切换到该语言?',\n switch: '切换到 $1',\n cancel: '取消',\n remember: '记住我的选择',\n },\n ],\n [\n ['zh-TW', 'zh-Hant'],\n {\n name: '繁體中文',\n hint: '你的首選語言是 $1,是否切換到該語言?',\n switch: '切換到 $1',\n cancel: '取消',\n remember: '記住我的選擇',\n },\n ],\n [\n ['de', 'de-DE'],\n {\n name: 'Deutsch',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['de-AT'],\n {\n name: 'Deutsch (Österreich)',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['vi', 'vi-VN'],\n {\n name: 'Tiếng Việt',\n hint: 'Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?',\n switch: 'Chuyển sang $1',\n cancel: 'Hủy',\n remember: 'Nhớ lựa chọn của tôi',\n },\n ],\n [\n ['uk'],\n {\n name: 'Українська',\n hint: 'Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?',\n switch: 'Переключитися на $1',\n cancel: 'Скасувати',\n remember: 'Запам’ятати мій вибір',\n },\n ],\n [\n ['ru', 'ru-RU'],\n {\n name: 'Русский',\n hint: 'Ваш основной язык - $1, вы хотите переключиться на него?',\n switch: 'Переключиться на $1',\n cancel: 'Отмена',\n remember: 'Запомнить мой выбор',\n },\n ],\n [\n ['br'],\n {\n name: 'Português (Brasil)',\n hint: 'A língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n [\n ['pl', 'pl-PL'],\n {\n name: 'Polski',\n hint: 'Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?',\n switch: 'Przełącz na $1',\n cancel: 'Anuluj',\n remember: 'Zapamiętaj moje wybory',\n },\n ],\n [\n ['sk', 'sk-SK'],\n {\n name: 'Slovenčina',\n hint: 'Vašou hlavnou jazykom je $1, chcete prepnúť naň?',\n switch: 'Prepnúť na $1',\n cancel: 'Zrušiť',\n remember: 'Zapamätať si moju voľbu',\n },\n ],\n [\n ['fr', 'fr-FR'],\n {\n name: 'Français',\n hint: 'Votre langue principale est $1, voulez-vous la changer ?',\n switch: 'Changer pour $1',\n cancel: 'Annuler',\n remember: 'Se souvenir de mon choix',\n },\n ],\n [\n ['tr', 'tr-TR'],\n {\n name: 'Türkçe',\n hint: 'Ana diliniz $1, ona geçmek ister misiniz?',\n switch: \"$1'e geç\",\n cancel: 'İptal',\n remember: 'Seçimimi hatırla',\n },\n ],\n [\n ['fi', 'fi-FI'],\n {\n name: 'Suomi',\n hint: 'Pääkielenäsi on $1, haluatko vaihtaa siihen?',\n switch: 'Vaihda $1:een',\n cancel: 'Peruuta',\n remember: 'Muista valintani',\n },\n ],\n [\n ['hu', 'hu-HU'],\n {\n name: 'Magyar',\n hint: 'A fő nyelvét $1, szeretné váltani?',\n switch: 'Váltás $1',\n cancel: 'Mégse',\n remember: 'Emlékezzen a választásomra',\n },\n ],\n [\n ['id', 'id-ID'],\n {\n name: 'Bahasa Indonesia',\n hint: 'Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?',\n switch: 'Beralih ke $1',\n cancel: 'Batal',\n remember: 'Ingat pilihan saya',\n },\n ],\n [\n ['nl', 'nl-NL'],\n {\n name: 'Nederlands',\n hint: 'Uw primaire taal is $1, wilt u overschakelen?',\n switch: 'Overschakelen naar $1',\n cancel: 'Annuleren',\n remember: 'Onthoud mijn keuze',\n },\n ],\n [\n ['ja', 'ja-JP'],\n {\n name: '日本語',\n hint: 'あなたの主要な言語は $1 です。それに切り替えますか?',\n switch: '$1 に切り替える',\n cancel: 'キャンセル',\n remember: '選択を記憶する',\n },\n ],\n [\n ['ko', 'ko-KO'],\n {\n name: '한국어',\n hint: '당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?',\n switch: '$1로 전환',\n cancel: '취소',\n remember: '내 선택 기억하기',\n },\n ],\n [\n ['es', 'es-ES'],\n {\n name: 'Español',\n hint: 'Su idioma principal es $1, ¿desea cambiarlo?',\n switch: 'Cambiar a $1',\n cancel: 'Cancelar',\n remember: 'Recordar mi elección',\n },\n ],\n [\n ['/pt'],\n {\n name: 'Português',\n hint: 'Sua língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n]\n","import {\n addViteSsrNoExternal,\n getFullLocaleConfig,\n getModulePath,\n} from '@vuepress/helper'\nimport type { PluginFunction } from 'vuepress/core'\nimport { getDirname, path } from 'vuepress/utils'\nimport { ensureRootHomePage } from './ensureRootHomePage.js'\nimport {\n generateAutoLocaleRedirectFiles,\n generateRedirectFiles,\n} from './generate/index.js'\nimport { getRedirectBehaviorConfig } from './getRedirectLocaleConfig.js'\nimport { getRedirectMap } from './getRedirectMap.js'\nimport { handleRedirectTo } from './handleRedirectTo.js'\nimport { redirectLocaleInfo } from './locales.js'\nimport { PLUGIN_NAME, logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst { url } = import.meta\nconst __dirname = getDirname(url)\n\nexport const redirectPlugin =\n (options: RedirectPluginOptions = {}): PluginFunction =>\n (app) => {\n if (app.env.isDebug) logger.info('Options:', options)\n\n const behaviorConfig = getRedirectBehaviorConfig(app, options)\n let redirectMap: Record<string, string> | null = null\n\n return {\n name: PLUGIN_NAME,\n\n alias: {\n '@vuepress/plugin-redirect/modal':\n options.switchLocale === 'modal'\n ? path.resolve(__dirname, '../client/components/RedirectModal.js')\n : getModulePath('@vuepress/helper/noopComponent', import.meta),\n },\n\n define: {\n __REDIRECT_CONFIG__: behaviorConfig,\n __REDIRECT_DIRECT__: options.switchLocale === 'direct',\n __REDIRECT_MODAL__: options.switchLocale === 'modal',\n __REDIRECT_LOCALES__: getFullLocaleConfig({\n app,\n name: 'redirect',\n config: options.locales,\n default: redirectLocaleInfo,\n }),\n },\n\n extendsBundlerOptions: (bundlerOptions: unknown): void => {\n addViteSsrNoExternal(bundlerOptions, app, '@vuepress/helper')\n },\n\n extendsPage: (page) => {\n handleRedirectTo(page, app)\n },\n\n onInitialized: async (): Promise<void> => {\n redirectMap = getRedirectMap(app, options)\n\n if (app.env.isDebug) logger.info('Redirect Map:', redirectMap)\n\n if (options.autoLocale && app.env.isDebug) await ensureRootHomePage(app)\n },\n\n onPrepared: async (): Promise<void> => {\n await app.writeTemp(\n 'redirect/map.js',\n `\\\nexport const redirectMap = ${\n app.env.isDev ? JSON.stringify(redirectMap, null, 2) : '{}'\n };\n`,\n )\n // clean redirectMap reference in dev server\n if (app.env.isDev) redirectMap = null\n },\n\n onGenerated: async (): Promise<void> => {\n await generateRedirectFiles(app, redirectMap!)\n if (options.autoLocale)\n await generateAutoLocaleRedirectFiles(app, behaviorConfig)\n },\n\n clientConfigFile: path.join(__dirname, '../client/config.js'),\n }\n }\n"],"names":["ensureRootHomePage","app","path","createPage","PLUGIN_NAME","logger","Logger","getLocaleRedirectHTML","config","defaultBehavior","defaultLocale","localeFallback","availableLocales","base","removeEndingSlash","generateAutoLocaleRedirectFiles","localeOptions","rootPaths","pathLocale","pagePath","localeRedirectMap","rootPath","succeed","entries","filePath","removeLeadingSlash","fs","getRedirectHTML","redirectUrl","generateRedirectFiles","hostname","resolvedHostname","isLinkHttp","from","to","isLinkAbsolute","AVAILABLE_FALLBACK","getRedirectBehaviorConfig","options","locales","deepAssign","fromEntries","key","lang","colors","isPlainObject","routePath","isArray","keys","HASH_REGEXP","normalizePath","removeHash","getRedirectMap","isFunction","frontmatter","handleRedirectTo","redirectTo","redirectLocaleInfo","url","__dirname","getDirname","redirectPlugin","behaviorConfig","redirectMap","getModulePath","getFullLocaleConfig","bundlerOptions","addViteSsrNoExternal","page"],"mappings":"gaAGO,MAAMA,EAAqB,MAAOC,GAA4B,CAGjEA,EAAI,MAAM,MAAM,CAAC,CAAE,KAAAC,CAAK,IAAMA,IAAS,GAAG,GAE1CD,EAAI,MAAM,KACR,MAAME,EAAWF,EAAK,CACpB,KAAM,IACN,YAAa,CAAE,MAAO,MAAO,EAE7B,QAAS;AAAA,CAGX,CAAC,CACH,CAEJ,ECjBaG,EAAc,4BAEdC,EAAS,IAAIC,EAAOF,CAAW,ECD/BG,EAAwB,CACnC,CACE,OAAAC,EACA,gBAAAC,EACA,cAAAC,EACA,eAAAC,CACF,EACAC,EACAC,IACW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCAQ0BA,EAAK,MAAM;AAAA;AAAA;AAAA;AAAA,qBAI7B,KAAK,UAAUL,CAAM,CAAC;AAAA,+BACZ,KAAK,UAAUI,CAAgB,CAAC;AAAA,4BAEzDA,EAAiB,SAASF,CAAa,EACnC,KAAK,UAAUA,CAAa,EAC5B,wBACN;AAAA,8BAC0B,KAAK,UAAUD,CAAe,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU3DE,EACI;AAAA;AAAA,EAIA,EACN;AAA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D,CAAc,CAC7D,EAEA,iBAAkB5D,EAAK,KAAKyD,EAAW,qBAAqB,CAC9D,CACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["logger","logger","logger"],"sources":["../../src/node/ensureRootHomePage.ts","../../src/node/logger.ts","../../src/node/generate/getLocaleRedirectHTML.ts","../../src/node/generate/generateAutoLocaleRedirectFiles.ts","../../src/node/generate/generateRedirectFiles.ts","../../src/node/getRedirectLocaleConfig.ts","../../src/node/getRedirectMap.ts","../../src/node/handleRedirectTo.ts","../../src/node/locales.ts","../../src/node/redirectPlugin.ts"],"sourcesContent":["import type { App } from 'vuepress/core'\nimport { createPage } from 'vuepress/core'\n\nexport const ensureRootHomePage = async (app: App): Promise<void> => {\n if (\n // root homepage not exists\n app.pages.every(({ path }) => path !== '/')\n ) {\n app.pages.push(\n await createPage(app, {\n path: '/',\n frontmatter: { title: 'Home' },\n // set markdown content\n content: `\\\nRedirecting to the correct locale...\n`,\n }),\n )\n }\n}\n","import { Logger } from '@vuepress/helper'\n\nexport const PLUGIN_NAME = '@vuepress/plugin-redirect'\n\nexport const logger = new Logger(PLUGIN_NAME)\n","import { removeEndingSlash } from '@vuepress/helper'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport const getLocaleRedirectHTML = (\n {\n config,\n defaultBehavior,\n defaultLocale,\n localeFallback,\n }: RedirectBehaviorConfig,\n availableLocales: string[],\n base: string,\n): string => `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"robots\" content=\"noindex\">\n <title>Redirecting...</title>\n <script>\n const { hash, origin, pathname } = window.location;\n const routePath = pathname.slice(${base.length});\n const { languages } = window.navigator;\n const anchor = hash.slice(1);\n\n const config = ${JSON.stringify(config)};\n const availableLocales = ${JSON.stringify(availableLocales)};\n const defaultLocale = ${\n availableLocales.includes(defaultLocale)\n ? JSON.stringify(defaultLocale)\n : 'availableLocales.pop()'\n };\n const defaultBehavior = ${JSON.stringify(defaultBehavior)}\n\n let matchedLocalePath = null;\n\n // get matched locale\n findLanguage:\n for (const lang of languages)\n for (const [localePath, langs] of Object.entries(config))\n if (langs.includes(lang)) {\n${\n localeFallback\n ? `\\\n if (!availableLocales.includes(localePath))\n continue;\n`\n : ``\n}\\\n matchedLocalePath = localePath;\n break findLanguage;\n }\n\n // default link\n const defaultLink = defaultLocale? \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${defaultLocale}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`: null;\n\n // a locale matches\n if (matchedLocalePath) {\n const localeLink = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\${routePath}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`;\n\n if (availableLocales.includes(matchedLocalePath)) {\n location.href = localeLink;\n }\n // the page does not exist\n else {\n // locale homepage\n if (defaultBehavior === \"homepage\") {\n location.href = \\`\\${origin}${removeEndingSlash(\n base,\n )}\\${matchedLocalePath}\\`;\n }\n // default locale page\n else if (defaultBehavior === \"defaultLocale\" && defaultLink) {\n location.href = defaultLink;\n }\n // as is to get a 404 page of that locale\n else {\n location.href = localeLink;\n }\n }\n }\n // we have a default page\n else if (defaultLink) {\n location.href = defaultLink;\n }\n else {\n location.href = \\`\\${origin}${removeEndingSlash(base)}/404.html\\`;\n }\n </script>\n</head>\n<body>\n <p>Redirecting...</p>\n</body>\n</html>\n`\n","import { entries, removeLeadingSlash } from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { logger } from '../logger.js'\nimport { getLocaleRedirectHTML } from './getLocaleRedirectHTML.js'\n\nexport const generateAutoLocaleRedirectFiles = async (\n app: App,\n localeOptions: RedirectBehaviorConfig,\n): Promise<void> => {\n const rootPaths = new Set(\n app.pages\n .filter(({ pathLocale }) => pathLocale === '/')\n .map(({ path: pagePath }) => pagePath),\n )\n const localeRedirectMap: Record<string, string[]> = {}\n\n app.pages\n .filter(({ pathLocale }) => pathLocale !== '/')\n .forEach(({ path: pagePath, pathLocale }) => {\n const rootPath = pagePath\n .replace(pathLocale, '/')\n .replace(/\\/$/, '/index.html')\n\n if (!rootPaths.has(rootPath))\n (localeRedirectMap[rootPath] ??= []).push(pathLocale)\n })\n\n const { succeed } = logger.load('Generating locale redirect files')\n\n await Promise.all(\n entries(localeRedirectMap).map(async ([rootPath, availableLocales]) => {\n const filePath = app.dir.dest(removeLeadingSlash(rootPath))\n\n if (!fs.existsSync(filePath)) {\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(\n filePath,\n getLocaleRedirectHTML(\n localeOptions,\n availableLocales,\n app.siteData.base,\n ),\n )\n }\n }),\n )\n\n succeed()\n}\n","import {\n entries,\n isLinkAbsolute,\n isLinkHttp,\n removeEndingSlash,\n removeLeadingSlash,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { fs, path } from 'vuepress/utils'\nimport { logger } from '../logger.js'\nimport { getRedirectHTML } from './getRedirectHTML.js'\n\nexport const generateRedirectFiles = async (\n app: App,\n config: Record<string, string>,\n hostname = '',\n): Promise<void> => {\n const resolvedHostname = hostname\n ? removeEndingSlash(isLinkHttp(hostname) ? hostname : `https://${hostname}`)\n : ''\n\n const { succeed } = logger.load('Generating redirect files')\n\n await Promise.all(\n entries(config).map(async ([from, to]) => {\n const filePath = app.dir.dest(removeLeadingSlash(from))\n\n if (!fs.existsSync(filePath)) {\n const redirectUrl = isLinkAbsolute(to)\n ? `${resolvedHostname}${app.siteData.base}${removeLeadingSlash(to)}`\n : to\n\n await fs.ensureDir(path.dirname(filePath))\n await fs.writeFile(filePath, getRedirectHTML(redirectUrl))\n }\n }),\n )\n\n succeed()\n}\n","import {\n deepAssign,\n entries,\n fromEntries,\n isArray,\n isPlainObject,\n keys,\n} from '@vuepress/helper'\nimport type { App } from 'vuepress/core'\nimport { colors } from 'vuepress/utils'\nimport type { RedirectBehaviorConfig } from '../shared/index.js'\nimport { logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst AVAILABLE_FALLBACK = ['defaultLocale', 'homepage', '404'] as const\n\nexport const getRedirectBehaviorConfig = (\n app: App,\n options: RedirectPluginOptions,\n): RedirectBehaviorConfig => {\n const { locales } = app.siteData\n\n const config = deepAssign(\n fromEntries(\n entries(locales)\n .filter(([key, { lang }]) => {\n if (!lang) {\n logger.error(\n `Missing ${colors.magenta(\n 'lang',\n )} option for locale \"${key}\", this locale will be ignored!`,\n )\n\n return false\n }\n\n return true\n })\n .map(([key, { lang }]) => [key, [lang!]]),\n ),\n isPlainObject(options.localeConfig)\n ? fromEntries(\n entries(options.localeConfig).map(([routePath, lang]) => [\n routePath,\n isArray(lang) ? lang : [lang],\n ]),\n )\n : {},\n )\n\n return {\n config,\n autoLocale: options.autoLocale ?? false,\n defaultLocale: options.defaultLocale || keys(config).pop()!,\n localeFallback: options.localeFallback ?? true,\n defaultBehavior:\n options.defaultBehavior &&\n AVAILABLE_FALLBACK.includes(options.defaultBehavior)\n ? options.defaultBehavior\n : 'defaultLocale',\n }\n}\n","import {\n entries,\n fromEntries,\n isArray,\n isFunction,\n isPlainObject,\n} from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type {\n RedirectPluginFrontmatter,\n RedirectPluginOptions,\n} from './types/index.js'\n\nexport const getRedirectMap = (\n app: App,\n options: RedirectPluginOptions,\n): Record<string, string> => {\n const config = isFunction(options.config)\n ? options.config(app)\n : isPlainObject(options.config)\n ? options.config\n : {}\n\n return {\n ...fromEntries(\n (\n app.pages as Page<Record<string, never>, RedirectPluginFrontmatter>[]\n ).flatMap(({ frontmatter, path }) =>\n isArray(frontmatter.redirectFrom)\n ? frontmatter.redirectFrom.map((from) => [\n normalizePath(from, true),\n path,\n ])\n : frontmatter.redirectFrom\n ? [[normalizePath(frontmatter.redirectFrom, true), path]]\n : [],\n ),\n ),\n ...fromEntries(\n entries(config).map(([from, to]) => [\n normalizePath(from, true),\n normalizePath(to),\n ]),\n ),\n }\n}\n","import { isLinkAbsolute, removeLeadingSlash } from '@vuepress/helper'\nimport type { App, Page } from 'vuepress/core'\nimport { normalizePath } from '../shared/normalizePath.js'\nimport type { RedirectPluginFrontmatter } from './types/index.js'\n\nexport const handleRedirectTo = ({ frontmatter }: Page, app: App): void => {\n const { base } = app.siteData\n const { redirectTo } = frontmatter as RedirectPluginFrontmatter\n\n if (redirectTo) {\n const redirectUrl = normalizePath(\n isLinkAbsolute(redirectTo)\n ? `${base}${removeLeadingSlash(redirectTo)}`\n : redirectTo,\n )\n\n ;(frontmatter.head ??= []).unshift([\n 'script',\n {},\n `{\\\nconst anchor = window.location.hash.slice(1);\\\nwindow.location.replace(\\`${redirectUrl}\\${anchor? \\`#\\${anchor}\\`: \"\"}\\`);\\\n}`,\n ])\n }\n}\n","import type { DefaultLocaleInfo } from '@vuepress/helper'\nimport type { RedirectPluginLocaleData } from '../shared/index.js'\n\n/**\n * Default locale info for `@vuepress/plugin-redirect`\n */\nexport const redirectLocaleInfo: DefaultLocaleInfo<RedirectPluginLocaleData> = [\n [\n ['en', 'en-US'],\n {\n name: 'English',\n hint: 'Your primary language is $1, do you want to switch to it?',\n switch: 'Switch to $1',\n cancel: 'Cancel',\n remember: 'Remember my choice',\n },\n ],\n [\n ['zh', 'zh-CN', 'zh-Hans'],\n {\n name: '简体中文',\n hint: '你的首选语言是 $1,是否切换到该语言?',\n switch: '切换到 $1',\n cancel: '取消',\n remember: '记住我的选择',\n },\n ],\n [\n ['zh-TW', 'zh-Hant'],\n {\n name: '繁體中文',\n hint: '你的首選語言是 $1,是否切換到該語言?',\n switch: '切換到 $1',\n cancel: '取消',\n remember: '記住我的選擇',\n },\n ],\n [\n ['de', 'de-DE'],\n {\n name: 'Deutsch',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['de-AT'],\n {\n name: 'Deutsch (Österreich)',\n hint: 'Ihre bevorzugte Sprache ist $1, möchten Sie zu dieser wechseln?',\n switch: 'Zu $1 wechseln',\n cancel: 'Abbrechen',\n remember: 'Meine Wahl merken',\n },\n ],\n [\n ['vi', 'vi-VN'],\n {\n name: 'Tiếng Việt',\n hint: 'Ngôn ngữ chính của bạn là $1, bạn có muốn chuyển sang nó?',\n switch: 'Chuyển sang $1',\n cancel: 'Hủy',\n remember: 'Nhớ lựa chọn của tôi',\n },\n ],\n [\n ['uk'],\n {\n name: 'Українська',\n hint: 'Вашою основною мовою є $1, чи бажаєте ви переключитися на неї?',\n switch: 'Переключитися на $1',\n cancel: 'Скасувати',\n remember: 'Запам’ятати мій вибір',\n },\n ],\n [\n ['ru', 'ru-RU'],\n {\n name: 'Русский',\n hint: 'Ваш основной язык - $1, вы хотите переключиться на него?',\n switch: 'Переключиться на $1',\n cancel: 'Отмена',\n remember: 'Запомнить мой выбор',\n },\n ],\n [\n ['br'],\n {\n name: 'Português (Brasil)',\n hint: 'A língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n [\n ['pl', 'pl-PL'],\n {\n name: 'Polski',\n hint: 'Twoim głównym językiem jest $1, czy chcesz przełączyć się na niego?',\n switch: 'Przełącz na $1',\n cancel: 'Anuluj',\n remember: 'Zapamiętaj moje wybory',\n },\n ],\n [\n ['sk', 'sk-SK'],\n {\n name: 'Slovenčina',\n hint: 'Vašou hlavnou jazykom je $1, chcete prepnúť naň?',\n switch: 'Prepnúť na $1',\n cancel: 'Zrušiť',\n remember: 'Zapamätať si moju voľbu',\n },\n ],\n [\n ['fr', 'fr-FR'],\n {\n name: 'Français',\n hint: 'Votre langue principale est $1, voulez-vous la changer ?',\n switch: 'Changer pour $1',\n cancel: 'Annuler',\n remember: 'Se souvenir de mon choix',\n },\n ],\n [\n ['tr', 'tr-TR'],\n {\n name: 'Türkçe',\n hint: 'Ana diliniz $1, ona geçmek ister misiniz?',\n switch: \"$1'e geç\",\n cancel: 'İptal',\n remember: 'Seçimimi hatırla',\n },\n ],\n [\n ['fi', 'fi-FI'],\n {\n name: 'Suomi',\n hint: 'Pääkielenäsi on $1, haluatko vaihtaa siihen?',\n switch: 'Vaihda $1:een',\n cancel: 'Peruuta',\n remember: 'Muista valintani',\n },\n ],\n [\n ['hu', 'hu-HU'],\n {\n name: 'Magyar',\n hint: 'A fő nyelvét $1, szeretné váltani?',\n switch: 'Váltás $1',\n cancel: 'Mégse',\n remember: 'Emlékezzen a választásomra',\n },\n ],\n [\n ['id', 'id-ID'],\n {\n name: 'Bahasa Indonesia',\n hint: 'Bahasa utama Anda adalah $1, apakah Anda ingin beralih ke sana?',\n switch: 'Beralih ke $1',\n cancel: 'Batal',\n remember: 'Ingat pilihan saya',\n },\n ],\n [\n ['nl', 'nl-NL'],\n {\n name: 'Nederlands',\n hint: 'Uw primaire taal is $1, wilt u overschakelen?',\n switch: 'Overschakelen naar $1',\n cancel: 'Annuleren',\n remember: 'Onthoud mijn keuze',\n },\n ],\n [\n ['ja', 'ja-JP'],\n {\n name: '日本語',\n hint: 'あなたの主要な言語は $1 です。それに切り替えますか?',\n switch: '$1 に切り替える',\n cancel: 'キャンセル',\n remember: '選択を記憶する',\n },\n ],\n [\n ['ko', 'ko-KO'],\n {\n name: '한국어',\n hint: '당신의 기본 언어는 $1입니다. 그것으로 전환 하시겠습니까?',\n switch: '$1로 전환',\n cancel: '취소',\n remember: '내 선택 기억하기',\n },\n ],\n [\n ['es', 'es-ES'],\n {\n name: 'Español',\n hint: 'Su idioma principal es $1, ¿desea cambiarlo?',\n switch: 'Cambiar a $1',\n cancel: 'Cancelar',\n remember: 'Recordar mi elección',\n },\n ],\n [\n ['/pt'],\n {\n name: 'Português',\n hint: 'Sua língua principal é $1, deseja mudar para ela?',\n switch: 'Mudar para $1',\n cancel: 'Cancelar',\n remember: 'Lembrar minha escolha',\n },\n ],\n]\n","import {\n addViteSsrNoExternal,\n getFullLocaleConfig,\n getModulePath,\n} from '@vuepress/helper'\nimport type { PluginFunction } from 'vuepress/core'\nimport { getDirname, path } from 'vuepress/utils'\nimport { ensureRootHomePage } from './ensureRootHomePage.js'\nimport {\n generateAutoLocaleRedirectFiles,\n generateRedirectFiles,\n} from './generate/index.js'\nimport { getRedirectBehaviorConfig } from './getRedirectLocaleConfig.js'\nimport { getRedirectMap } from './getRedirectMap.js'\nimport { handleRedirectTo } from './handleRedirectTo.js'\nimport { redirectLocaleInfo } from './locales.js'\nimport { PLUGIN_NAME, logger } from './logger.js'\nimport type { RedirectPluginOptions } from './types/index.js'\n\nconst { url } = import.meta\nconst __dirname = getDirname(url)\n\nexport const redirectPlugin =\n (options: RedirectPluginOptions = {}): PluginFunction =>\n (app) => {\n if (app.env.isDebug) logger.info('Options:', options)\n\n const behaviorConfig = getRedirectBehaviorConfig(app, options)\n let redirectMap: Record<string, string> | null = null\n\n return {\n name: PLUGIN_NAME,\n\n alias: {\n '@vuepress/plugin-redirect/modal':\n options.switchLocale === 'modal'\n ? path.resolve(__dirname, '../client/components/RedirectModal.js')\n : getModulePath('@vuepress/helper/noopComponent', import.meta),\n },\n\n define: {\n __REDIRECT_CONFIG__: behaviorConfig,\n __REDIRECT_DIRECT__: options.switchLocale === 'direct',\n __REDIRECT_MODAL__: options.switchLocale === 'modal',\n __REDIRECT_LOCALES__: getFullLocaleConfig({\n app,\n name: 'redirect',\n config: options.locales,\n default: redirectLocaleInfo,\n }),\n },\n\n extendsBundlerOptions: (bundlerOptions: unknown) => {\n addViteSsrNoExternal(bundlerOptions, app, '@vuepress/helper')\n },\n\n extendsPage: (page) => {\n handleRedirectTo(page, app)\n },\n\n onInitialized: async () => {\n redirectMap = getRedirectMap(app, options)\n\n if (app.env.isDebug) logger.info('Redirect Map:', redirectMap)\n\n if (options.autoLocale && app.env.isDebug) await ensureRootHomePage(app)\n },\n\n onPrepared: async () => {\n await app.writeTemp(\n 'redirect/map.js',\n `\\\nexport const redirectMap = ${\n app.env.isDev ? JSON.stringify(redirectMap, null, 2) : '{}'\n };\n`,\n )\n // clean redirectMap reference in dev server\n if (app.env.isDev) redirectMap = null\n },\n\n onGenerated: async () => {\n await generateRedirectFiles(app, redirectMap!)\n if (options.autoLocale)\n await generateAutoLocaleRedirectFiles(app, behaviorConfig)\n },\n\n clientConfigFile: path.join(__dirname, '../client/config.js'),\n }\n }\n"],"mappings":"+fAGA,MAAa,EAAqB,KAAO,IAA4B,CAGjE,EAAI,MAAM,OAAO,CAAE,UAAW,IAAS,IAAI,EAE3C,EAAI,MAAM,KACR,MAAM,EAAW,EAAK,CACpB,KAAM,IACN,YAAa,CAAE,MAAO,OAAQ,CAE9B,QAAS;EAGV,CAAC,CACH,ECfQ,EAAc,4BAEdA,EAAS,IAAI,EAAO,EAAY,CCDhC,GACX,CACE,SACA,kBACA,gBACA,kBAEF,EACA,IACW;;;;;;;;uCAQ0B,EAAK,OAAO;;;;qBAI9B,KAAK,UAAU,EAAO,CAAC;+BACb,KAAK,UAAU,EAAiB,CAAC;4BAE1D,EAAiB,SAAS,EAAc,CACpC,KAAK,UAAU,EAAc,CAC7B,yBACL;8BACyB,KAAK,UAAU,EAAgB,CAAC;;;;;;;;;EAU5D,EACI;;EAIA,GACL;;;;;;qDAMoD,EAC/C,EACD,CAAC;;;;uCAIiC,EAC/B,EACD,CAAC;;;;;;;;;wCASgC,EAC5B,EACD,CAAC;;;;;;;;;;;;;;;;;oCAiBwB,EAAkB,EAAK,CAAC;;;;;;;;EClF/C,EAAkC,MAC7C,EACA,IACkB,CAClB,IAAM,EAAY,IAAI,IACpB,EAAI,MACD,QAAQ,CAAE,gBAAiB,IAAe,IAAI,CAC9C,KAAK,CAAE,KAAM,KAAe,EAAS,CACzC,CACK,EAA8C,EAAE,CAEtD,EAAI,MACD,QAAQ,CAAE,gBAAiB,IAAe,IAAI,CAC9C,SAAS,CAAE,KAAM,EAAU,gBAAi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EAAK,QAAQ,EAAW,wCAAwC,CAChE,EAAc,iCAAkC,OAAO,KAAK,CACnE,CAED,OAAQ,CACN,oBAAqB,EACrB,oBAAqB,EAAQ,eAAiB,SAC9C,mBAAoB,EAAQ,eAAiB,QAC7C,qBAAsB,EAAoB,CACxC,MACA,KAAM,WACN,OAAQ,EAAQ,QAChB,QAAS,EACV,CAAC,CACH,CAED,sBAAwB,GAA4B,CAClD,EAAqB,EAAgB,EAAK,mBAAmB,EAG/D,YAAc,GAAS,CACrB,EAAiB,EAAM,EAAI,EAG7B,cAAe,SAAY,CACzB,EAAc,EAAe,EAAK,EAAQ,CAEtC,EAAI,IAAI,SAAS,EAAO,KAAK,gBAAiB,EAAY,CAE1D,EAAQ,YAAc,EAAI,IAAI,SAAS,MAAM,EAAmB,EAAI,EAG1E,WAAY,SAAY,CACtB,MAAM,EAAI,UACR,kBACA;6BAEE,EAAI,IAAI,MAAQ,KAAK,UAAU,EAAa,KAAM,EAAE,CAAG,KACxD;EAEF,CAEG,EAAI,IAAI,QAAO,EAAc,OAGnC,YAAa,SAAY,CACvB,MAAM,EAAsB,EAAK,EAAa,CAC1C,EAAQ,YACV,MAAM,EAAgC,EAAK,EAAe,EAG9D,iBAAkB,EAAK,KAAK,EAAW,sBAAsB,CAC9D"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalizePath-DCapcto5.js","names":[],"sources":["../src/shared/normalizePath.ts"],"sourcesContent":["const HASH_REGEXP = /#.*$/u\n\nexport const normalizePath = (path: string, removeHash = false): string =>\n (removeHash ? path.replace(HASH_REGEXP, '') : path)\n .replace(/\\/(?:README\\.md)?$/i, '/index.html')\n .replace(/(?:\\.(?:md|html))?$/, '.html')\n"],"mappings":"AAAA,MAAM,EAAc,QAEP,GAAiB,EAAc,EAAa,MACtD,EAAa,EAAK,QAAQ,EAAa,GAAG,CAAG,GAC3C,QAAQ,sBAAuB,cAAc,CAC7C,QAAQ,sBAAuB,QAAQ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./normalizePath-DCapcto5.js";import{r as t,t as n}from"./useRedirectInfo-BhfN7KrZ.js";import{usePreferredLanguages as r,watchImmediate as i}from"@vueuse/core";import{computed as a,onMounted as o}from"vue";import{useData as s,useRoute as c,useRouteLocale as l,useRoutePath as u,useRouter as d}from"vuepress/client";import{redirectMap as f}from"@temp/redirect/map.js";import{entries as p,isLinkHttp as m}from"@vuepress/helper/client";const h=({autoLocale:t,config:n,defaultBehavior:o,defaultLocale:s,localeFallback:h})=>{let g=Object.entries(n),_=r(),v=c(),y=d(),b=l(),x=u(),S=a(()=>b.value===`/`),C=()=>{let e=x.value,t=y.getRoutes(),n=s&&t.some(({path:t})=>t===e.replace(`/`,s))?s:t.find(({path:t})=>e.split(`/`).length>=3&&t===e.replace(/^\/[^/]+\//,`/`))?.path,r=null;findLanguage:for(let n of _.value)for(let[i,a]of g)if(a.includes(n)){if(h&&t.every(({path:t})=>t!==e.replace(`/`,t)))continue;r=i;break findLanguage}let i=n?v.fullPath.replace(`/`,n):null;if(r){let n=t.some(({path:t})=>e.replace(`/`,r)===t),a=v.fullPath.replace(`/`,r),s=n?a:o===`homepage`?r:o===`defaultLocale`&&i?i:a;y.replace(s)}else i?y.replace(i):x.value!==`/404.html`&&y.replace(`/404.html`)};i(x,n=>{for(let[t,r]of p(f))if(e(n.toLowerCase())===t.toLowerCase()){m(r)?window.open(r):y.replace(r);return}t&&S.value&&C()})},g=e=>{let{routeLocale:r,routePath:i}=s(),a=d(),c=n(e);o(()=>{c.value&&!t.value[r.value]&&(a.replace(i.value.replace(r.value,c.value.localePath)),t.value[r.value]=!0)})};export{h as n,g as t};
|
|
2
|
+
//# sourceMappingURL=setupRedirect-DB0Ip2i-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setupRedirect-DB0Ip2i-.js","names":[],"sources":["../src/client/composables/setupDevServerRedirect.ts","../src/client/composables/setupRedirect.ts"],"sourcesContent":["import { redirectMap } from '@temp/redirect/map.js'\nimport { entries, isLinkHttp } from '@vuepress/helper/client'\nimport { usePreferredLanguages, watchImmediate } from '@vueuse/core'\nimport { computed } from 'vue'\nimport {\n useRoute,\n useRouteLocale,\n useRoutePath,\n useRouter,\n} from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { normalizePath } from '../../shared/index.js'\n\nexport const setupDevServerRedirect = ({\n autoLocale,\n config,\n defaultBehavior,\n defaultLocale: defaultLocalePath,\n localeFallback,\n}: RedirectBehaviorConfig): void => {\n const localeEntries = Object.entries(config)\n const languages = usePreferredLanguages()\n const route = useRoute()\n const router = useRouter()\n const routeLocale = useRouteLocale()\n const routePath = useRoutePath()\n\n const isRootLocale = computed(() => routeLocale.value === '/')\n\n const handleLocaleRedirect = (): void => {\n const routePathValue = routePath.value\n const routes = router.getRoutes()\n const defaultLocale =\n defaultLocalePath &&\n routes.some(\n ({ path }) => path === routePathValue.replace('/', defaultLocalePath),\n )\n ? defaultLocalePath\n : routes.find(\n ({ path }) =>\n routePathValue.split('/').length >= 3 &&\n path === routePathValue.replace(/^\\/[^/]+\\//, '/'),\n )?.path\n\n let matchedLocalePath: string | null = null\n\n // get matched locale\n // oxlint-disable-next-line no-labels\n findLanguage: for (const lang of languages.value) {\n for (const [localePath, langs] of localeEntries) {\n if (langs.includes(lang)) {\n if (\n localeFallback &&\n routes.every(\n ({ path }) => path !== routePathValue.replace('/', path),\n )\n )\n continue\n\n matchedLocalePath = localePath\n // oxlint-disable-next-line no-labels\n break findLanguage\n }\n }\n }\n\n // default link\n const defaultRoute = defaultLocale\n ? route.fullPath.replace('/', defaultLocale)\n : null\n\n // a locale matches\n if (matchedLocalePath) {\n const hasLocalePage = routes.some(\n ({ path }) => routePathValue.replace('/', matchedLocalePath) === path,\n )\n const localeRoute = route.fullPath.replace('/', matchedLocalePath)\n\n const redirectPath =\n // the locale page exists\n hasLocalePage\n ? localeRoute\n : // the page does not exist\n defaultBehavior === 'homepage'\n ? // locale homepage\n matchedLocalePath\n : defaultBehavior === 'defaultLocale' && defaultRoute\n ? // default locale page\n defaultRoute\n : // as is to get a 404 page of that locale\n localeRoute\n\n void router.replace(redirectPath)\n }\n // we have a default page\n else if (defaultRoute) {\n void router.replace(defaultRoute)\n } else if (routePath.value !== '/404.html') {\n void router.replace('/404.html')\n }\n }\n\n watchImmediate(routePath, (path) => {\n // handle redirects\n for (const [from, to] of entries(redirectMap)) {\n if (normalizePath(path.toLowerCase()) === from.toLowerCase()) {\n if (isLinkHttp(to)) window.open(to)\n else void router.replace(to)\n\n return\n }\n }\n\n if (autoLocale && isRootLocale.value) handleLocaleRedirect()\n })\n}\n","import { onMounted } from 'vue'\nimport { useData, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { statusSessionStorage } from '../utils/index.js'\nimport { useRedirectInfo } from './useRedirectInfo.js'\n\nexport interface LocaleInfo {\n lang: string\n localePath: string\n}\n\nexport const setupRedirect = (behaviorConfig: RedirectBehaviorConfig): void => {\n const { routeLocale, routePath } = useData()\n const router = useRouter()\n const redirectInfo = useRedirectInfo(behaviorConfig)\n\n onMounted(() => {\n if (redirectInfo.value && !statusSessionStorage.value[routeLocale.value]) {\n void router.replace(\n routePath.value.replace(\n routeLocale.value,\n redirectInfo.value.localePath,\n ),\n )\n statusSessionStorage.value[routeLocale.value] = true\n }\n })\n}\n"],"mappings":"mcAaA,MAAa,GAA0B,CACrC,aACA,SACA,kBACA,cAAe,EACf,oBACkC,CAClC,IAAM,EAAgB,OAAO,QAAQ,EAAO,CACtC,EAAY,GAAuB,CACnC,EAAQ,GAAU,CAClB,EAAS,GAAW,CACpB,EAAc,GAAgB,CAC9B,EAAY,GAAc,CAE1B,EAAe,MAAe,EAAY,QAAU,IAAI,CAExD,MAAmC,CACvC,IAAM,EAAiB,EAAU,MAC3B,EAAS,EAAO,WAAW,CAC3B,EACJ,GACA,EAAO,MACJ,CAAE,UAAW,IAAS,EAA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CACD,EAAqB,MAAM,EAAY,OAAS,KAElD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useLocalStorage as e,usePreferredLanguages as t,useSessionStorage as n}from"@vueuse/core";import{computed as r}from"vue";import{useRouteLocale as i}from"vuepress/client";import{entries as a}from"@vuepress/helper/client";const o=`VUEPRESS_REDIRECT_STATUS`,s=e(o,{}),c=n(o,{}),l=e=>{let n=t(),o=i(),s=a(e.config);return r(()=>{if(s.some(([e])=>o.value===e)){for(let e of n.value)for(let[t,n]of s)if(n.includes(e))return t===o.value?null:{lang:e,localePath:t}}return null})};export{s as n,c as r,l as t};
|
|
2
|
+
//# sourceMappingURL=useRedirectInfo-BhfN7KrZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRedirectInfo-BhfN7KrZ.js","names":[],"sources":["../src/client/utils/storage.ts","../src/client/composables/useRedirectInfo.ts"],"sourcesContent":["import { useLocalStorage, useSessionStorage } from '@vueuse/core'\n\nconst REDIRECT_STORAGE_KEY = 'VUEPRESS_REDIRECT_STATUS'\n\nexport const statusLocalStorage = useLocalStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n\nexport const statusSessionStorage = useSessionStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n","import { entries } from '@vuepress/helper/client'\nimport { usePreferredLanguages } from '@vueuse/core'\nimport type { ComputedRef } from 'vue'\nimport { computed } from 'vue'\nimport { useRouteLocale } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport interface RedirectInfo {\n lang: string\n localePath: string\n}\n\nexport const useRedirectInfo = (\n behaviorConfig: RedirectBehaviorConfig,\n): ComputedRef<RedirectInfo | null> => {\n const languages = usePreferredLanguages()\n const routeLocale = useRouteLocale()\n\n const localeEntries = entries(behaviorConfig.config)\n\n return computed(() => {\n if (localeEntries.some(([key]) => routeLocale.value === key)) {\n for (const language of languages.value) {\n for (const [localePath, langs] of localeEntries) {\n if (langs.includes(language)) {\n // oxlint-disable-next-line max-depth\n if (localePath === routeLocale.value) return null\n\n return {\n lang: language,\n localePath,\n }\n }\n }\n }\n }\n\n return null\n })\n}\n"],"mappings":"mOAEA,MAAM,EAAuB,2BAEhB,EAAqB,EAChC,EACA,EAAE,CACH,CAEY,EAAuB,EAClC,EACA,EAAE,CACH,CCAY,EACX,GACqC,CACrC,IAAM,EAAY,GAAuB,CACnC,EAAc,GAAgB,CAE9B,EAAgB,EAAQ,EAAe,OAAO,CAEpD,OAAO,MAAe,CACpB,GAAI,EAAc,MAAM,CAAC,KAAS,EAAY,QAAU,EAAI,MACrD,IAAM,KAAY,EAAU,MAC/B,IAAK,GAAM,CAAC,EAAY,KAAU,EAChC,GAAI,EAAM,SAAS,EAAS,CAI1B,OAFI,IAAe,EAAY,MAAc,KAEtC,CACL,KAAM,EACN,aACD,CAMT,OAAO,MACP"}
|
package/package.json
CHANGED
|
@@ -1,53 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vuepress/plugin-redirect",
|
|
3
|
-
"version": "2.0.0-rc.
|
|
3
|
+
"version": "2.0.0-rc.124",
|
|
4
4
|
"description": "VuePress plugin - redirect",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"vuepress-plugin",
|
|
7
|
-
"vuepress",
|
|
8
6
|
"plugin",
|
|
9
|
-
"redirect"
|
|
7
|
+
"redirect",
|
|
8
|
+
"vuepress",
|
|
9
|
+
"vuepress-plugin"
|
|
10
10
|
],
|
|
11
11
|
"homepage": "https://ecosystem.vuejs.press/plugins/tools/redirect.html",
|
|
12
12
|
"bugs": {
|
|
13
13
|
"url": "https://github.com/vuepress/ecosystem/issues"
|
|
14
14
|
},
|
|
15
|
-
"repository": {
|
|
16
|
-
"type": "git",
|
|
17
|
-
"url": "git+https://github.com/vuepress/ecosystem.git",
|
|
18
|
-
"directory": "plugins/tools/plugin-redirect"
|
|
19
|
-
},
|
|
20
15
|
"license": "MIT",
|
|
21
16
|
"author": {
|
|
22
17
|
"name": "Mr.Hope",
|
|
23
18
|
"email": "mister-hope@outlook.com",
|
|
24
19
|
"url": "https://mister-hope.com"
|
|
25
20
|
},
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"./package.json": "./package.json"
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/vuepress/ecosystem.git",
|
|
24
|
+
"directory": "plugins/tools/plugin-redirect"
|
|
31
25
|
},
|
|
32
|
-
"main": "./lib/node/index.js",
|
|
33
|
-
"types": "./lib/node/index.d.ts",
|
|
34
26
|
"bin": {
|
|
35
27
|
"vp-redirect": "./lib/cli/index.js"
|
|
36
28
|
},
|
|
37
29
|
"files": [
|
|
38
30
|
"lib"
|
|
39
31
|
],
|
|
32
|
+
"type": "module",
|
|
33
|
+
"sideEffects": [
|
|
34
|
+
"./lib/client/styles/**/*.css"
|
|
35
|
+
],
|
|
36
|
+
"exports": {
|
|
37
|
+
".": {
|
|
38
|
+
"types": "./lib/node/index.d.ts",
|
|
39
|
+
"default": "./lib/node/index.js"
|
|
40
|
+
},
|
|
41
|
+
"./client": {
|
|
42
|
+
"types": "./lib/client/index.d.ts",
|
|
43
|
+
"default": "./lib/client/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./package.json": "./package.json"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
40
50
|
"dependencies": {
|
|
41
|
-
"@vuepress/helper": "2.0.0-rc.
|
|
42
|
-
"@vueuse/core": "^14.2.
|
|
51
|
+
"@vuepress/helper": "2.0.0-rc.124",
|
|
52
|
+
"@vueuse/core": "^14.2.1",
|
|
43
53
|
"commander": "^14.0.3",
|
|
44
|
-
"vue": "^3.5.
|
|
54
|
+
"vue": "^3.5.29"
|
|
45
55
|
},
|
|
46
56
|
"peerDependencies": {
|
|
47
57
|
"vuepress": "2.0.0-rc.26"
|
|
48
58
|
},
|
|
49
|
-
"
|
|
50
|
-
"access": "public"
|
|
51
|
-
},
|
|
52
|
-
"gitHead": "5dfd2d24f8335f718182701995420907b0a00905"
|
|
59
|
+
"gitHead": "f17e7479b1ef3c06814b6107df9188ba351702da"
|
|
53
60
|
}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
interface RedirectBehaviorOptions {
|
|
2
|
-
/**
|
|
3
|
-
* Whether enable locales redirection
|
|
4
|
-
*
|
|
5
|
-
* 是否启用语言重定向
|
|
6
|
-
*
|
|
7
|
-
* @default false
|
|
8
|
-
*/
|
|
9
|
-
autoLocale?: boolean;
|
|
10
|
-
/**
|
|
11
|
-
* Whether fallback to other locales user defined
|
|
12
|
-
*
|
|
13
|
-
* 是否回退到用户定义的其他语言
|
|
14
|
-
*
|
|
15
|
-
* @default true
|
|
16
|
-
*/
|
|
17
|
-
localeFallback?: boolean;
|
|
18
|
-
/**
|
|
19
|
-
* Behavior when a locale version is not available for current link
|
|
20
|
-
*
|
|
21
|
-
* @description `"homepage"` and `"404"` is only available when a locale is assigned to current language
|
|
22
|
-
*
|
|
23
|
-
* 当前链接没有可用的语言版本时的行为
|
|
24
|
-
*
|
|
25
|
-
* @description 只有当语言分配给当前语言时,`"homepage"` 和 `"404"` 才可用
|
|
26
|
-
*
|
|
27
|
-
* @default "defaultLocale"
|
|
28
|
-
*/
|
|
29
|
-
defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
|
|
30
|
-
/**
|
|
31
|
-
* Default locale path
|
|
32
|
-
*
|
|
33
|
-
* @description the first locale will be used if absent
|
|
34
|
-
*
|
|
35
|
-
* 默认语言路径
|
|
36
|
-
*
|
|
37
|
-
* @description 如果缺失,则使用第一个语言
|
|
38
|
-
*/
|
|
39
|
-
defaultLocale?: string;
|
|
40
|
-
}
|
|
41
|
-
interface RedirectBehaviorConfig extends Required<RedirectBehaviorOptions> {
|
|
42
|
-
/**
|
|
43
|
-
* Locale language config
|
|
44
|
-
*
|
|
45
|
-
* 多语言语言配置
|
|
46
|
-
*/
|
|
47
|
-
config: Record<string, string[]>;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export type { RedirectBehaviorConfig as R };
|
package/lib/client/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{redirectMap as D}from"@temp/redirect/map.js";import{entries as M,isLinkHttp as S}from"@vuepress/helper/client";import{usePreferredLanguages as $,watchImmediate as x}from"@vueuse/core";import{computed as C,onMounted as E}from"vue";import{useRoute as I,useRouter as L,useRouteLocale as j,useRoutePath as y,useData as z}from"vuepress/client";import{u as A,s as R}from"./useRedirectInfo-BzhIENgm.js";const B=/#.*$/u,F=(o,e=!1)=>(e?o.replace(B,""):o).replace(/\/(?:README\.md)?$/i,"/index.html").replace(/(?:\.(?:md|html))?$/,".html"),H=({autoLocale:o,config:e,defaultBehavior:p,defaultLocale:u,localeFallback:n})=>{const P=Object.entries(e),g=$(),d=I(),c=L(),w=j(),h=y(),b=C(()=>w.value==="/"),k=()=>{const t=h.value,l=c.getRoutes(),r=u&&l.some(({path:a})=>a===t.replace("/",u))?u:l.find(({path:a})=>t.split("/").length>=3&&a===t.replace(/^\/[^/]+\//,"/"))?.path;let s=null;e:for(const a of g.value)for(const[f,v]of P)if(v.includes(a)){if(n&&l.every(({path:m})=>m!==t.replace("/",m)))continue;s=f;break e}const i=r?d.fullPath.replace("/",r):null;if(s){const a=l.some(({path:m})=>t.replace("/",s)===m),f=d.fullPath.replace("/",s),v=a?f:p==="homepage"?s:p==="defaultLocale"&&i?i:f;c.replace(v)}else i?c.replace(i):h.value!=="/404.html"&&c.replace("/404.html")};x(h,t=>{for(const[l,r]of M(D))if(F(t.toLowerCase())===l.toLowerCase()){S(r)?window.open(r):c.replace(r);return}o&&b.value&&k()})},O=o=>{const{routeLocale:e,routePath:p}=z(),u=L(),n=A(o);E(()=>{n.value&&!R.value[e.value]&&(u.replace(p.value.replace(e.value,n.value.localePath)),R.value[e.value]=!0)})};export{O as a,H as s};
|
|
2
|
-
//# sourceMappingURL=setupRedirect-BBJERz7T.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"setupRedirect-BBJERz7T.js","sources":["../../src/shared/normalizePath.ts","../../src/client/composables/setupDevServerRedirect.ts","../../src/client/composables/setupRedirect.ts"],"sourcesContent":["const HASH_REGEXP = /#.*$/u\n\nexport const normalizePath = (path: string, removeHash = false): string =>\n (removeHash ? path.replace(HASH_REGEXP, '') : path)\n .replace(/\\/(?:README\\.md)?$/i, '/index.html')\n .replace(/(?:\\.(?:md|html))?$/, '.html')\n","import { redirectMap } from '@temp/redirect/map.js'\nimport { entries, isLinkHttp } from '@vuepress/helper/client'\nimport { usePreferredLanguages, watchImmediate } from '@vueuse/core'\nimport { computed } from 'vue'\nimport {\n useRoute,\n useRouteLocale,\n useRoutePath,\n useRouter,\n} from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { normalizePath } from '../../shared/index.js'\n\nexport const setupDevServerRedirect = ({\n autoLocale,\n config,\n defaultBehavior,\n defaultLocale: defaultLocalePath,\n localeFallback,\n}: RedirectBehaviorConfig): void => {\n const localeEntries = Object.entries(config)\n const languages = usePreferredLanguages()\n const route = useRoute()\n const router = useRouter()\n const routeLocale = useRouteLocale()\n const routePath = useRoutePath()\n\n const isRootLocale = computed(() => routeLocale.value === '/')\n\n const handleLocaleRedirect = (): void => {\n const routePathValue = routePath.value\n const routes = router.getRoutes()\n const defaultLocale =\n defaultLocalePath &&\n routes.some(\n ({ path }) => path === routePathValue.replace('/', defaultLocalePath),\n )\n ? defaultLocalePath\n : routes.find(\n ({ path }) =>\n routePathValue.split('/').length >= 3 &&\n path === routePathValue.replace(/^\\/[^/]+\\//, '/'),\n )?.path\n\n let matchedLocalePath: string | null = null\n\n // get matched locale\n // eslint-disable-next-line no-restricted-syntax\n findLanguage: for (const lang of languages.value)\n for (const [localePath, langs] of localeEntries)\n if (langs.includes(lang)) {\n if (\n localeFallback &&\n routes.every(\n ({ path }) => path !== routePathValue.replace('/', path),\n )\n )\n continue\n\n matchedLocalePath = localePath\n break findLanguage\n }\n\n // default link\n const defaultRoute = defaultLocale\n ? route.fullPath.replace('/', defaultLocale)\n : null\n\n // a locale matches\n if (matchedLocalePath) {\n const hasLocalePage = routes.some(\n ({ path }) => routePathValue.replace('/', matchedLocalePath) === path,\n )\n const localeRoute = route.fullPath.replace('/', matchedLocalePath)\n\n const redirectPath =\n // the locale page exists\n hasLocalePage\n ? localeRoute\n : // the page does not exist\n defaultBehavior === 'homepage'\n ? // locale homepage\n matchedLocalePath\n : defaultBehavior === 'defaultLocale' && defaultRoute\n ? // default locale page\n defaultRoute\n : // as is to get a 404 page of that locale\n localeRoute\n\n router.replace(redirectPath)\n }\n // we have a default page\n else if (defaultRoute) {\n router.replace(defaultRoute)\n } else if (routePath.value !== '/404.html') {\n router.replace('/404.html')\n }\n }\n\n watchImmediate(routePath, (path) => {\n // handle redirects\n for (const [from, to] of entries(redirectMap))\n if (normalizePath(path.toLowerCase()) === from.toLowerCase()) {\n if (isLinkHttp(to)) window.open(to)\n else router.replace(to)\n\n return\n }\n\n if (autoLocale && isRootLocale.value) handleLocaleRedirect()\n })\n}\n","import { onMounted } from 'vue'\nimport { useData, useRouter } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\nimport { statusSessionStorage } from '../utils/index.js'\nimport { useRedirectInfo } from './useRedirectInfo.js'\n\nexport interface LocaleInfo {\n lang: string\n localePath: string\n}\n\nexport const setupRedirect = (behaviorConfig: RedirectBehaviorConfig): void => {\n const { routeLocale, routePath } = useData()\n const router = useRouter()\n const redirectInfo = useRedirectInfo(behaviorConfig)\n\n onMounted(() => {\n if (redirectInfo.value && !statusSessionStorage.value[routeLocale.value]) {\n router.replace(\n routePath.value.replace(\n routeLocale.value,\n redirectInfo.value.localePath,\n ),\n )\n statusSessionStorage.value[routeLocale.value] = true\n }\n })\n}\n"],"names":["HASH_REGEXP","normalizePath","path","removeHash","setupDevServerRedirect","autoLocale","config","defaultBehavior","defaultLocalePath","localeFallback","localeEntries","languages","usePreferredLanguages","route","useRoute","router","useRouter","routeLocale","useRouteLocale","routePath","useRoutePath","isRootLocale","computed","handleLocaleRedirect","routePathValue","routes","defaultLocale","matchedLocalePath","findLanguage","lang","localePath","langs","defaultRoute","hasLocalePage","localeRoute","redirectPath","watchImmediate","from","to","entries","redirectMap","isLinkHttp","setupRedirect","behaviorConfig","useData","redirectInfo","useRedirectInfo","onMounted","statusSessionStorage"],"mappings":"mZAAA,MAAMA,EAAc,QAEPC,EAAgB,CAACC,EAAcC,EAAa,MACtDA,EAAaD,EAAK,QAAQF,EAAa,EAAE,EAAIE,GAC3C,QAAQ,sBAAuB,aAAa,EAC5C,QAAQ,sBAAuB,OAAO,ECQ9BE,EAAyB,CAAC,CACrC,WAAAC,EACA,OAAAC,EACA,gBAAAC,EACA,cAAeC,EACf,eAAAC,CACF,IAAoC,CAClC,MAAMC,EAAgB,OAAO,QAAQJ,CAAM,EACrCK,EAAYC,EAAAA,EACZC,EAAQC,EAAAA,EACRC,EAASC,EAAAA,EACTC,EAAcC,IACdC,EAAYC,EAAAA,EAEZC,EAAeC,EAAS,IAAML,EAAY,QAAU,GAAG,EAEvDM,EAAuB,IAAY,CACvC,MAAMC,EAAiBL,EAAU,MAC3BM,EAASV,EAAO,YAChBW,EACJlB,GACAiB,EAAO,KACL,CAAC,CAAE,KAAAvB,CAAK,IAAMA,IAASsB,EAAe,QAAQ,IAAKhB,CAAiB,CACtE,EACIA,EACAiB,EAAO,KACL,CAAC,CAAE,KAAAvB,CAAK,IACNsB,EAAe,MAAM,GAAG,EAAE,QAAU,GACpCtB,IAASsB,EAAe,QAAQ,aAAc,GAAG,CACrD,GAAG,KAET,IAAIG,EAAmC,KAIvCC,EAAc,UAAWC,K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,QACdF,EAAY,MACZ4B,EAAa,MAAM,UACrB,CACF,EACAG,EAAqB,MAAM/B,EAAY,KAAK,EAAI,GAEpD,CAAC,CACH"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{useSessionStorage as c,useLocalStorage as l,usePreferredLanguages as f}from"@vueuse/core";import{entries as i}from"@vuepress/helper/client";import{computed as m}from"vue";import{useRouteLocale as S}from"vuepress/client";const s="VUEPRESS_REDIRECT_STATUS",g=l(s,{}),p=c(s,{}),R=a=>{const u=f(),e=S(),t=i(a.config);return m(()=>{if(t.some(([o])=>e.value===o)){for(const o of u.value)for(const[r,n]of t)if(n.includes(o))return r===e.value?null:{lang:o,localePath:r}}return null})};export{g as a,p as s,R as u};
|
|
2
|
-
//# sourceMappingURL=useRedirectInfo-BzhIENgm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useRedirectInfo-BzhIENgm.js","sources":["../../src/client/utils/storage.ts","../../src/client/composables/useRedirectInfo.ts"],"sourcesContent":["import { useLocalStorage, useSessionStorage } from '@vueuse/core'\n\nconst REDIRECT_STORAGE_KEY = 'VUEPRESS_REDIRECT_STATUS'\n\nexport const statusLocalStorage = useLocalStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n\nexport const statusSessionStorage = useSessionStorage<Record<string, boolean>>(\n REDIRECT_STORAGE_KEY,\n {},\n)\n","import { entries } from '@vuepress/helper/client'\nimport { usePreferredLanguages } from '@vueuse/core'\nimport type { ComputedRef } from 'vue'\nimport { computed } from 'vue'\nimport { useRouteLocale } from 'vuepress/client'\nimport type { RedirectBehaviorConfig } from '../../shared/index.js'\n\nexport interface RedirectInfo {\n lang: string\n localePath: string\n}\n\nexport const useRedirectInfo = (\n behaviorConfig: RedirectBehaviorConfig,\n): ComputedRef<RedirectInfo | null> => {\n const languages = usePreferredLanguages()\n const routeLocale = useRouteLocale()\n\n const localeEntries = entries(behaviorConfig.config)\n\n return computed(() => {\n if (localeEntries.some(([key]) => routeLocale.value === key))\n for (const language of languages.value)\n for (const [localePath, langs] of localeEntries)\n if (langs.includes(language)) {\n if (localePath === routeLocale.value) return null\n\n return {\n lang: language,\n localePath,\n }\n }\n\n return null\n })\n}\n"],"names":["REDIRECT_STORAGE_KEY","statusLocalStorage","useLocalStorage","statusSessionStorage","useSessionStorage","useRedirectInfo","behaviorConfig","languages","usePreferredLanguages","routeLocale","useRouteLocale","localeEntries","entries","computed","key","language","localePath","langs"],"mappings":"mOAEA,MAAMA,EAAuB,2BAEhBC,EAAqBC,EAChCF,EACA,CAAA,CACF,EAEaG,EAAuBC,EAClCJ,EACA,CAAA,CACF,ECAaK,EACXC,GACqC,CACrC,MAAMC,EAAYC,EAAAA,EACZC,EAAcC,IAEdC,EAAgBC,EAAQN,EAAe,MAAM,EAEnD,OAAOO,EAAS,IAAM,CACpB,GAAIF,EAAc,KAAK,CAAC,CAACG,CAAG,IAAML,EAAY,QAAUK,CAAG,GACzD,UAAWC,KAAYR,EAAU,MAC/B,SAAW,CAACS,EAAYC,CAAK,IAAKN,EAChC,GAAIM,EAAM,SAASF,CAAQ,EACzB,OAAIC,IAAeP,EAAY,MAAc,KAEtC,CACL,KAAMM,EACN,WAAAC,CACF,EAGR,OAAO,IACT,CAAC,CACH"}
|