@vuepress/plugin-redirect 2.0.0-rc.12 → 2.0.0-rc.121

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.
Files changed (71) hide show
  1. package/lib/cli/index.js +19 -73
  2. package/lib/cli/index.js.map +1 -0
  3. package/lib/{shared/localeConfig.d.ts → client/behavior-BgEQhx7R.d.ts} +15 -19
  4. package/lib/client/components/RedirectModal.d.ts +61 -0
  5. package/lib/client/components/RedirectModal.js +2 -0
  6. package/lib/client/components/RedirectModal.js.map +1 -0
  7. package/lib/client/config.d.ts +7 -4
  8. package/lib/client/config.js +2 -11
  9. package/lib/client/config.js.map +1 -0
  10. package/lib/client/index.d.ts +21 -0
  11. package/lib/client/index.js +2 -0
  12. package/lib/client/index.js.map +1 -0
  13. package/lib/client/setupRedirect-BBJERz7T.js +2 -0
  14. package/lib/client/setupRedirect-BBJERz7T.js.map +1 -0
  15. package/lib/client/styles/redirect-modal.css +1 -0
  16. package/lib/client/styles/redirect-modal.css.map +1 -0
  17. package/lib/client/styles/vars.css +1 -10
  18. package/lib/client/styles/vars.css.map +1 -0
  19. package/lib/client/useRedirectInfo-BzhIENgm.js +2 -0
  20. package/lib/client/useRedirectInfo-BzhIENgm.js.map +1 -0
  21. package/lib/node/index.d.ts +113 -2
  22. package/lib/node/index.js +90 -1
  23. package/lib/node/index.js.map +1 -0
  24. package/package.json +10 -15
  25. package/lib/cli/index.d.ts +0 -2
  26. package/lib/client/components/LanguageSwitch.d.ts +0 -4
  27. package/lib/client/components/LanguageSwitch.js +0 -99
  28. package/lib/client/composables/index.d.ts +0 -1
  29. package/lib/client/composables/index.js +0 -1
  30. package/lib/client/composables/setupDevServerRedirect.d.ts +0 -1
  31. package/lib/client/composables/setupDevServerRedirect.js +0 -80
  32. package/lib/client/define.d.ts +0 -3
  33. package/lib/client/define.js +0 -3
  34. package/lib/client/styles/language-switch.css +0 -57
  35. package/lib/node/ensureRootHomePage.d.ts +0 -2
  36. package/lib/node/ensureRootHomePage.js +0 -15
  37. package/lib/node/generate/generateAutoLocaleRedirectFiles.d.ts +0 -3
  38. package/lib/node/generate/generateAutoLocaleRedirectFiles.js +0 -28
  39. package/lib/node/generate/generateRedirectFiles.d.ts +0 -2
  40. package/lib/node/generate/generateRedirectFiles.js +0 -21
  41. package/lib/node/generate/getLocaleRedirectHTML.d.ts +0 -2
  42. package/lib/node/generate/getLocaleRedirectHTML.js +0 -77
  43. package/lib/node/generate/getRedirectHTML.d.ts +0 -1
  44. package/lib/node/generate/getRedirectHTML.js +0 -18
  45. package/lib/node/generate/index.d.ts +0 -2
  46. package/lib/node/generate/index.js +0 -2
  47. package/lib/node/getRedirectLocaleConfig.d.ts +0 -4
  48. package/lib/node/getRedirectLocaleConfig.js +0 -35
  49. package/lib/node/getRedirectMap.d.ts +0 -3
  50. package/lib/node/getRedirectMap.js +0 -25
  51. package/lib/node/handleRedirectTo.d.ts +0 -2
  52. package/lib/node/handleRedirectTo.js +0 -19
  53. package/lib/node/locales.d.ts +0 -3
  54. package/lib/node/locales.js +0 -129
  55. package/lib/node/logger.d.ts +0 -3
  56. package/lib/node/logger.js +0 -3
  57. package/lib/node/redirectPlugin.d.ts +0 -3
  58. package/lib/node/redirectPlugin.js +0 -53
  59. package/lib/node/types/frontmatter.d.ts +0 -4
  60. package/lib/node/types/frontmatter.js +0 -1
  61. package/lib/node/types/index.d.ts +0 -2
  62. package/lib/node/types/index.js +0 -1
  63. package/lib/node/types/options.d.ts +0 -22
  64. package/lib/node/types/options.js +0 -1
  65. package/lib/shared/index.d.ts +0 -3
  66. package/lib/shared/index.js +0 -3
  67. package/lib/shared/localeConfig.js +0 -1
  68. package/lib/shared/locales.d.ts +0 -24
  69. package/lib/shared/locales.js +0 -1
  70. package/lib/shared/normalizePath.d.ts +0 -1
  71. package/lib/shared/normalizePath.js +0 -4
package/lib/cli/index.js CHANGED
@@ -1,74 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- import { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper';
4
- import { cac } from 'cac';
5
- import { loadUserConfig, resolveAppConfig, resolveCliAppConfig, resolveUserConfigConventionalPath, transformUserConfigToPlugin, } from 'vuepress/cli';
6
- import { createBuildApp } from 'vuepress/core';
7
- import { fs, logger, path } from 'vuepress/utils';
8
- import { getRedirectHTML } from '../node/generate/getRedirectHTML.js';
9
- const require = createRequire(import.meta.url);
10
- const cli = cac('vp-redirect');
11
- const { version } = require('@vuepress/plugin-redirect/package.json');
12
- cli
13
- .command('generate [source-dir]', 'Generate redirect site using VuePress project under source folder')
14
- .option('--hostname <hostname>', 'Hostname to redirect to (E.g.: https://new.example.com/)', { default: '/' })
15
- .option('-c, --config <config>', 'Set path to config file')
16
- .option('-o, --output <output>', 'Set the output directory (default: .vuepress/redirect)')
17
- .option('--cache <cache>', 'Set the directory of the cache files')
18
- .option('-t, --temp <temp>', 'Set the directory of the temporary files')
19
- .option('--clean-cache', 'Clean the cache files before generation')
20
- .option('--clean-temp', 'Clean the temporary files before generation')
21
- .action(async (sourceDir, commandOptions) => {
22
- if (!sourceDir)
23
- return cli.outputHelp();
24
- // ensure NODE_ENV is set
25
- process.env.NODE_ENV ??= 'production';
26
- // resolve app config from cli options
27
- const cliAppConfig = resolveCliAppConfig(sourceDir, {});
28
- // resolve user config file
29
- const userConfigPath = resolveUserConfigConventionalPath(cliAppConfig.source);
30
- const { userConfig } = await loadUserConfig(userConfigPath);
31
- // resolve the final app config to use
32
- const appConfig = resolveAppConfig({
33
- defaultAppConfig: {},
34
- cliAppConfig,
35
- userConfig,
36
- });
37
- if (appConfig === null)
38
- return;
39
- // create vuepress app
40
- const app = createBuildApp(appConfig);
41
- // use user-config plugin
42
- app.use(transformUserConfigToPlugin(userConfig, cliAppConfig.source));
43
- // clean temp and cache
44
- if (commandOptions.cleanTemp === true) {
45
- logger.info('Cleaning temp...');
46
- await fs.remove(app.dir.temp());
47
- }
48
- if (commandOptions.cleanCache === true) {
49
- logger.info('Cleaning cache...');
50
- await fs.remove(app.dir.cache());
51
- }
52
- const outputFolder = commandOptions.output
53
- ? path.join(process.cwd(), commandOptions.output)
54
- : path.join(app.dir.source(), '.vuepress', 'redirect');
55
- // empty output directory
56
- await fs.emptyDir(outputFolder);
57
- // initialize vuepress app to get pages
58
- logger.info('Initializing VuePress and preparing data...');
59
- await app.init();
60
- // redirect all pages
61
- // initialize vuepress app to get pages
62
- logger.info('Generating redirect pages...');
63
- await Promise.all(app.pages.map((page) => {
64
- const redirectUrl = `${removeEndingSlash(commandOptions.hostname)}${app.options.base}${removeLeadingSlash(page.path)}`;
65
- const destLocation = path.join(outputFolder, removeLeadingSlash(page.path.replace(/\/$/, '/index.html')));
66
- return fs
67
- .ensureDir(path.dirname(destLocation))
68
- .then(() => fs.writeFile(destLocation, getRedirectHTML(redirectUrl)));
69
- }));
70
- });
71
- cli.command('').action(() => cli.outputHelp());
72
- cli.help();
73
- cli.version(version);
74
- cli.parse();
2
+ import{removeEndingSlash as v,removeLeadingSlash as h}from"@vuepress/helper";import{createCommand as C}from"commander";import{resolveCliAppConfig as w,resolveUserConfigPath as y,resolveUserConfigConventionalPath as $,loadUserConfig as S,resolveAppConfig as b,transformUserConfigToPlugin as A}from"vuepress/cli";import{createBuildApp as P}from"vuepress/core";import{fs as t,logger as n,path as a}from"vuepress/utils";var j="2.0.0-rc.121",x={version:j};const E=e=>`<!doctype html>
3
+ <html lang="en">
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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../package.json","../../src/node/generate/getRedirectHTML.ts","../../src/cli/index.ts"],"sourcesContent":["{\n \"name\": \"@vuepress/plugin-redirect\",\n \"version\": \"2.0.0-rc.121\",\n \"description\": \"VuePress plugin - redirect\",\n \"keywords\": [\n \"vuepress-plugin\",\n \"vuepress\",\n \"plugin\",\n \"redirect\"\n ],\n \"homepage\": \"https://ecosystem.vuejs.press/plugins/tools/redirect.html\",\n \"bugs\": {\n \"url\": \"https://github.com/vuepress/ecosystem/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/vuepress/ecosystem.git\",\n \"directory\": \"plugins/tools/plugin-redirect\"\n },\n \"license\": \"MIT\",\n \"author\": {\n \"name\": \"Mr.Hope\",\n \"email\": \"mister-hope@outlook.com\",\n \"url\": \"https://mister-hope.com\"\n },\n \"type\": \"module\",\n \"exports\": {\n \".\": \"./lib/node/index.js\",\n \"./client\": \"./lib/client/index.js\",\n \"./package.json\": \"./package.json\"\n },\n \"main\": \"./lib/node/index.js\",\n \"types\": \"./lib/node/index.d.ts\",\n \"bin\": {\n \"vp-redirect\": \"./lib/cli/index.js\"\n },\n \"files\": [\n \"lib\"\n ],\n \"scripts\": {\n \"build\": \"tsc -b tsconfig.build.json\",\n \"bundle\": \"rollup -c rollup.config.ts --configPlugin esbuild\",\n \"clean\": \"rimraf --glob ./lib ./*.tsbuildinfo\",\n \"style\": \"sass src:lib --embed-sources --style=compressed --pkg-importer=node\"\n },\n \"dependencies\": {\n \"@vuepress/helper\": \"workspace:*\",\n \"@vueuse/core\": \"catalog:\",\n \"commander\": \"^14.0.2\",\n \"vue\": \"catalog:\"\n },\n \"peerDependencies\": {\n \"vuepress\": \"catalog:\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\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","#!/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\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"],"names":["version","package_default","getRedirectHTML","redirectUrl","program","createCommand","sourceDir","output","commandOptions","fs","cliAppConfig","resolveCliAppConfig","userConfigPath","resolveUserConfigPath","resolveUserConfigConventionalPath","userConfig","loadUserConfig","appConfig","resolveAppConfig","app","createBuildApp","transformUserConfigToPlugin","logger","outputFolder","path","page","removeEndingSlash","removeLeadingSlash","destLocation","pkg"],"mappings":";gaACE,IACAA,EAAW,eAFbC,EAAA,CAEE,QAAAD,CAuDF,ECzDO,MAAME,EAAmBC,GAAgC;AAAA;AAAA;AAAA;AAAA;AAAA,+CAKjBA,CAAW;AAAA,gCAC1BA,CAAW;AAAA;AAAA;AAAA;AAAA,gCAIXA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECerCC,EAAUC,EAAc,aAAa,EAE3CD,EACG,QAAQ,wBAAwB,EAChC,YAAY,qDAAqD,EACjE,OACC,wBACA,2DACA,GACF,EACC,OAAO,wBAAyB,yBAAyB,EACzD,OAAO,kBAAmB,sCAAsC,EAChE,OAAO,gBAAiB,0CAA0C,EAClE,OAAO,gBAAiB,yCAAyC,EACjE,OAAO,eAAgB,6CAA6C,EACpE,SAAS,WAAY,sCAAsC,EAC3D,SACC,WACA,uEACF,EACC,OACC,MACEE,EACAC,EACAC,IACG,CAEH,QAAQ,IAAI,WAAa,aAEpBC,EAAG,WAAWH,CAAS,GAC1BF,EAAQ,MAAM,oBAAoBE,CAAS,kBAAkB,EAI/D,MAAMI,EAAeC,EAAoBL,EAAW,CAAA,CAAE,EAGhDM,EAAiBJ,EAAe,OAClCK,EAAsBL,EAAe,MAAM,EAC3CM,EAAkCJ,EAAa,MAAM,EAEnD,CAAE,WAAAK,CAAW,EAAI,MAAMC,EAAeJ,CAAc,EAGpDK,EAAYC,EAAiB,CACjC,iBAAkB,CAChB,MAAOV,EAAe,MACtB,KAAMA,EAAe,IACvB,EACA,aAAAE,EACA,WAAAK,CACF,CAAC,EAED,GAAIE,IAAc,KAAM,OAGxB,MAAME,EAAMC,EAAeH,CAAS,EAGpCE,EAAI,IAAIE,EAA4BN,EAAYL,EAAa,MAAM,CAAC,EAGhEF,EAAe,YAAc,KAC/Bc,EAAO,KAAK,kBAAkB,EAC9B,MAAMb,EAAG,OAAOU,EAAI,IAAI,MAAM,GAE5BX,EAAe,aAAe,KAChCc,EAAO,KAAK,mBAAmB,EAC/B,MAAMb,EAAG,OAAOU,EAAI,IAAI,MAAA,CAAO,GAGjC,MAAMI,EAAehB,EACjBiB,EAAK,KAAK,QAAQ,MAAOjB,CAAM,EAC/BiB,EAAK,KAAKL,EAAI,IAAI,SAAU,YAAa,UAAU,EAGvD,MAAMV,EAAG,SAASc,CAAY,EAE9BD,EAAO,KAAK,6CAA6C,EAGzD,MAAMH,EAAI,KAAA,EAEVG,EAAO,KAAK,8BAA8B,EAG1C,MAAM,QAAQ,IACZH,EAAI,MAAM,IAAKM,GAAS,CACtB,MAAMtB,EAAc,GAAGuB,EAAkBlB,EAAe,QAAQ,CAAC,GAC/DW,EAAI,SAAS,IACf,GAAGQ,EAAmBF,EAAK,IAAI,CAAC,GAC1BG,EAAeJ,EAAK,KACxBD,EACAI,EAAmBF,EAAK,KAAK,QAAQ,MAAO,aAAa,CAAC,CAC5D,EAEA,OAAOhB,EACJ,UAAUe,EAAK,QAAQI,CAAY,CAAC,EACpC,KAAK,IACJnB,EAAG,UAAUmB,EAAc1B,EAAgBC,CAAW,CAAC,CACzD,CACJ,CAAC,CACH,CACF,CACF,EAEFC,EAAQ,QAAQyB,EAAI,OAAO,EAC3BzB,EAAQ,mBAAmB,uCAAuC,EAElE,MAAMA,EAAQ,WAAA"}
@@ -1,4 +1,4 @@
1
- export interface RedirectLocaleConfig {
1
+ interface RedirectBehaviorOptions {
2
2
  /**
3
3
  * Whether enable locales redirection
4
4
  *
@@ -6,21 +6,7 @@ export interface RedirectLocaleConfig {
6
6
  *
7
7
  * @default false
8
8
  */
9
- autoLocale: boolean;
10
- /**
11
- * Whether switch locales
12
- *
13
- * 是否启用重定向语言
14
- *
15
- * @default false
16
- */
17
- switchLocale: 'direct' | 'modal' | false;
18
- /**
19
- * Locale language config
20
- *
21
- * 多语言语言配置
22
- */
23
- localeConfig: Record<string, string[]>;
9
+ autoLocale?: boolean;
24
10
  /**
25
11
  * Whether fallback to other locales user defined
26
12
  *
@@ -28,7 +14,7 @@ export interface RedirectLocaleConfig {
28
14
  *
29
15
  * @default true
30
16
  */
31
- localeFallback: boolean;
17
+ localeFallback?: boolean;
32
18
  /**
33
19
  * Behavior when a locale version is not available for current link
34
20
  *
@@ -40,7 +26,7 @@ export interface RedirectLocaleConfig {
40
26
  *
41
27
  * @default "defaultLocale"
42
28
  */
43
- defaultBehavior: 'defaultLocale' | 'homepage' | '404';
29
+ defaultBehavior?: '404' | 'defaultLocale' | 'homepage';
44
30
  /**
45
31
  * Default locale path
46
32
  *
@@ -50,5 +36,15 @@ export interface RedirectLocaleConfig {
50
36
  *
51
37
  * @description 如果缺失,则使用第一个语言
52
38
  */
53
- defaultLocale: string;
39
+ defaultLocale?: string;
40
+ }
41
+ interface RedirectBehaviorConfig extends Required<RedirectBehaviorOptions> {
42
+ /**
43
+ * Locale language config
44
+ *
45
+ * 多语言语言配置
46
+ */
47
+ config: Record<string, string[]>;
54
48
  }
49
+
50
+ export type { RedirectBehaviorConfig as R };
@@ -0,0 +1,61 @@
1
+ import * as vue from 'vue';
2
+ import { PropType, VNode } from 'vue';
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 };
@@ -0,0 +1,2 @@
1
+ import{useScrollLock as y}from"@vueuse/core";import{defineComponent as k,ref as v,computed as g,h as e,watch as w,onMounted as j,nextTick as C,onBeforeUnmount as R,TransitionGroup as S}from"vue";import{useRouter as x,useData as L}from"vuepress/client";import"@vuepress/helper/transition/fade-in-scale-up.css";import"../styles/redirect-modal.css";import{u as M,s as d,a as f}from"../useRedirectInfo-BzhIENgm.js";import"@vuepress/helper/client";var P=k({name:"RedirectModal",props:{config:{type:Object,required:!0},locales:{type:Object,required:!0}},setup(n){const h=x(),{routeLocale:l,routePath:s}=L(),r=M(n.config),m=v(),t=y(m),o=v(!1),u=g(()=>{if(!r.value)return null;const{lang:c,localePath:b}=r.value,i=[n.locales[b],n.locales[l.value]];return{hint:i.map(({hint:a})=>a.replace("$1",c)),switch:i.map(({switch:a})=>a.replace("$1",c)).join(" / "),cancel:i.map(({cancel:a})=>a).join(" / "),remember:i.map(({remember:a})=>a).join(" / ")}}),p=()=>{d.value[l.value]=!0,o.value&&(f.value[l.value]=!0),t.value=!1};return w(s,()=>{t.value=!1}),j(async()=>{m.value=document.body,await C(),r.value&&!d.value[l.value]&&!f.value[l.value]&&(t.value=!0)}),R(()=>{t.value=!1}),()=>e(S,{name:"fade-in-scale-up"},()=>t.value?e("div",{key:"mask",class:"redirect-modal-mask"},e("div",{key:"popup",class:"redirect-modal-wrapper"},[e("div",{class:"redirect-modal-content"},u.value?.hint.map(c=>e("p",c))),e("div",{class:"redirect-modal-hint"},[e("input",{id:"remember-redirect",type:"checkbox",value:o.value,onChange:()=>{o.value=!o.value}}),e("label",{for:"remember-redirect"},u.value?.remember)]),e("button",{type:"button",class:"redirect-modal-action primary",onClick:()=>{p(),h.replace(s.value.replace(l.value,r.value.localePath))}},u.value?.switch),e("button",{type:"button",class:"redirect-modal-action",onClick:()=>{p()}},u.value?.cancel)])):null)}});export{P as default};
2
+ //# sourceMappingURL=RedirectModal.js.map
@@ -0,0 +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) {\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\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 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,\n )\n },\n})\n"],"names":["RedirectModal","defineComponent","props","router","useRouter","routeLocale","routePath","useData","redirectInfo","useRedirectInfo","body","ref","showModal","useScrollLock","shouldRemember","locale","computed","lang","localePath","locales","hint","switchText","cancel","remember","updateState","statusSessionStorage","statusLocalStorage","watch","onMounted","nextTick","onBeforeUnmount","h","TransitionGroup","text"],"mappings":"2bAsBA,IAAAA,EAAeC,EAAgB,CAC7B,KAAM,gBAEN,MAAO,CACL,OAAQ,CACN,KAAM,OACN,SAAU,EACZ,EAEA,QAAS,CACP,KAAM,OACN,SAAU,EACZ,CACF,EAEA,MAAMC,EAAO,CACX,MAAMC,EAASC,EAAAA,EACT,CAAE,YAAAC,EAAa,UAAAC,CAAU,EAAIC,IAC7BC,EAAeC,EAAgBP,EAAM,MAAM,EAE3CQ,EAAOC,EAAAA,EAEPC,EAAYC,EAAcH,CAAI,EAC9BI,EAAiBH,EAAI,EAAK,EAE1BI,EAASC,EAAS,IAAM,CAC5B,GAAI,CAACR,EAAa,MAAO,OAAO,KAEhC,KAAM,CAAE,KAAAS,EAAM,WAAAC,CAAW,EAAIV,EAAa,MACpCW,EAAU,CACdjB,EAAM,QAAQgB,CAAU,EACxBhB,EAAM,QAAQG,EAAY,KAAK,CACjC,EAEA,MAAO,CACL,KAAMc,EAAQ,IAAI,CAAC,CAAE,KAAAC,CAAK,IAAMA,EAAK,QAAQ,KAAMH,CAAI,CAAC,EACxD,OAAQE,EACL,IAAI,CAAC,CAAE,OAAQE,CAAW,IAAMA,EAAW,QAAQ,KAAMJ,CAAI,CAAC,EAC9D,KAAK,KAAK,EACb,OAAQE,EAAQ,IAAI,CAAC,CAAE,OAAAG,CAAO,IAAMA,CAAM,EAAE,KAAK,KAAK,EACtD,SAAUH,EAAQ,IAAI,CAAC,CAAE,SAAAI,CAAS,IAAMA,CAAQ,EAAE,KAAK,KAAK,CAC9D,CACF,CAAC,EAEKC,EAAc,IAAY,CAC9BC,EAAqB,MAAMpB,EAAY,KAAK,EAAI,GAC5CS,EAAe,QACjBY,EAAmB,MAAMrB,EAAY,KAAK,EAAI,IAEhDO,EAAU,MAAQ,EACpB,EAEA,OAAAe,EAAMrB,EAAW,IAAM,CACrBM,EAAU,MAAQ,EACpB,CAAC,EAEDgB,EAAU,SAAY,CACpBlB,EAAK,MAAQ,SAAS,KAEtB,MAAMmB,IAGJrB,EAAa,OACb,CAACiB,EAAqB,MAAMpB,EAAY,KAAK,GAC7C,CAACqB,EAAmB,MAAMrB,EAAY,KAAK,IAE3CO,EAAU,MAAQ,GAEtB,CAAC,EAEDkB,EAAgB,IAAM,CACpBlB,EAAU,MAAQ,EACpB,CAAC,EAEM,IACLmB,EAAEC,EAAiB,CAAE,KAAM,kBAAmB,EAAG,IAC/CpB,EAAU,MACNmB,EACE,MACA,CAAE,IAAK,OAAQ,MAAO,qBAAsB,EAC5CA,EACE,MACA,CACE,IAAK,QACL,MAAO,wBACT,EACA,CACEA,EACE,MACA,CAAE,MAAO,wBAAyB,EAClChB,EAAO,OAAO,KAAK,IAAKkB,GAASF,EAAE,IAAKE,CAAI,CAAC,CAC/C,EACAF,EAAE,MAAO,CAAE,MAAO,qBAAsB,EAAG,CACzCA,EAAE,QAAS,CACT,GAAI,oBACJ,KAAM,WACN,MAAOjB,EAAe,MACtB,SAAU,IAAM,CACdA,EAAe,MAAQ,CAACA,EAAe,KACzC,CACF,CAAC,EACDiB,EACE,QACA,CAAE,IAAK,mBAAoB,EAC3BhB,EAAO,OAAO,QAChB,CACF,CAAC,EACDgB,EACE,SACA,CACE,KAAM,SACN,MAAO,gCACP,QAAS,IAAM,CACbP,EAAAA,EACArB,EAAO,QACLG,EAAU,MAAM,QACdD,EAAY,MACZG,EAAa,MAAO,UACtB,CACF,CACF,CACF,EACAO,EAAO,OAAO,MAChB,EACAgB,EACE,SACA,CACE,KAAM,SACN,MAAO,wBACP,QAAS,IAAM,CACbP,GACF,CACF,EACAT,EAAO,OAAO,MAChB,CACF,CACF,CACF,EACA,IACN,CACJ,CACF,CAAC"}
@@ -1,4 +1,7 @@
1
- import type { ClientConfig } from 'vuepress/client';
2
- import './styles/vars.css';
3
- declare const _default: ClientConfig;
4
- export default _default;
1
+ import * as vuepress_client from 'vuepress/client';
2
+ import { R as RedirectBehaviorConfig } from './behavior-BgEQhx7R.js';
3
+
4
+ declare const config: RedirectBehaviorConfig;
5
+ declare const _default: vuepress_client.ClientConfig;
6
+
7
+ export { config, _default as default };
@@ -1,11 +1,2 @@
1
- import { defineClientConfig } from 'vuepress/client';
2
- import LanguageSwitch from './components/LanguageSwitch.js';
3
- import { setupDevServerRedirect } from './composables/setupDevServerRedirect.js';
4
- import './styles/vars.css';
5
- export default defineClientConfig({
6
- setup() {
7
- if (__VUEPRESS_DEV__)
8
- setupDevServerRedirect();
9
- },
10
- rootComponents: __REDIRECT_LOCALE_SWITCH__ ? [LanguageSwitch] : [],
11
- });
1
+ import o from"@vuepress/plugin-redirect/modal";import{h as t}from"vue";import{defineClientConfig as r}from"vuepress/client";import"./styles/vars.css";import{a as e,s as i}from"./setupRedirect-BBJERz7T.js";import"@temp/redirect/map.js";import"@vuepress/helper/client";import"@vueuse/core";import"./useRedirectInfo-BzhIENgm.js";const _=__REDIRECT_CONFIG__;var m=r({setup(){__REDIRECT_DIRECT__&&e(_),__VUEPRESS_DEV__&&i(_)},...__REDIRECT_MODAL__?{rootComponents:[()=>t(o,{config:_,locales:__REDIRECT_LOCALES__})]}:{}});export{_ as config,m as default};
2
+ //# sourceMappingURL=config.js.map
@@ -0,0 +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"],"names":["config","config_default","defineClientConfig","setupRedirect","setupDevServerRedirect","h","RedirectModal"],"mappings":"sUAcO,MAAMA,EAAS,oBAEtB,IAAAC,EAAeC,EAAmB,CAChC,OAAQ,CACF,qBAAqBC,EAAcH,CAAM,EACzC,kBAAkBI,EAAuBJ,CAAM,CACrD,EACA,GAAI,mBACA,CACE,eAAgB,CACd,IACEK,EAAEC,EAAe,CACf,OAAAN,EACA,QAAS,oBACX,CAAC,CACL,CACF,EACA,CAAA,CACN,CAAC"}
@@ -0,0 +1,21 @@
1
+ export { default as RedirectModal } from './components/RedirectModal.js';
2
+ import { R as RedirectBehaviorConfig } from './behavior-BgEQhx7R.js';
3
+ import { ComputedRef } from 'vue';
4
+ import '@vuepress/helper/client';
5
+
6
+ declare const setupDevServerRedirect: ({ autoLocale, config, defaultBehavior, defaultLocale: defaultLocalePath, localeFallback, }: RedirectBehaviorConfig) => void;
7
+
8
+ interface LocaleInfo {
9
+ lang: string;
10
+ localePath: string;
11
+ }
12
+ declare const setupRedirect: (behaviorConfig: RedirectBehaviorConfig) => void;
13
+
14
+ interface RedirectInfo {
15
+ lang: string;
16
+ localePath: string;
17
+ }
18
+ declare const useRedirectInfo: (behaviorConfig: RedirectBehaviorConfig) => ComputedRef<RedirectInfo | null>;
19
+
20
+ export { setupDevServerRedirect, setupRedirect, useRedirectInfo };
21
+ export type { LocaleInfo, RedirectInfo };
@@ -0,0 +1,2 @@
1
+ import{default as d}from"./components/RedirectModal.js";import{s as u,a as c}from"./setupRedirect-BBJERz7T.js";import{u as x}from"./useRedirectInfo-BzhIENgm.js";import"@vueuse/core";import"vue";import"vuepress/client";import"@vuepress/helper/transition/fade-in-scale-up.css";import"./styles/redirect-modal.css";import"@temp/redirect/map.js";import"@vuepress/helper/client";export{d as RedirectModal,u as setupDevServerRedirect,c as setupRedirect,x as useRedirectInfo};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
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
@@ -0,0 +1 @@
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,KAAQlB,EAAU,MACzC,SAAW,CAACmB,EAAYC,CAAK,IAAKrB,EAChC,GAAIqB,EAAM,SAASF,CAAI,EAAG,CACxB,GACEpB,GACAgB,EAAO,MACL,CAAC,CAAE,KAAAvB,CAAK,IAAMA,IAASsB,EAAe,QAAQ,IAAKtB,CAAI,CACzD,EAEA,SAEFyB,EAAoBG,EACpB,MAAMF,CACR,CAGJ,MAAMI,EAAeN,EACjBb,EAAM,SAAS,QAAQ,IAAKa,CAAa,EACzC,KAGJ,GAAIC,EAAmB,CACrB,MAAMM,EAAgBR,EAAO,KAC3B,CAAC,CAAE,KAAAvB,CAAK,IAAMsB,EAAe,QAAQ,IAAKG,CAAiB,IAAMzB,CACnE,EACMgC,EAAcrB,EAAM,SAAS,QAAQ,IAAKc,CAAiB,EAE3DQ,EAEJF,EACIC,EAEA3B,IAAoB,WAElBoB,EACApB,IAAoB,iBAAmByB,EAErCA,EAEAE,EAEVnB,EAAO,QAAQoB,CAAY,CAC7B,MAESH,EACPjB,EAAO,QAAQiB,CAAY,EAClBb,EAAU,QAAU,aAC7BJ,EAAO,QAAQ,WAAW,CAE9B,EAEAqB,EAAejB,EAAYjB,GAAS,CAElC,SAAW,CAACmC,EAAMC,CAAE,IAAKC,EAAQC,CAAW,EAC1C,GAAIvC,EAAcC,EAAK,YAAA,CAAa,IAAMmC,EAAK,YAAA,EAAe,CACxDI,EAAWH,CAAE,EAAG,OAAO,KAAKA,CAAE,EAC7BvB,EAAO,QAAQuB,CAAE,EAEtB,MACF,CAEEjC,GAAcgB,EAAa,OAAOE,EAAAA,CACxC,CAAC,CACH,ECpGamB,EAAiBC,GAAiD,CAC7E,KAAM,CAAE,YAAA1B,EAAa,UAAAE,CAAU,EAAIyB,EAAAA,EAC7B7B,EAASC,EAAAA,EACT6B,EAAeC,EAAgBH,CAAc,EAEnDI,EAAU,IAAM,CACVF,EAAa,OAAS,CAACG,EAAqB,MAAM/B,EAAY,KAAK,IACrEF,EAAO,QACLI,EAAU,MAAM,QACdF,EAAY,MACZ4B,EAAa,MAAM,UACrB,CACF,EACAG,EAAqB,MAAM/B,EAAY,KAAK,EAAI,GAEpD,CAAC,CACH"}
@@ -0,0 +1 @@
1
+ .redirect-modal-mask{position:fixed;inset:0;z-index:var(--redirect-z-index);display:flex;align-items:center;justify-content:center;backdrop-filter:blur(10px)}@media print{.redirect-modal-mask{display:none}}.redirect-modal-wrapper{position:relative;z-index:1500;overflow:hidden;max-width:80vw;padding:1rem 2rem;border-radius:.5rem;background:var(--redirect-c-bg);box-shadow:0 2px 6px 0 var(--redirect-c-shadow)}.redirect-modal-hint{margin-top:.5rem;color:var(--vp-c-text-mute);font-size:.875rem;text-align:start}.redirect-modal-hint input[type=checkbox]{position:relative;vertical-align:text-bottom;height:1em;margin-inline-end:18px;font-size:inherit;cursor:pointer;appearance:none}.redirect-modal-hint input[type=checkbox]::after{content:" ";position:absolute;top:0;display:inline-block;box-sizing:border-box;width:14px;height:14px;padding-inline-start:0;border:1px solid var(--vp-c-border);border-radius:50%;background:var(--vp-c-control);text-align:center;visibility:visible}.redirect-modal-hint input[type=checkbox]:checked::after{content:"";border-color:var(--vp-c-accent-bg);background:var(--vp-c-accent-bg)}.redirect-modal-hint input[type=checkbox]:checked::before{content:"";position:absolute;inset-inline-start:5px;top:2px;z-index:1;width:2px;height:6px;border:solid var(--vp-c-white);border-width:0 2px 2px 0;transform:rotate(45deg)}.redirect-modal-hint label{display:inline-block}.redirect-modal-action{display:block;width:100%;margin:1rem 0;padding:.5rem .75rem;border:none;border-radius:.5rem;background-color:var(--redirect-c-control);color:inherit;cursor:pointer}.redirect-modal-action:hover{background-color:var(--redirect-c-control-hover)}.redirect-modal-action.primary{background-color:var(--redirect-c-accent-bg);color:var(--redirect-c-accent-text)}.redirect-modal-action.primary:hover{background-color:var(--redirect-c-accent-hover)}/*# sourceMappingURL=redirect-modal.css.map */
@@ -0,0 +1 @@
1
+ {"version":3,"sourceRoot":"","sources":["../../../src/client/styles/redirect-modal.scss"],"names":[],"mappings":"AAAA,qBACE,eACA,QACA,gCAEA,aACA,mBACA,uBAEA,2BAEA,aAXF,qBAYI,cAIJ,wBACE,kBACA,aAEA,gBAEA,eACA,kBACA,oBAEA,gCACA,gDAGF,qBACE,iBACA,4BACA,kBACA,iBAEA,0CACE,kBAEA,2BAEA,WACA,uBAEA,kBAEA,eAEA,gBAEA,iDACE,YAEA,kBACA,MAEA,qBAEA,sBACA,WACA,YACA,uBACA,oCACA,kBAEA,+BAEA,kBAEA,mBAIA,yDACE,WACA,mCACA,iCAGF,0DACE,WAEA,kBACA,uBACA,QACA,UAEA,UACA,WACA,+BACA,yBAEA,wBAKN,2BACE,qBAIJ,uBACE,cAEA,WACA,cACA,qBACA,YACA,oBAEA,2CACA,cAEA,eAEA,6BACE,iDAGF,+BACE,6CACA,oCAEA,qCACE","file":"redirect-modal.css","sourcesContent":[".redirect-modal-mask {\n position: fixed;\n inset: 0;\n z-index: var(--redirect-z-index);\n\n display: flex;\n align-items: center;\n justify-content: center;\n\n backdrop-filter: blur(10px);\n\n @media print {\n display: none;\n }\n}\n\n.redirect-modal-wrapper {\n position: relative;\n z-index: 1500;\n\n overflow: hidden;\n\n max-width: 80vw;\n padding: 1rem 2rem;\n border-radius: 0.5rem;\n\n background: var(--redirect-c-bg);\n box-shadow: 0 2px 6px 0 var(--redirect-c-shadow);\n}\n\n.redirect-modal-hint {\n margin-top: 0.5rem;\n color: var(--vp-c-text-mute);\n font-size: 0.875rem;\n text-align: start;\n\n input[type='checkbox'] {\n position: relative;\n\n vertical-align: text-bottom;\n\n height: 1em;\n margin-inline-end: 18px;\n\n font-size: inherit;\n\n cursor: pointer;\n\n appearance: none;\n\n &::after {\n content: ' ';\n\n position: absolute;\n top: 0;\n\n display: inline-block;\n\n box-sizing: border-box;\n width: 14px;\n height: 14px;\n padding-inline-start: 0;\n border: 1px solid var(--vp-c-border);\n border-radius: 50%;\n\n background: var(--vp-c-control);\n\n text-align: center;\n\n visibility: visible;\n }\n\n &:checked {\n &::after {\n content: '';\n border-color: var(--vp-c-accent-bg);\n background: var(--vp-c-accent-bg);\n }\n\n &::before {\n content: '';\n\n position: absolute;\n inset-inline-start: 5px;\n top: 2px;\n z-index: 1;\n\n width: 2px;\n height: 6px;\n border: solid var(--vp-c-white);\n border-width: 0 2px 2px 0;\n\n transform: rotate(45deg);\n }\n }\n }\n\n label {\n display: inline-block;\n }\n}\n\n.redirect-modal-action {\n display: block;\n\n width: 100%;\n margin: 1rem 0;\n padding: 0.5rem 0.75rem;\n border: none;\n border-radius: 0.5rem;\n\n background-color: var(--redirect-c-control);\n color: inherit;\n\n cursor: pointer;\n\n &:hover {\n background-color: var(--redirect-c-control-hover);\n }\n\n &.primary {\n background-color: var(--redirect-c-accent-bg);\n color: var(--redirect-c-accent-text);\n\n &:hover {\n background-color: var(--redirect-c-accent-hover);\n }\n }\n}\n"]}
@@ -1,10 +1 @@
1
- :root {
2
- --redirect-z-index: 1499;
3
- --redirect-bg-color: #fff;
4
- --redirect-bg-color-light: #f3f4f5;
5
- --redirect-bg-color-lighter: #eeeeee;
6
- --redirect-text-color: #2c3e50;
7
- --redirect-primary-bg-color: #3eaf7c;
8
- --redirect-primary-hover-bg-color: #4abf8a;
9
- --redirect-primary-text-color: #fff;
10
- }
1
+ :root{--redirect-z-index: 1499;--redirect-c-bg: var(--vp-c-bg-elv);--redirect-c-text: var(--vp-c-text);--redirect-c-accent-bg: var(--vp-c-accent-bg);--redirect-c-accent-hover: var(--vp-c-accent-hover);--redirect-c-accent-text: var(--vp-c-accent-text);--redirect-c-control: var(--vp-c-control);--redirect-c-control-hover: var(--vp-c-control-hover);--redirect-c-shadow: var(--vp-c-shadow)}/*# sourceMappingURL=vars.css.map */
@@ -0,0 +1 @@
1
+ {"version":3,"sourceRoot":"","sources":["../../../src/client/styles/vars.css"],"names":[],"mappings":"AAAA,MACE,yBACA,oCACA,oCACA,8CACA,oDACA,kDACA,0CACA,sDACA","file":"vars.css","sourcesContent":[":root {\n --redirect-z-index: 1499;\n --redirect-c-bg: var(--vp-c-bg-elv);\n --redirect-c-text: var(--vp-c-text);\n --redirect-c-accent-bg: var(--vp-c-accent-bg);\n --redirect-c-accent-hover: var(--vp-c-accent-hover);\n --redirect-c-accent-text: var(--vp-c-accent-text);\n --redirect-c-control: var(--vp-c-control);\n --redirect-c-control-hover: var(--vp-c-control-hover);\n --redirect-c-shadow: var(--vp-c-shadow);\n}\n"]}
@@ -0,0 +1,2 @@
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
@@ -0,0 +1 @@
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"}
@@ -1,2 +1,113 @@
1
- export * from './redirectPlugin.js';
2
- export type * from './types/index.js';
1
+ import { App, LocaleConfig, PluginFunction } from 'vuepress/core';
2
+ import { PageFrontmatter } from 'vuepress';
3
+
4
+ interface RedirectPluginFrontmatter extends PageFrontmatter {
5
+ redirectFrom?: string[] | string;
6
+ redirectTo?: string;
7
+ }
8
+
9
+ interface RedirectBehaviorOptions {
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
+
83
+ interface RedirectPluginOptions extends RedirectBehaviorOptions {
84
+ /**
85
+ * Redirect mapping
86
+ *
87
+ * 重定向映射
88
+ */
89
+ config?: Record<string, string> | ((app: App) => Record<string, string>);
90
+ /**
91
+ * Whether switch locales
92
+ *
93
+ * 是否启用重定向语言
94
+ */
95
+ switchLocale?: 'direct' | 'modal' | false;
96
+ /**
97
+ * Locale language config
98
+ *
99
+ * 多语言语言配置
100
+ */
101
+ localeConfig?: Record<string, string[] | string>;
102
+ /**
103
+ * Locales config
104
+ *
105
+ * 多语言选项
106
+ */
107
+ locales?: LocaleConfig<RedirectPluginLocaleData>;
108
+ }
109
+
110
+ declare const redirectPlugin: (options?: RedirectPluginOptions) => PluginFunction;
111
+
112
+ export { redirectPlugin };
113
+ export type { RedirectPluginFrontmatter, RedirectPluginOptions };