@clarusjs/theme-docs 0.6.0 → 0.8.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.
@@ -0,0 +1,209 @@
1
+ // Versioned docs: each released line's docs kept at <base>v<version>/, built from its release tag and frozen. This
2
+ // file is the part with no I/O: the settings, which versions to archive, how an archived page is marked, and the
3
+ // navigation guards. versions-cli.js builds and fetches the archives; vite.js lists them for the version menu.
4
+ // @see https://clarusjs.com/docs-sites/versioned-docs
5
+
6
+ /**
7
+ * @typedef {object} Archived
8
+ * @property {string} version as shown and in the URL (/v0.19/): '0.19' before 1.0, '1' from it
9
+ * @property {string} tag the release tag it's built from
10
+ * @property {boolean} [retired] taken down: not served or listed; its URLs redirect to the latest docs
11
+ */
12
+ /**
13
+ * @typedef {object} VersionsFile versions.json, next to the site's Vite config
14
+ * @property {string} [tag] how releases are tagged, with {version}: 'v{version}' (the default), 'mylib@{version}'
15
+ * @property {string} [from] the first release to archive ('0.19.0'): docs older than it may not build under a base
16
+ * @property {'auto' | 'major' | 'minor'} [lines] how releases group into versions: 'auto' (the default) by minor before
17
+ * 1.0 and by major from it; 'major' or 'minor' always
18
+ * @property {number} [minors] by major: the newest major's latest minors are versions of their own too (2.4, 2.3 while
19
+ * 2.5 is live); they give way to the major's archive once the next major is out
20
+ * @property {number} [keep] serve at most this many archived versions, newest first; older ones are retired
21
+ * @property {string} [latest] the newest release, written by snapshot: deploys apply the rules above without git tags
22
+ * @property {string} [download] where archives are, with {tag} and {asset}; default: the repository's GitHub releases
23
+ * @property {string} [name] the project's name, for the banner ("the docs for <name> 0.19")
24
+ * @property {string} [out] the built site, from the site's folder (default dist/client)
25
+ * @property {string} [install] the install command (default: from the lockfile)
26
+ * @property {string} [build] the build command; {base} is the version's base path (default: from the lockfile)
27
+ * @property {Archived[]} [versions] the archived versions, newest first
28
+ */
29
+ /** @typedef {Required<Pick<VersionsFile, 'tag' | 'out'>> & VersionsFile & { repository?: string }} Settings */
30
+
31
+ /**
32
+ * The settings with their defaults; `repository` (package.json's) for the default download address.
33
+ * @param {VersionsFile} file
34
+ * @param {string} [repository]
35
+ * @returns {Settings}
36
+ */
37
+ export function settingsOf(file, repository) {
38
+ return { tag: 'v{version}', out: 'dist/client', ...file, repository }
39
+ }
40
+
41
+ /** The archive's file name. @param {string} version */
42
+ export const assetName = (version) => `docs-v${version}.tar.gz`
43
+
44
+ /**
45
+ * Where an archive downloads from.
46
+ * @param {Settings} s
47
+ * @param {Archived} entry
48
+ */
49
+ export function downloadUrl(s, entry) {
50
+ let pattern = s.download
51
+ if (!pattern) {
52
+ // https://github.com/o/r(.git), git+https…, git@github.com:o/r.git, github:o/r; dots are allowed in names
53
+ const repo = /github(?:\.com[/:]|:)([^/\s]+\/[^/\s#]+?)(?:\.git)?(?:[/#]|$)/.exec(s.repository ?? '')?.[1]
54
+ if (!repo) throw new Error('versions.json: set "download" (with {tag} and {asset}); no GitHub repository in package.json to default to')
55
+ pattern = `https://github.com/${repo}/releases/download/{tag}/{asset}`
56
+ }
57
+ return pattern.replace('{tag}', encodeURIComponent(entry.tag)).replace('{asset}', assetName(entry.version))
58
+ }
59
+
60
+ /**
61
+ * The line (archived version) a release belongs to: by `lines`, and the newest major's minors with `minors`.
62
+ * @param {string} v '2.3.1'
63
+ * @param {Partial<Settings>} [s]
64
+ * @param {number} [newestMajor]
65
+ */
66
+ export function lineOf(v, s = {}, newestMajor) {
67
+ const [major, minor] = /** @type {[string, string]} */ (v.split('.'))
68
+ const lines = s.lines ?? 'auto'
69
+ if (lines === 'minor' || (lines === 'auto' && major === '0')) return `${major}.${minor}`
70
+ return s.minors && Number(major) === newestMajor ? `${major}.${minor}` : major
71
+ }
72
+
73
+ /** A 1.0+ minor line under major grouping (`minors`), as opposed to a major or a 0.x minor. @param {string} line @param {Partial<Settings>} s */
74
+ const isMinorOfMajor = (line, s) => (s.lines ?? 'auto') !== 'minor' && line.includes('.') && !line.startsWith('0.')
75
+
76
+ /** @param {number[]} a @param {number[]} b */
77
+ const cmp = (a, b) => (a[0] ?? 0) - (b[0] ?? 0) || (a[1] ?? 0) - (b[1] ?? 0) || (a[2] ?? 0) - (b[2] ?? 0)
78
+
79
+ /**
80
+ * The versions to archive that aren't listed yet, newest first: the latest patch of each line from `from`, except the
81
+ * newest release's line (the live docs).
82
+ * @param {string[]} tags the repository's tags
83
+ * @param {Settings} s
84
+ * @param {Archived[]} listed
85
+ * @returns {Archived[]}
86
+ */
87
+ export function toArchive(tags, s, listed) {
88
+ const releases = releasesOf(tags, s)
89
+ const newest = newestOf(tags, s)
90
+ const from = (s.from ?? '0.0.0').split('.').map(Number)
91
+ /** @type {Map<string, { tag: string, v: number[] }>} */
92
+ const latest = new Map()
93
+ for (const { tag, v } of releases) {
94
+ if (cmp(v, from) < 0) continue
95
+ const line = lineOf(v.join('.'), s, newest[0])
96
+ const seen = latest.get(line)
97
+ if (!seen || cmp(v, seen.v) > 0) latest.set(line, { tag, v })
98
+ }
99
+ latest.delete(lineOf(newest.join('.'), s, newest[0]))
100
+ // The newest major's minors: only its latest `minors` (older ones would be retired at once)
101
+ const minors = [...latest].filter(([line]) => isMinorOfMajor(line, s)).sort(([, a], [, b]) => cmp(b.v, a.v))
102
+ for (const [line] of minors.slice(s.minors ?? 0)) latest.delete(line)
103
+ const skip = new Set(listed.map((a) => a.version))
104
+ return [...latest]
105
+ .filter(([line]) => !skip.has(line))
106
+ .sort(([, a], [, b]) => cmp(b.v, a.v))
107
+ .map(([version, { tag }]) => ({ version, tag }))
108
+ }
109
+
110
+ /** The releases among `tags` (by the `tag` pattern; no prereleases). @param {string[]} tags @param {Settings} s */
111
+ function releasesOf(tags, s) {
112
+ const [before = '', after = ''] = s.tag.split('{version}')
113
+ return tags.flatMap((tag) => {
114
+ if (!tag.startsWith(before) || !tag.endsWith(after)) return []
115
+ const version = tag.slice(before.length, tag.length - after.length)
116
+ return /^\d+\.\d+\.\d+$/.test(version) ? [{ tag, v: version.split('.').map(Number) }] : []
117
+ })
118
+ }
119
+
120
+ /** The newest release's version numbers ([] without any). @param {string[]} tags @param {Settings} s */
121
+ export function newestOf(tags, s) {
122
+ /** @type {number[]} */
123
+ let newest = []
124
+ for (const { v } of releasesOf(tags, s)) if (cmp(v, newest) > 0) newest = v
125
+ return newest
126
+ }
127
+
128
+ /**
129
+ * What a deploy serves, from versions.json alone: the archived versions listed, less those retired by hand, minors
130
+ * past `minors` (or of an older major than `latest`'s), and those past `keep`. A retired minor whose major is served
131
+ * redirects there (/v2.3/x → /v2/x); others to the latest docs (`to` '').
132
+ * @param {VersionsFile} file
133
+ * @returns {{ served: string[], retired: { version: string, to: string }[] }}
134
+ */
135
+ export function plan(file) {
136
+ const s = settingsOf(file)
137
+ const newestMajor = file.latest ? Number(file.latest.split('.')[0]) : undefined
138
+ /** @type {string[]} */ const served = []
139
+ /** @type {Archived[]} */ const retired = []
140
+ let minors = 0
141
+ for (const a of file.versions ?? []) {
142
+ let ok = !a.retired
143
+ if (ok && newestMajor !== undefined && isMinorOfMajor(a.version, s)) {
144
+ ok = Number(a.version.split('.')[0]) === newestMajor && ++minors <= (s.minors ?? 0)
145
+ }
146
+ if (ok && s.keep !== undefined && served.length >= s.keep) ok = false
147
+ if (ok) served.push(a.version)
148
+ else retired.push(a)
149
+ }
150
+ return {
151
+ served,
152
+ retired: retired.map((a) => {
153
+ const major = /** @type {string} */ (a.version.split('.')[0])
154
+ return { version: a.version, to: a.version.includes('.') && served.includes(major) ? major : '' }
155
+ }),
156
+ }
157
+ }
158
+
159
+ // Each version is its own build with its own runtime: a navigation between two must load the page, not swap it in.
160
+ // clarusjs takes over same-origin navigations (the Navigation API's navigate event); a listener registered before it,
161
+ // by an inline script in <head> (module scripts run after), stops the event reaching it for these.
162
+ // ponytail: relies on listener order; a framework opt-out (a navigation scope) would replace it.
163
+ /** @param {string} leaves the condition, on `p` (the destination's path) and `v(path)` (its version segment, or '') */
164
+ const guard = (leaves) =>
165
+ `window.navigation&&navigation.addEventListener('navigate',function(e){var p=new URL(e.destination.url).pathname;` +
166
+ String.raw`var v=function(x){var r=/\/(v\d+(?:\.\d+)?)(?:\/|$)/.exec(x);return r?r[1]:''};` +
167
+ `if(${leaves})e.stopImmediatePropagation()})`
168
+
169
+ /** An archived version's pages: navigations leaving its prefix (/v0.19/, under the base) load the page. @param {string} prefix */
170
+ export const archivedGuard = (prefix) => guard(`p.indexOf(${JSON.stringify(prefix)})!==0`)
171
+
172
+ /**
173
+ * Every page the theme renders (the live docs, and archives built with it): a navigation into another version (a
174
+ * /v0.19/ or /v1 segment, under any base) loads the page; within the same version it swaps as usual. A page of the
175
+ * site's own with such a segment would load instead of swap: slower, never wrong.
176
+ */
177
+ export const LATEST_GUARD = guard('v(p)!==v(location.pathname)')
178
+
179
+ const BANNER = 'old-version-banner'
180
+ // Inline, so it doesn't depend on the archived site's stylesheet; its colour tokens when it has them
181
+ const STYLE =
182
+ 'padding:8px 16px;text-align:center;font-size:14px;background:var(--surface,#f4f4f5);color:var(--fg,#18181b);' +
183
+ 'border-bottom:1px solid var(--rule,#d4d4d8)'
184
+
185
+ /**
186
+ * An archived page's HTML, marked: a banner after `<body…>` saying which version it is, with a link to the same page in
187
+ * the latest docs; in a full document, the navigation guard first in <head>, its canonical link pointed at the latest
188
+ * page, and noindex. Insertions only: built under its own base, its links already stay inside it.
189
+ * @param {string} html
190
+ * @param {{ version: string, path: string, base: string, name?: string }} o the page's path without the base
191
+ */
192
+ export function markSnapshot(html, { version, path, base, name }) {
193
+ if (html.includes(`class="${BANNER}"`)) return html
194
+ const latest = base.replace(/\/$/, '') + path || '/'
195
+ const banner =
196
+ `<div class="${BANNER}" role="note" style="${STYLE}">You're reading the docs for ${name ?? 'version'} ${version}. ` +
197
+ `<a href="${latest}">Same page in the latest docs</a></div>`
198
+ let out = html.replace(/<body\b[^>]*>/, (tag) => tag + banner)
199
+ if (!/<\/head>/.test(out)) return out
200
+ out = out.replace(/<head\b[^>]*>/, (tag) => `${tag}<script>${archivedGuard(`${base}v${version}/`)}</script>`)
201
+ out = out.replace(/<link rel="canonical" href="([^"]*)">/, (_, href) => `<link rel="canonical" href="${href.replace(`${base}v${version}/`, base).replace(/\/$/, path === '/' ? '/' : '')}">`)
202
+ return out.replace('</head>', '<meta name="robots" content="noindex"></head>')
203
+ }
204
+
205
+ /** A page's path from its file in the built site: 'guide/lists/index.html' → '/guide/lists'. @param {string} file */
206
+ export function pagePath(file) {
207
+ const p = file.replace(/(^|\/)index(\.frag)?\.html$/, '').replace(/\.html$/, '')
208
+ return /^(404|500)$/.test(p) ? '/' : '/' + p
209
+ }
package/src/vite.d.ts CHANGED
@@ -11,6 +11,12 @@ export type Options = {
11
11
  * write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
12
12
  */
13
13
  llms?: LlmsOptions;
14
+ /**
15
+ * versioned docs: the version menu, from versions.json next to the Vite config
16
+ * (`import versions from 'virtual:theme-docs/versions'`, passed as the theme config's `versions`); archived versions are
17
+ * built and added by the clarusjs-docs-versions command (https://clarusjs.com/docs-sites/versioned-docs)
18
+ */
19
+ versions?: VersionsOptions;
14
20
  /**
15
21
  * parts of the layout replaced by files of the site's own, from
16
22
  * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
@@ -18,6 +24,27 @@ export type Options = {
18
24
  components?: Partial<Record<PartName, string>>;
19
25
  };
20
26
  export type PartName = 'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer';
27
+ export type VersionsOptions = {
28
+ /**
29
+ * the live docs' version, as the menu shows it ('v0.20.0')
30
+ */
31
+ current: string;
32
+ /**
33
+ * more rows at the end of the menu (release notes, a changelog)
34
+ */
35
+ links?: {
36
+ label: string;
37
+ href: string;
38
+ }[];
39
+ /**
40
+ * list at most this many archived versions in the menu, newest first (the rest: `all`)
41
+ */
42
+ menu?: number;
43
+ /**
44
+ * a page listing every version (with the theme's version-list.tscl): an "All versions" row
45
+ */
46
+ all?: string;
47
+ };
21
48
  export type LlmsOptions = {
22
49
  /**
23
50
  * the site's name, the file's heading
package/src/vite.js CHANGED
@@ -8,19 +8,31 @@ import { fileURLToPath } from 'node:url'
8
8
  import { parse } from 'clarusjs/compiler'
9
9
  import { gitDates } from 'clarusjs/vite'
10
10
  import { CHUNK, termFile, tokens } from './search.js'
11
+ import { plan } from './versions.js'
11
12
 
12
13
  const ID = 'virtual:theme-docs/pages'
14
+ const VERSIONS_ID = 'virtual:theme-docs/versions'
13
15
 
14
16
  /**
15
17
  * @typedef {object} Options
16
18
  * @property {string} [pages] the pages folder, from the Vite root (default src/pages)
17
19
  * @property {boolean} [search] false: no search index (it's written to the client output's search/ after the build)
18
20
  * @property {LlmsOptions} [llms] write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
21
+ * @property {VersionsOptions} [versions] versioned docs: the version menu, from versions.json next to the Vite config
22
+ * (`import versions from 'virtual:theme-docs/versions'`, passed as the theme config's `versions`); archived versions are
23
+ * built and added by the clarusjs-docs-versions command (https://clarusjs.com/docs-sites/versioned-docs)
19
24
  * @property {Partial<Record<PartName, string>>} [components] parts of the layout replaced by files of the site's own, from
20
25
  * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
21
26
  */
22
27
 
23
28
  /** @typedef {'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer'} PartName */
29
+ /**
30
+ * @typedef {object} VersionsOptions
31
+ * @property {string} current the live docs' version, as the menu shows it ('v0.20.0')
32
+ * @property {{ label: string, href: string }[]} [links] more rows at the end of the menu (release notes, a changelog)
33
+ * @property {number} [menu] list at most this many archived versions in the menu, newest first (the rest: `all`)
34
+ * @property {string} [all] a page listing every version (with the theme's version-list.tscl): an "All versions" row
35
+ */
24
36
 
25
37
  /**
26
38
  * @typedef {object} LlmsOptions
@@ -97,6 +109,8 @@ export function themeDocs(options = {}) {
97
109
  let dir = resolve(options.pages ?? 'src/pages')
98
110
  /** @type {Map<string, string>} */
99
111
  let overrides = new Map()
112
+ /** @type {import('./versions.js').VersionsFile} */
113
+ let versionsFile = {}
100
114
  return {
101
115
  name: 'clarusjs:theme-docs',
102
116
  // Before Vite resolves the layout's relative import of a part itself.
@@ -106,11 +120,26 @@ export function themeDocs(options = {}) {
106
120
  api: {
107
121
  /** @param {string} root */
108
122
  clarusComponents: (root) => [...overridesOf(options.components ?? {}, root).values()],
123
+ // Archived versions are other builds, unpacked into this one after it (retired ones redirect): not missing pages.
124
+ clarusLinksIgnore: () => (versionsFile.versions ?? []).map((a) => `/v${a.version}/`),
125
+ },
126
+ // mermaid (an optional peer, for diagrams) pre-bundled when the site has it: otherwise dev finds it at the first
127
+ // diagram, re-optimizes and reloads the page, and a diagram whose import was in flight shows its source
128
+ /** @param {{ root?: string }} userConfig */
129
+ config(userConfig) {
130
+ // node_modules/mermaid from the root up, as Vite resolves it (not require.resolve: pnpm run's NODE_PATH would find
131
+ // it in the workspace's store for a site that doesn't depend on it)
132
+ for (let d = resolve(userConfig.root ?? process.cwd()); ; d = dirname(d)) {
133
+ if (existsSync(join(d, 'node_modules/mermaid/package.json'))) return { optimizeDeps: { include: ['mermaid'] } }
134
+ if (dirname(d) === d) return undefined
135
+ }
109
136
  },
110
137
  /** @param {{ root: string }} config */
111
138
  configResolved(config) {
112
139
  dir = resolve(config.root, options.pages ?? 'src/pages')
113
140
  overrides = overridesOf(options.components ?? {}, config.root)
141
+ const list = join(config.root, 'versions.json')
142
+ if (options.versions && existsSync(list)) versionsFile = JSON.parse(readFileSync(list, 'utf8'))
114
143
  },
115
144
  /**
116
145
  * @param {string} id
@@ -118,6 +147,7 @@ export function themeDocs(options = {}) {
118
147
  */
119
148
  resolveId(id, importer) {
120
149
  if (id === ID) return '\0' + ID
150
+ if (id === VERSIONS_ID) return '\0' + VERSIONS_ID
121
151
  // The layout's import of a part the site replaced (./parts/x.tscl from the theme): the site's file.
122
152
  // The query (?render: the layout rendered in the browser) stays on the site's file.
123
153
  if (overrides.size && importer && id.startsWith('./parts/')) {
@@ -129,6 +159,14 @@ export function themeDocs(options = {}) {
129
159
  },
130
160
  /** @param {string} id */
131
161
  load(id) {
162
+ if (id === '\0' + VERSIONS_ID) {
163
+ const v = options.versions
164
+ // The served versions only (versions.js plan(): retired by hand, by lines, minors or keep aren't)
165
+ const served = new Set(plan(versionsFile).served)
166
+ const archived = (versionsFile.versions ?? []).filter((a) => served.has(a.version)).map(({ version, tag }) => ({ version, tag }))
167
+ const data = v && { current: v.current, archived, links: v.links ?? [], ...(v.menu !== undefined && { menu: v.menu }), ...(v.all && { all: v.all }) }
168
+ return `export default ${JSON.stringify(data ?? null)}\n`
169
+ }
132
170
  return id === '\0' + ID ? `export default ${JSON.stringify(readPages(dir))}\n` : undefined
133
171
  },
134
172
  // After clarusjs has prerendered the site: the search index, from the built pages.
@@ -293,7 +331,8 @@ export function buildIndex(sections) {
293
331
  for (const [word, n] of uses) weights.set(word, Math.min(n, 3))
294
332
  for (const word of tokens(section.h)) weights.set(word, (weights.get(word) ?? 0) + 10)
295
333
  for (const [word, weight] of weights) {
296
- const shard = shards.get(termFile(word)) ?? shards.set(termFile(word), {}).get(termFile(word))
334
+ // No prototype: words like constructor and __proto__ are terms like any other.
335
+ const shard = shards.get(termFile(word)) ?? shards.set(termFile(word), Object.create(null)).get(termFile(word))
297
336
  ;(/** @type {Record<string, number[]>} */ (shard)[word] ??= []).push(id, weight)
298
337
  }
299
338
  }