@viteplus/versions 2.3.0 → 3.0.0

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/README.md CHANGED
@@ -8,6 +8,12 @@
8
8
  [![Discord](https://img.shields.io/discord/1422908712116420659?logo=Discord&label=Discord)](https://discord.gg/6vgFhJTEGn)
9
9
  [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-blue)](https://deepwiki.com/viteplus/versions)
10
10
 
11
+ > [!NOTE]
12
+ > This is a community project and is not affiliated with or endorsed by `VoidZero`, `Vite`, `VitePress`, or `Vite+`.
13
+ > The `viteplus` GitHub organization and the `@viteplus` npm scope are independent and predate any knowledge of
14
+ > `Vite+`. the name only means "plugins for Vite and VitePress". See
15
+ > [#59](https://github.com/viteplus/versions/issues/59#issuecomment-6780832222).
16
+
11
17
  A VitePress plugin for versioned documentation. Call `defineVersionedConfig` instead of VitePress's
12
18
  `defineConfig` and it manages versioned routes, a per-version sidebar and navigation, and a `VersionSwitcher`
13
19
  component - so a single site can serve your current docs alongside frozen copies of every previous version.
@@ -19,7 +25,8 @@ VitePress v1.6.4 and the v2.x line.
19
25
 
20
26
  ## Key Features
21
27
 
22
- - **Versioned routes**: serve the current docs from `src/` at the root and each `archive/` subfolder as a frozen, separately-routed version.
28
+ - **Versioned routes**: serve every version - the docs in `src/` and each `archive/` subfolder - under its own name, and open the stable one at `/`.
29
+ - **Release branching**: draft the next release at `/next/` with `latest` pointing at the stable version, and label versions such as `v1.x (LTS)`.
23
30
  - **Per-version navigation**: give every version its own nav and sidebar, or share one configuration across all of them.
24
31
  - **Version switcher**: a built-in `VersionSwitcher` component that lists every version and switches between them.
25
32
  - **Version-aware localization**: full multi-language support, with locale and version combined into clean URLs.
@@ -63,8 +70,28 @@ export default defineVersionedConfig({
63
70
  });
64
71
  ```
65
72
 
66
- Current-version content lives in `docs/src` and is served at the site root; each subfolder of `docs/archive`
67
- becomes a frozen version. `defineVersionedConfig` wires the routing - you do not set `srcDir` yourself.
73
+ Current-version content lives in `docs/src` and is served under its `current` label; each subfolder of `docs/archive`
74
+ becomes a frozen version, and `/` opens the latest one. `defineVersionedConfig` wires the routing - you do not set `srcDir` yourself.
75
+
76
+ ## Stable and unreleased versions
77
+
78
+ Point `latest` at an archived version while `docs/src` holds the docs of a release that is not out yet:
79
+
80
+ ```ts
81
+ export default defineVersionedConfig({
82
+ versionsConfig: {
83
+ current: 'next', // docs/src is served at /next/
84
+ latest: 'v2.x', // docs/archive/v2.x is served at /v2.x/ and opened at /
85
+ versions: {
86
+ 'v1.x': { label: 'v1.x (LTS)' }, // switcher label
87
+ 'v0.x': { path: 'legacy/v0' } // a version from its own folder
88
+ }
89
+ }
90
+ });
91
+ ```
92
+
93
+ Absolute links in your markdown stay inside the version of the page that holds them, and a misspelled version
94
+ name fails the build. See [Configuration Options](https://viteplus.github.io/versions/guide/config/configuration).
68
95
 
69
96
  ## Theme setup
70
97
 
@@ -74,22 +101,28 @@ Register the `VersionSwitcher` component in your theme so it can be placed in th
74
101
  // .vitepress/theme/index.ts
75
102
  import DefaultTheme from 'vitepress/theme';
76
103
  import VersionSwitcher from '@viteplus/versions/components/version-switcher.component.vue';
104
+ import { installVersionFallback } from '@viteplus/versions/fallback';
77
105
 
78
106
  export default {
79
107
  extends: DefaultTheme,
80
- enhanceApp({ app }) {
108
+ enhanceApp({ app, router, siteData }) {
81
109
  app.component('VersionSwitcher', VersionSwitcher);
110
+ installVersionFallback(router, siteData);
82
111
  }
83
112
  };
84
113
  ```
85
114
 
115
+ `installVersionFallback` catches a switch of version or language onto a page that does not exist there, such as the
116
+ language menu on an untranslated page, and opens the home page of that version or language instead. Any other missing
117
+ address keeps its 404 page.
118
+
86
119
  ## Project structure
87
120
 
88
121
  ```text
89
122
  docs/
90
123
  ├── .vitepress/
91
124
  │ └── config.ts
92
- ├── src/ // current version content (served at the root)
125
+ ├── src/ // current version content (served under its current label)
93
126
  │ ├── index.md
94
127
  │ └── guide/
95
128
  └── archive/ // archived versions (each subfolder is one frozen version)
@@ -114,13 +147,13 @@ export default defineVersionedConfig({
114
147
  ## Version-specific navigation
115
148
 
116
149
  `nav` and `sidebar` each accept an array (shared by every version) or an object keyed by version, where `root`
117
- is the current version. Version-specific entries are self-contained and do not inherit from `root`.
150
+ is the default for every version without its own key. Version-specific entries are self-contained and do not inherit from `root`.
118
151
 
119
152
  ```ts
120
153
  export default defineVersionedConfig({
121
154
  themeConfig: {
122
155
  nav: {
123
- // Default navigation for the current version
156
+ // Default navigation for every version without its own key
124
157
  root: [
125
158
  { text: 'Home', link: '/' },
126
159
  { text: 'Guide', link: '/guide/' }
@@ -140,11 +173,13 @@ export default defineVersionedConfig({
140
173
  Control how source paths map to URLs with `rewritesHook`.
141
174
 
142
175
  ```ts
176
+ import { join } from 'path/posix';
177
+
143
178
  export default defineVersionedConfig({
144
179
  versionsConfig: {
145
180
  hooks: {
146
- // version first, then locale
147
- rewritesHook: (source, version, locale) => `${version}/${locale}/${source}`
181
+ // keep locale/version/ in front, reshape the rest
182
+ rewritesHook: (source, version, locale) => join(locale, version, source.toLowerCase())
148
183
  }
149
184
  }
150
185
  });
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Imports
3
+ */
4
+
5
+ import { URL as NodeURL } from 'url';
6
+ import { installVersionFallback, pathToRoute, resolveSwitchRoute, routeToPath, splitRoute } from './fallback.component';
7
+
8
+ /**
9
+ * Tests
10
+ */
11
+
12
+ const versioning = {
13
+ versions: [ 'next', 'v2.x', 'v1.x' ],
14
+ latestVersion: 'v2.x',
15
+ locales: [ 'de' ],
16
+ routes: {
17
+ next: [ 'next/index.md', 'next/guide.md', 'de/next/index.md', 'de/next/guide.md' ],
18
+ 'v2.x': [ 'v2.x/index.md', 'v2.x/guide.md', 'v2.x/config/index.md', 'de/v2.x/index.md' ],
19
+ 'v1.x': [ 'v1.x/index.md', 'v1.x/hooks.md' ]
20
+ }
21
+ };
22
+
23
+ describe('pathToRoute', () => {
24
+ test.each`
25
+ pathname | route
26
+ ${ '/' } | ${ 'index.md' }
27
+ ${ '/de/v1.x/' } | ${ 'de/v1.x/index.md' }
28
+ ${ '/v1.x/guide.html' } | ${ 'v1.x/guide.md' }
29
+ ${ '/v1.x/guide' } | ${ 'v1.x/guide.md' }
30
+ ${ '/v1.x/f%C3%BCr' } | ${ 'v1.x/für.md' }
31
+ `('should read $pathname as $route', ({ pathname, route }: any) => {
32
+ expect(pathToRoute(pathname)).toBe(route);
33
+ });
34
+ });
35
+
36
+ describe('routeToPath', () => {
37
+ test.each`
38
+ route | cleanUrls | path
39
+ ${ 'de/v1.x/index.md' } | ${ false } | ${ '/de/v1.x/' }
40
+ ${ 'v1.x/guide.md' } | ${ false } | ${ '/v1.x/guide.html' }
41
+ ${ 'v1.x/guide.md' } | ${ true } | ${ '/v1.x/guide' }
42
+ ${ 'index.md' } | ${ false } | ${ '/' }
43
+ `('should write $route as $path', ({ route, cleanUrls, path }: any) => {
44
+ expect(routeToPath(route, cleanUrls)).toBe(path);
45
+ });
46
+ });
47
+
48
+ describe('splitRoute', () => {
49
+ test.each`
50
+ route | parts
51
+ ${ 'de/v1.x/guide/index.md' } | ${ { locale: 'de', version: 'v1.x', page: 'guide' } }
52
+ ${ 'v1.x/guide.md' } | ${ { locale: '', version: 'v1.x', page: 'guide' } }
53
+ ${ 'v1.x/index.md' } | ${ { locale: '', version: 'v1.x', page: '' } }
54
+ ${ 'guide.md' } | ${ { locale: '', version: '', page: 'guide' } }
55
+ `('should split $route', ({ route, parts }: any) => {
56
+ expect(splitRoute(route, versioning)).toEqual(parts);
57
+ });
58
+ });
59
+
60
+ describe('resolveSwitchRoute', () => {
61
+ test.each`
62
+ case | from | to | expected
63
+ ${ 'a page that exists' } | ${ 'v2.x/guide.md' } | ${ 'v1.x/hooks.md' } | ${ undefined }
64
+ ${ 'a missing page that is no switch' } | ${ 'v2.x/guide.md' } | ${ 'v2.x/missing.md' } | ${ undefined }
65
+ ${ 'a missing page in another version that is another page' } | ${ 'v2.x/guide.md' } | ${ 'v1.x/missing.md' } | ${ undefined }
66
+ ${ 'an old link that names no version' } | ${ 'v2.x/guide.md' } | ${ 'guide.md' } | ${ undefined }
67
+ ${ 'a version switch, to the home of the locale' } | ${ 'de/next/guide.md' } | ${ 'de/v2.x/guide.md' } | ${ 'de/v2.x/index.md' }
68
+ ${ 'a version switch, to the root home without the locale' } | ${ 'de/v2.x/index.md' } | ${ 'de/v1.x/index.md' } | ${ 'v1.x/index.md' }
69
+ ${ 'a version switch onto a folder page' } | ${ 'v2.x/config/index.md' } | ${ 'v1.x/config.md' } | ${ 'v1.x/index.md' }
70
+ ${ 'a language switch, to the home of the version' } | ${ 'v2.x/guide.md' } | ${ 'de/v2.x/guide.md' } | ${ 'de/v2.x/index.md' }
71
+ ${ 'a language switch, to the latest home in the language' } | ${ 'v1.x/hooks.md' } | ${ 'de/v1.x/hooks.md' } | ${ 'de/v2.x/index.md' }
72
+ `('should send $case to $expected', ({ from, to, expected }: any) => {
73
+ expect(resolveSwitchRoute(from, to, versioning)).toBe(expected);
74
+ });
75
+
76
+ test('should let a switch through when no home exists either', () => {
77
+ const bare = { ...versioning, routes: { 'v1.x': [ 'v1.x/hooks.md' ] } };
78
+
79
+ expect(resolveSwitchRoute('v1.x/hooks.md', 'de/v1.x/hooks.md', bare)).toBeUndefined();
80
+ });
81
+ });
82
+
83
+ describe('installVersionFallback', () => {
84
+ let router: any;
85
+ const siteData: any = { value: { base: '/docs/', cleanUrls: false, themeConfig: { versioning } } };
86
+
87
+ beforeEach(() => {
88
+ xJet.restoreAllMocks();
89
+
90
+ // the test sandbox has no global URL, which every browser and Node provide
91
+ (<any> globalThis).URL ??= NodeURL;
92
+ (<any> globalThis).window = { location: { href: 'https://a.com/docs/' } };
93
+ router = { go: xJet.fn(async () => undefined), route: { data: { relativePath: 'v1.x/hooks.md' } } };
94
+ });
95
+
96
+ afterEach(() => {
97
+ delete (<any> globalThis).window;
98
+ });
99
+
100
+ test('should move a language switch onto a missing page through the router, keeping the query and hash', async () => {
101
+ installVersionFallback(router, siteData);
102
+
103
+ await expect(router.onBeforeRouteChange('/docs/de/v1.x/hooks.html?q=1#top')).resolves.toBe(false);
104
+ expect(router.go).toHaveBeenCalledWith('/docs/de/v2.x/?q=1#top');
105
+ });
106
+
107
+ const passing = [
108
+ [ 'a page that exists', '/docs/v2.x/guide.html' ],
109
+ [ 'a missing page that is no switch', '/docs/v1.x/missing.html' ],
110
+ [ 'an old link that names no version', '/docs/guide.html' ],
111
+ [ 'an address outside the site base', '/other/de/v1.x/hooks.html' ]
112
+ ];
113
+
114
+ for (const [ name, to ] of passing) {
115
+ test(`should let ${ name } through`, async () => {
116
+ installVersionFallback(router, siteData);
117
+
118
+ await expect(router.onBeforeRouteChange(to)).resolves.toBeUndefined();
119
+ expect(router.go).not.toHaveBeenCalled();
120
+ });
121
+ }
122
+
123
+ test('should let the first load through, which has no page to switch from', async () => {
124
+ router.route.data = undefined;
125
+ installVersionFallback(router, siteData);
126
+
127
+ await expect(router.onBeforeRouteChange('/docs/de/v1.x/hooks.html')).resolves.toBeUndefined();
128
+ });
129
+
130
+ test('should run the hook that the theme set before it, and stop when that hook cancels', async () => {
131
+ router.onBeforeRouteChange = xJet.fn(() => false);
132
+ installVersionFallback(router, siteData);
133
+
134
+ await expect(router.onBeforeRouteChange('/docs/de/v1.x/hooks.html')).resolves.toBe(false);
135
+ expect(router.go).not.toHaveBeenCalled();
136
+ });
137
+ });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Type-only imports erased during TypeScript compilation.
3
+ */
4
+
5
+ import type { Ref } from 'vue';
6
+ import type { Router, SiteData } from 'vitepress';
7
+ import type { VersioningPluginInterface } from './version-switcher.component';
8
+
9
+ /**
10
+ * The parts of a route, see {@link splitRoute}.
11
+ *
12
+ * @since 3.0.0
13
+ */
14
+
15
+ export interface RoutePartsInterface {
16
+ /**
17
+ * The locale prefix, empty for the root locale.
18
+ *
19
+ * @since 3.0.0
20
+ */
21
+
22
+ locale: string;
23
+
24
+ /**
25
+ * The version name, empty when the route names none.
26
+ *
27
+ * @since 3.0.0
28
+ */
29
+
30
+ version: string;
31
+
32
+ /**
33
+ * The page inside the locale and version, without `.md` and without a trailing `index`.
34
+ *
35
+ * @since 3.0.0
36
+ */
37
+
38
+ page: string;
39
+ }
40
+
41
+ /**
42
+ * Turns the path of an address into the route of the page it names.
43
+ *
44
+ * @param pathname - The path of the address, without the site base, query, or hash
45
+ * @returns The route in the form of {@link VersioningPluginInterface.routes}, such as `de/v1.x/guide.md`
46
+ *
47
+ * @remarks
48
+ * A folder address names its `index.md`, and `.html` is read as `.md`, so clean and plain URLs give the same route.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * pathToRoute('/de/v1.x/'); // 'de/v1.x/index.md'
53
+ * pathToRoute('/v1.x/guide.html'); // 'v1.x/guide.md'
54
+ * pathToRoute('/v1.x/guide'); // 'v1.x/guide.md'
55
+ * ```
56
+ *
57
+ * @since 3.0.0
58
+ */
59
+
60
+ export function pathToRoute(pathname: string): string {
61
+ const path = decodeURI(pathname).replace(/^\/+/, '');
62
+ if (!path || path.endsWith('/')) return `${ path }index.md`;
63
+
64
+ return `${ path.replace(/\.html$/, '') }.md`;
65
+ }
66
+
67
+ /**
68
+ * Turns a route back into the path of its address.
69
+ *
70
+ * @param route - A route such as `de/v1.x/index.md`
71
+ * @param cleanUrls - Whether the site serves pages without `.html`
72
+ * @returns The path of the address, starting with a slash and without the site base
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * routeToPath('de/v1.x/index.md', false); // '/de/v1.x/'
77
+ * routeToPath('v1.x/guide.md', false); // '/v1.x/guide.html'
78
+ * routeToPath('v1.x/guide.md', true); // '/v1.x/guide'
79
+ * ```
80
+ *
81
+ * @since 3.0.0
82
+ */
83
+
84
+ export function routeToPath(route: string, cleanUrls: boolean): string {
85
+ return `/${ route.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, cleanUrls ? '' : '.html') }`;
86
+ }
87
+
88
+ /**
89
+ * Splits a route into its locale, its version, and the page inside them.
90
+ *
91
+ * @param route - A route such as `de/v1.x/guide.md`
92
+ * @param versioning - The versioning data that names the versions and the locale prefixes
93
+ * @returns The parts of the route, with an empty `locale` for the root locale and an empty `version` when it names none
94
+ *
95
+ * @remarks
96
+ * The page is written without `.md` and without a trailing `index`, so `guide.md` and `guide/index.md`,
97
+ * which VitePress serves for the same address, give the same page.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * splitRoute('de/v1.x/guide/index.md', versioning); // { locale: 'de', version: 'v1.x', page: 'guide' }
102
+ * splitRoute('v1.x/index.md', versioning); // { locale: '', version: 'v1.x', page: '' }
103
+ * ```
104
+ *
105
+ * @since 3.0.0
106
+ */
107
+
108
+ export function splitRoute(route: string, versioning: VersioningPluginInterface): RoutePartsInterface {
109
+ const segments = route.split('/');
110
+ const locale = segments.length > 1 && (versioning.locales ?? []).includes(segments[0]) ? segments.shift()! : '';
111
+ const version = versioning.versions.includes(segments[0]) ? segments.shift()! : '';
112
+ const page = segments.join('/').replace(/(^|\/)index\.md$/, '').replace(/\.md$/, '');
113
+
114
+ return { locale, version, page };
115
+ }
116
+
117
+ /**
118
+ * Finds the page to open when the reader switches version or language onto a page that does not exist there.
119
+ *
120
+ * @param from - The route of the page the reader is on
121
+ * @param to - The route the reader asked for
122
+ * @param versioning - The versioning data that the plugin publishes in `themeConfig.versioning`
123
+ * @returns The route to open instead, or `undefined` to let the navigation through
124
+ *
125
+ * @remarks
126
+ * Only a switch is caught: `to` has to be the page of `from` with another version, another locale, or both.
127
+ * Any other address that no version publishes, typed or linked, keeps its not-found page.
128
+ *
129
+ * - Switching version opens the home page of the new version in the locale, then in the root locale.
130
+ * - Switching language opens the home page of the version in the new language,
131
+ * then the home page of the {@link VersioningPluginInterface.latestVersion | latest} version in it.
132
+ *
133
+ * When none of them exists either, the navigation goes through and shows the not-found page.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * // de has no guide in v2.x, and no pages at all in v1.x
138
+ * resolveSwitchRoute('v2.x/guide.md', 'de/v2.x/guide.md', versioning); // 'de/v2.x/index.md'
139
+ * resolveSwitchRoute('v1.x/hooks.md', 'de/v1.x/hooks.md', versioning); // 'de/v2.x/index.md'
140
+ * resolveSwitchRoute('v2.x/guide.md', 'v2.x/missing.md', versioning); // undefined, not a switch
141
+ * ```
142
+ *
143
+ * @since 3.0.0
144
+ */
145
+
146
+ export function resolveSwitchRoute(from: string, to: string, versioning: VersioningPluginInterface): string | undefined {
147
+ const published = new Set(Object.values(versioning.routes ?? {}).flat());
148
+ const find = (candidate: string): string | undefined =>
149
+ [ candidate, candidate.replace(/\.md$/, '/index.md') ].find(form => published.has(form));
150
+
151
+ if (find(to)) return;
152
+
153
+ const source = splitRoute(from, versioning);
154
+ const target = splitRoute(to, versioning);
155
+ if (!target.version || source.page !== target.page) return;
156
+ if (source.locale === target.locale && source.version === target.version) return;
157
+
158
+ const home = (...parts: Array<string>): string => [ ...parts.filter(Boolean), 'index.md' ].join('/');
159
+ const candidates = source.locale === target.locale
160
+ ? [ home(target.locale, target.version), home(target.version) ]
161
+ : [ home(target.locale, target.version), home(target.locale, versioning.latestVersion) ];
162
+
163
+ for (const candidate of candidates) {
164
+ const found = find(candidate);
165
+ if (found) return found;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Catches a switch of version or language onto a page that does not exist there, and opens the nearest page instead.
171
+ *
172
+ * @param router - The VitePress router, from the `enhanceApp` context
173
+ * @param siteData - The site data, from the `enhanceApp` context
174
+ *
175
+ * @remarks
176
+ * The version switcher already links to a page that exists, but VitePress's language menu links every page
177
+ * to the same page in each language, translated or not. The fallback hooks into `router.onBeforeRouteChange`,
178
+ * after any hook that the theme set before it, and hands such a switch to {@link resolveSwitchRoute},
179
+ * keeping the query and the hash. Every other navigation, the first load included, goes through untouched,
180
+ * so an address that does not exist still shows the not-found page.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * // .vitepress/theme/index.ts
185
+ * import { installVersionFallback } from '@viteplus/versions/fallback';
186
+ *
187
+ * export default {
188
+ * extends: DefaultTheme,
189
+ * enhanceApp({ app, router, siteData }) {
190
+ * app.component('VersionSwitcher', VersionSwitcher);
191
+ * installVersionFallback(router, siteData);
192
+ * }
193
+ * };
194
+ * ```
195
+ *
196
+ * @see resolveSwitchRoute
197
+ * @since 3.0.0
198
+ */
199
+
200
+ export function installVersionFallback(router: Router, siteData: Ref<SiteData>): void {
201
+ const previous = router.onBeforeRouteChange;
202
+
203
+ router.onBeforeRouteChange = async (to: string): Promise<void | boolean> => {
204
+ if (await previous?.(to) === false) return false;
205
+
206
+ const { base, cleanUrls, themeConfig } = siteData.value;
207
+ const versioning: VersioningPluginInterface | undefined = themeConfig?.versioning;
208
+ const from = router.route.data?.relativePath;
209
+ if (typeof window === 'undefined' || !versioning || !from) return;
210
+
211
+ const url = new URL(to, window.location.href);
212
+ if (!url.pathname.startsWith(base)) return;
213
+
214
+ const target = resolveSwitchRoute(from, pathToRoute(url.pathname.slice(base.length)), versioning);
215
+ if (!target) return;
216
+
217
+ await router.go(`${ base.replace(/\/$/, '') }${ routeToPath(target, !!cleanUrls) }${ url.search }${ url.hash }`);
218
+
219
+ return false;
220
+ };
221
+ }