svelte-docsmith 0.14.0 → 0.15.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.
Files changed (68) hide show
  1. package/dist/buildtime/paths.d.ts +5 -0
  2. package/dist/buildtime/paths.js +7 -0
  3. package/dist/buildtime/props/extract.d.ts +19 -0
  4. package/dist/buildtime/props/extract.js +158 -0
  5. package/dist/buildtime/props/parse.d.ts +17 -0
  6. package/dist/buildtime/props/parse.js +108 -0
  7. package/dist/buildtime/props/typescript.d.ts +54 -0
  8. package/dist/buildtime/props/typescript.js +345 -0
  9. package/dist/buildtime/vite/collect.js +22 -42
  10. package/dist/buildtime/vite/fields.d.ts +49 -0
  11. package/dist/buildtime/vite/fields.js +72 -0
  12. package/dist/buildtime/vite/frontmatter-schema.d.ts +38 -0
  13. package/dist/buildtime/vite/frontmatter-schema.js +96 -0
  14. package/dist/buildtime/vite/index.d.ts +16 -0
  15. package/dist/buildtime/vite/index.js +65 -2
  16. package/dist/buildtime/vite/pages.d.ts +5 -0
  17. package/dist/buildtime/vite/pages.js +10 -5
  18. package/dist/client.d.ts +24 -0
  19. package/dist/components/docs/accordion-item.svelte +2 -1
  20. package/dist/components/docs/accordion-item.svelte.d.ts +2 -1
  21. package/dist/components/docs/accordion.svelte +2 -1
  22. package/dist/components/docs/accordion.svelte.d.ts +2 -1
  23. package/dist/components/docs/badge.svelte +4 -3
  24. package/dist/components/docs/badge.svelte.d.ts +4 -3
  25. package/dist/components/docs/callout.svelte +6 -2
  26. package/dist/components/docs/callout.svelte.d.ts +6 -2
  27. package/dist/components/docs/card-grid.svelte +6 -1
  28. package/dist/components/docs/card-grid.svelte.d.ts +1 -0
  29. package/dist/components/docs/card.svelte +4 -2
  30. package/dist/components/docs/card.svelte.d.ts +4 -2
  31. package/dist/components/docs/file-tree-item.svelte +5 -2
  32. package/dist/components/docs/file-tree-item.svelte.d.ts +5 -2
  33. package/dist/components/docs/file-tree.svelte +6 -1
  34. package/dist/components/docs/file-tree.svelte.d.ts +1 -0
  35. package/dist/components/docs/kbd.svelte +6 -1
  36. package/dist/components/docs/kbd.svelte.d.ts +1 -0
  37. package/dist/components/docs/live-example.svelte +5 -2
  38. package/dist/components/docs/live-example.svelte.d.ts +5 -2
  39. package/dist/components/docs/prop.svelte +43 -12
  40. package/dist/components/docs/prop.svelte.d.ts +4 -0
  41. package/dist/components/docs/props-table.svelte +75 -6
  42. package/dist/components/docs/props-table.svelte.d.ts +9 -2
  43. package/dist/components/docs/step.svelte +1 -0
  44. package/dist/components/docs/step.svelte.d.ts +1 -0
  45. package/dist/components/docs/steps.svelte +6 -1
  46. package/dist/components/docs/steps.svelte.d.ts +1 -0
  47. package/dist/components/docs/tab-item.svelte +6 -2
  48. package/dist/components/docs/tab-item.svelte.d.ts +6 -2
  49. package/dist/components/docs/tabs.svelte +8 -4
  50. package/dist/components/docs/tabs.svelte.d.ts +8 -4
  51. package/dist/components/landing/action.svelte +5 -2
  52. package/dist/components/landing/action.svelte.d.ts +5 -2
  53. package/dist/components/landing/cta.svelte +4 -3
  54. package/dist/components/landing/cta.svelte.d.ts +4 -3
  55. package/dist/components/landing/feature-grid.svelte +7 -4
  56. package/dist/components/landing/feature-grid.svelte.d.ts +7 -4
  57. package/dist/components/landing/feature.svelte +1 -0
  58. package/dist/components/landing/feature.svelte.d.ts +1 -0
  59. package/dist/components/landing/hero.svelte +5 -5
  60. package/dist/components/landing/hero.svelte.d.ts +5 -5
  61. package/dist/core/content.d.ts +27 -0
  62. package/dist/core/extracted-props.d.ts +39 -0
  63. package/dist/core/extracted-props.js +1 -0
  64. package/dist/core/index.d.ts +1 -1
  65. package/dist/index.d.ts +2 -1
  66. package/dist/utils/type-text.d.ts +13 -0
  67. package/dist/utils/type-text.js +49 -0
  68. package/package.json +14 -2
@@ -0,0 +1,345 @@
1
+ /**
2
+ * The type half of props extraction: the TypeScript checker reads a
3
+ * component's props type the way svelte-check does, so a prop typed with an
4
+ * imported alias shows its resolved union rather than the alias name. See
5
+ * docs/adr/0006-own-extractor-on-typescript-checker.md.
6
+ *
7
+ * Each `.svelte` file is served to TypeScript as a virtual `X.svelte.ts`
8
+ * holding its svelte2tsx output. One language service lives per Vite root and
9
+ * is reused across props imports, so unchanged files aren't re-parsed.
10
+ *
11
+ * `typescript` and `svelte2tsx` are optional peer dependencies, loaded only when
12
+ * a page imports `?props`.
13
+ */
14
+ import fs from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import path from 'node:path';
17
+ export const MISSING_PEERS = 'Generated props tables need TypeScript. Install the optional peer ' +
18
+ 'dependencies with: npm i -D typescript svelte2tsx';
19
+ let loaded;
20
+ /** Load the optional peers once per process; `undefined` when not installed. */
21
+ export function loadPeers() {
22
+ loaded ??= (async () => {
23
+ try {
24
+ const [tsModule, s2t] = await Promise.all([import('typescript'), import('svelte2tsx')]);
25
+ const ts = (tsModule.default ?? tsModule);
26
+ const dir = path.dirname(createRequire(import.meta.url).resolve('svelte2tsx'));
27
+ const shims = ['svelte-shims-v4.d.ts', 'svelte-jsx-v4.d.ts'].map((f) => path.join(dir, f));
28
+ return { ts, svelte2tsx: s2t.svelte2tsx, shims };
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ })();
34
+ return loaded;
35
+ }
36
+ /** A file's modification time, or `-1` when it can't be read. */
37
+ export function mtimeOf(file) {
38
+ try {
39
+ return fs.statSync(file).mtimeMs;
40
+ }
41
+ catch {
42
+ return -1;
43
+ }
44
+ }
45
+ /** Whether a path lies inside a `node_modules` directory, on any platform. */
46
+ export function inNodeModules(file) {
47
+ return /[\\/]node_modules[\\/]/.test(file);
48
+ }
49
+ const formatFlags = (ts) => ts.TypeFormatFlags.NoTruncation |
50
+ ts.TypeFormatFlags.UseSingleQuotesForStringLiteralType |
51
+ ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
52
+ export function createPropsTypeChecker({ ts, svelte2tsx, shims }, options) {
53
+ const compilerOptions = readCompilerOptions(ts, options.root, options.tsconfig);
54
+ const roots = new Set();
55
+ const generated = new Map();
56
+ const mtime = mtimeOf;
57
+ // `X.svelte.ts` stands for `X.svelte` unless a real `X.svelte.ts` (a runes
58
+ // module) exists.
59
+ const isVirtual = (file) => file.endsWith('.svelte.ts') && !ts.sys.fileExists(file) && ts.sys.fileExists(file.slice(0, -3));
60
+ /** The file on disk a program file stands for. */
61
+ const onDisk = (file) => (isVirtual(file) ? file.slice(0, -3) : file);
62
+ const readVirtual = (file) => {
63
+ const svelteFile = file.slice(0, -3);
64
+ const time = mtime(svelteFile);
65
+ const cached = generated.get(svelteFile);
66
+ if (cached && cached.mtime === time)
67
+ return cached.code;
68
+ const { code } = svelte2tsx(fs.readFileSync(svelteFile, 'utf-8'), {
69
+ filename: svelteFile,
70
+ isTsFile: true,
71
+ mode: 'ts',
72
+ version: options.svelteVersion
73
+ });
74
+ generated.set(svelteFile, { mtime: time, code });
75
+ return code;
76
+ };
77
+ const fileExists = (file) => isVirtual(file) || ts.sys.fileExists(file);
78
+ const readFile = (file) => (isVirtual(file) ? readVirtual(file) : ts.sys.readFile(file));
79
+ const resolutionHost = {
80
+ fileExists,
81
+ readFile,
82
+ directoryExists: ts.sys.directoryExists,
83
+ realpath: ts.sys.realpath,
84
+ getCurrentDirectory: () => options.root,
85
+ getDirectories: ts.sys.getDirectories
86
+ };
87
+ const host = {
88
+ getCompilationSettings: () => compilerOptions,
89
+ getScriptFileNames: () => [...shims, ...roots],
90
+ getScriptVersion: (file) => String(mtime(onDisk(file))),
91
+ getScriptSnapshot: (file) => {
92
+ const text = readFile(file);
93
+ return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);
94
+ },
95
+ getCurrentDirectory: () => options.root,
96
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
97
+ fileExists,
98
+ readFile,
99
+ directoryExists: ts.sys.directoryExists,
100
+ getDirectories: ts.sys.getDirectories,
101
+ realpath: ts.sys.realpath,
102
+ resolveModuleNameLiterals(literals, containingFile, redirected, opts, containingSourceFile) {
103
+ return literals.map((literal) => resolveModule(literal.text, containingFile, opts, redirected, {
104
+ mode: ts.getModeForUsageLocation(containingSourceFile, literal, opts)
105
+ }));
106
+ }
107
+ };
108
+ // A `.svelte` specifier resolves like its `.svelte.js` twin, which every
109
+ // resolution mode maps onto the virtual `.svelte.ts`. That keeps relative
110
+ // imports, package `imports` (`#lib/…`) and tsconfig `paths` working.
111
+ function resolveModule(name, containingFile, opts = compilerOptions, redirected, { mode } = {}) {
112
+ const resolve = (spec) => ts.resolveModuleName(spec, containingFile, opts, resolutionHost, undefined, redirected, mode);
113
+ const result = resolve(name);
114
+ if (result.resolvedModule || !name.endsWith('.svelte'))
115
+ return result;
116
+ return resolve(name + '.js');
117
+ }
118
+ const service = ts.createLanguageService(host, ts.createDocumentRegistry());
119
+ // The project files a component pulls in (its type imports included), so
120
+ // editing a shared `types.ts` re-extracts the props that use it.
121
+ const dependencies = (program, entry) => {
122
+ const seen = new Set([entry.fileName]);
123
+ const queue = [entry.fileName];
124
+ for (let file = queue.shift(); file; file = queue.shift()) {
125
+ const text = program.getSourceFile(file)?.text ?? '';
126
+ for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
127
+ const target = resolveModule(fileName, file).resolvedModule?.resolvedFileName;
128
+ if (!target || inNodeModules(target) || seen.has(target))
129
+ continue;
130
+ seen.add(target);
131
+ queue.push(target);
132
+ }
133
+ }
134
+ return [...seen].map(onDisk);
135
+ };
136
+ return {
137
+ read(files) {
138
+ for (const file of files)
139
+ roots.add(file + '.ts');
140
+ const program = service.getProgram();
141
+ return files.map((file) => {
142
+ try {
143
+ const source = program?.getSourceFile(file + '.ts');
144
+ if (!program || !source)
145
+ return undefined;
146
+ const typed = readProps(ts, program, source);
147
+ return typed && { ...typed, files: dependencies(program, source) };
148
+ }
149
+ catch (error) {
150
+ return error instanceof Error ? error : new Error(String(error));
151
+ }
152
+ });
153
+ }
154
+ };
155
+ }
156
+ function readCompilerOptions(ts, root, tsconfig) {
157
+ const configFile = tsconfig
158
+ ? path.resolve(root, tsconfig)
159
+ : ts.findConfigFile(root, ts.sys.fileExists, 'tsconfig.json');
160
+ let base = {
161
+ target: ts.ScriptTarget.ESNext,
162
+ module: ts.ModuleKind.ESNext,
163
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
164
+ strict: true
165
+ };
166
+ if (configFile && ts.sys.fileExists(configFile)) {
167
+ const parsed = ts.getParsedCommandLineOfConfigFile(configFile, {}, {
168
+ ...ts.sys,
169
+ onUnRecoverableConfigFileDiagnostic: () => { }
170
+ });
171
+ if (parsed)
172
+ base = parsed.options;
173
+ }
174
+ return {
175
+ ...base,
176
+ allowJs: true,
177
+ skipLibCheck: true,
178
+ noEmit: true,
179
+ declaration: false,
180
+ composite: false,
181
+ incremental: false
182
+ };
183
+ }
184
+ function readProps(ts, program, source) {
185
+ const typeNode = findPropsTypeNode(ts, source);
186
+ if (!typeNode)
187
+ return undefined;
188
+ const checker = program.getTypeChecker();
189
+ const flags = formatFlags(ts);
190
+ const propsType = checker.getTypeFromTypeNode(typeNode);
191
+ const isExternal = (sf) => program.isSourceFileFromExternalLibrary(sf) ||
192
+ program.isSourceFileDefaultLibrary(sf) ||
193
+ inNodeModules(sf.fileName);
194
+ const declaredOutside = (symbol) => {
195
+ const declarations = symbol.getDeclarations() ?? [];
196
+ return declarations.length > 0 && declarations.every((d) => isExternal(d.getSourceFile()));
197
+ };
198
+ // A prop typed with an alias from a library (`ClassValue`) keeps its name:
199
+ // expanding it would print the library's internals. Project aliases fall
200
+ // through to `printPropType`, which expands them.
201
+ const libraryAlias = (symbol) => {
202
+ const declaration = symbol.valueDeclaration;
203
+ if (!declaration || !ts.isPropertySignature(declaration) || !declaration.type)
204
+ return;
205
+ const declared = checker.getTypeFromTypeNode(declaration.type);
206
+ const alias = declared.aliasSymbol?.getDeclarations() ?? [];
207
+ if (alias.length === 0 || !alias.every((d) => isExternal(d.getSourceFile())))
208
+ return;
209
+ return checker.typeToString(declared, typeNode, flags);
210
+ };
211
+ const props = [];
212
+ let anyInherited = false;
213
+ for (const symbol of checker.getPropertiesOfType(propsType)) {
214
+ if (declaredOutside(symbol)) {
215
+ anyInherited = true;
216
+ continue;
217
+ }
218
+ const optional = (symbol.flags & ts.SymbolFlags.Optional) !== 0;
219
+ const tags = symbol.getJsDocTags(checker);
220
+ const tag = (name) => {
221
+ const found = tags.find((t) => t.name === name);
222
+ return found ? ts.displayPartsToString(found.text ?? []).trim() : undefined;
223
+ };
224
+ const description = ts.displayPartsToString(symbol.getDocumentationComment(checker)).trim();
225
+ props.push({
226
+ name: symbol.name,
227
+ type: libraryAlias(symbol) ??
228
+ printPropType(ts, checker, checker.getTypeOfSymbol(symbol), optional, typeNode, flags),
229
+ optional,
230
+ description: description || undefined,
231
+ deprecated: tag('deprecated'),
232
+ defaultTag: tag('default'),
233
+ internal: tag('internal') !== undefined
234
+ });
235
+ }
236
+ const inherited = anyInherited
237
+ ? inheritedGroups(ts, program, checker, propsType, declaredOutside, typeNode, flags)
238
+ : [];
239
+ return { props, inherited, files: [] };
240
+ }
241
+ /** The type annotation on the `$props()` declaration in the svelte2tsx output. */
242
+ function findPropsTypeNode(ts, source) {
243
+ let found;
244
+ const visit = (node) => {
245
+ if (found)
246
+ return;
247
+ if (ts.isVariableDeclaration(node) &&
248
+ node.initializer &&
249
+ ts.isCallExpression(node.initializer) &&
250
+ ts.isIdentifier(node.initializer.expression) &&
251
+ node.initializer.expression.text === '$props') {
252
+ found = node.type;
253
+ return;
254
+ }
255
+ ts.forEachChild(node, visit);
256
+ };
257
+ visit(source);
258
+ return found;
259
+ }
260
+ /** `Snippet<[]>` is how the checker spells a bare `Snippet`. */
261
+ const bareSnippet = (type) => type.replace(/\bSnippet<\[\]>/g, 'Snippet');
262
+ /**
263
+ * A union prints member by member: an alias of literals (`BadgeVariant`)
264
+ * expands to its values, and the `undefined` an optional prop picks up is
265
+ * dropped. Any other type prints as written (`Snippet`, `Item[]`, `T`).
266
+ */
267
+ function printPropType(ts, checker, type, optional, enclosing, flags) {
268
+ if (!type.isUnion())
269
+ return bareSnippet(checker.typeToString(type, enclosing, flags));
270
+ let members = type.types.filter((t) => !(optional && t.flags & ts.TypeFlags.Undefined));
271
+ const booleans = members.filter((t) => t.flags & ts.TypeFlags.BooleanLiteral);
272
+ const parts = [];
273
+ let wroteBoolean = false;
274
+ if (booleans.length === 2) {
275
+ members = members.filter((t) => !booleans.includes(t));
276
+ wroteBoolean = true;
277
+ }
278
+ for (const member of members)
279
+ parts.push(bareSnippet(checker.typeToString(member, enclosing, flags)));
280
+ if (wroteBoolean)
281
+ parts.push('boolean');
282
+ if (parts.length === 1)
283
+ return parts[0];
284
+ return parts.map((p) => (p.includes('=>') ? `(${p})` : p)).join(' | ');
285
+ }
286
+ /**
287
+ * Name what the external props came from: each part of the props intersection
288
+ * (or base of the props interface) whose props are all declared outside the
289
+ * project. An element's attributes (`HTMLAnchorAttributes`) are named by tag.
290
+ */
291
+ function inheritedGroups(ts, program, checker, propsType, declaredOutside, enclosing, flags) {
292
+ const parts = [];
293
+ const collect = (type) => {
294
+ if (type.isIntersection()) {
295
+ type.types.forEach(collect);
296
+ return;
297
+ }
298
+ const props = checker.getPropertiesOfType(type);
299
+ if (props.length > 0 && props.every(declaredOutside)) {
300
+ parts.push(type);
301
+ return;
302
+ }
303
+ const target = type.target ?? type;
304
+ if (target.isClassOrInterface()) {
305
+ for (const base of checker.getBaseTypes(target))
306
+ collect(base);
307
+ }
308
+ };
309
+ collect(propsType);
310
+ const tags = elementTags(program, checker);
311
+ const groups = parts.map((type) => {
312
+ const tag = tags.get(type);
313
+ return tag
314
+ ? { kind: 'element', label: tag }
315
+ : { kind: 'type', label: checker.typeToString(type, enclosing, flags) };
316
+ });
317
+ return groups.length > 0 ? groups : [{ kind: 'type', label: 'more inherited attributes' }];
318
+ }
319
+ /**
320
+ * Attribute types that belong to exactly one tag in Svelte's
321
+ * `SvelteHTMLElements` map (`HTMLAnchorAttributes` → `a`). Shared types like
322
+ * `HTMLAttributes<HTMLElement>` map to many tags, so they keep their name.
323
+ */
324
+ function elementTags(program, checker) {
325
+ const tags = new Map();
326
+ const elements = program
327
+ .getSourceFiles()
328
+ .find((sf) => /[\\/]svelte[\\/]elements\.d\.ts$/.test(sf.fileName));
329
+ const moduleSymbol = elements && checker.getSymbolAtLocation(elements);
330
+ const map = moduleSymbol &&
331
+ checker.getExportsOfModule(moduleSymbol).find((s) => s.name === 'SvelteHTMLElements');
332
+ if (!map)
333
+ return tags;
334
+ const shared = new Set();
335
+ for (const entry of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(map))) {
336
+ const type = checker.getTypeOfSymbol(entry);
337
+ if (tags.has(type))
338
+ shared.add(type);
339
+ else
340
+ tags.set(type, entry.name);
341
+ }
342
+ for (const type of shared)
343
+ tags.delete(type);
344
+ return tags;
345
+ }
@@ -7,9 +7,10 @@
7
7
  */
8
8
  import path from 'node:path';
9
9
  import { firstSegmentUnder } from '../../utils/url.js';
10
- import { docsBaseFrom, urlFor } from '../paths.js';
10
+ import { docsBaseFrom, relativeToCwd, urlFor } from '../paths.js';
11
11
  import { titleOf } from './pages.js';
12
12
  import { extractLlmsContent, extractSearchText, extractToc, readingMinutes } from './extract.js';
13
+ import { customFields, readField } from './fields.js';
13
14
  /**
14
15
  * Resolve every titled page against the site's layout. Shared by all three
15
16
  * indexes so they can never disagree about which pages exist or where they live.
@@ -46,45 +47,23 @@ function indexedPages(pages, options) {
46
47
  return archived ? archived.id : versions.current.id;
47
48
  }
48
49
  }
49
- /**
50
- * Read a page's `section` frontmatter: a string is one level, an array is a
51
- * nested group path. Non-string array members are dropped; anything else is
52
- * treated as no section.
53
- */
54
- function readSection(value) {
55
- if (typeof value === 'string')
56
- return value;
57
- if (Array.isArray(value)) {
58
- const segs = value.filter((s) => typeof s === 'string');
59
- return segs.length ? segs : undefined;
60
- }
61
- return undefined;
62
- }
63
50
  /** The most-specific (last) group segment, for the compact search-result pill. */
64
- function sectionLabel(value) {
65
- const section = readSection(value);
66
- if (section === undefined)
67
- return undefined;
51
+ function sectionLabel(front) {
52
+ const section = readField(front, 'section');
68
53
  return Array.isArray(section) ? section[section.length - 1] : section;
69
54
  }
70
55
  /** The full group path joined, so nested pages group under one llms.txt heading. */
71
- function sectionKey(value) {
72
- const section = readSection(value);
73
- if (section === undefined)
74
- return undefined;
56
+ function sectionKey(front) {
57
+ const section = readField(front, 'section');
75
58
  return Array.isArray(section) ? section.join(' / ') : section;
76
59
  }
77
60
  /**
78
- * A frontmatter field, when it holds the type the index expects. Frontmatter is
79
- * whatever the author typed, so a field of the wrong type is dropped rather than
80
- * carried into the index as one.
61
+ * A page's custom fields, or `undefined` when it has none, so a page without
62
+ * them adds nothing to the eagerly-loaded content index.
81
63
  */
82
- function stringField(front, key) {
83
- return typeof front[key] === 'string' ? front[key] : undefined;
84
- }
85
- /** As {@link stringField}, for the numeric fields. */
86
- function numberField(front, key) {
87
- return typeof front[key] === 'number' ? front[key] : undefined;
64
+ function dataOf(front) {
65
+ const fields = customFields(front);
66
+ return Object.keys(fields).length ? fields : undefined;
88
67
  }
89
68
  /**
90
69
  * The sidebar's index: the frontmatter fields navigation needs, plus the heading
@@ -98,14 +77,15 @@ export function contentIndex(pages, options) {
98
77
  return indexedPages(pages, options).map((page) => ({
99
78
  title: page.title,
100
79
  path: page.url,
101
- description: stringField(page.frontmatter, 'description'),
102
- section: readSection(page.frontmatter.section),
103
- order: numberField(page.frontmatter, 'order'),
104
- sourcePath: path.relative(process.cwd(), page.file).split(path.sep).join('/'),
80
+ description: readField(page.frontmatter, 'description'),
81
+ section: readField(page.frontmatter, 'section'),
82
+ order: readField(page.frontmatter, 'order'),
83
+ sourcePath: relativeToCwd(page.file),
105
84
  lastUpdated: page.lastUpdated,
106
85
  readingTime: readingMinutes(extractSearchText(page.source)),
107
86
  toc: extractToc(page.source),
108
- version: page.version
87
+ version: page.version,
88
+ data: dataOf(page.frontmatter)
109
89
  }));
110
90
  }
111
91
  /**
@@ -117,8 +97,8 @@ export function searchIndex(pages, options) {
117
97
  return indexedPages(pages, options).map((page) => ({
118
98
  path: page.url,
119
99
  title: page.title,
120
- section: sectionLabel(page.frontmatter.section),
121
- description: stringField(page.frontmatter, 'description'),
100
+ section: sectionLabel(page.frontmatter),
101
+ description: readField(page.frontmatter, 'description'),
122
102
  headings: extractToc(page.source).map((entry) => entry.title),
123
103
  text: extractSearchText(page.source),
124
104
  version: page.version
@@ -133,9 +113,9 @@ export function llmsIndex(pages, options) {
133
113
  return indexedPages(pages, options).map((page) => ({
134
114
  path: page.url,
135
115
  title: page.title,
136
- section: sectionKey(page.frontmatter.section),
137
- order: numberField(page.frontmatter, 'order'),
138
- description: stringField(page.frontmatter, 'description'),
116
+ section: sectionKey(page.frontmatter),
117
+ order: readField(page.frontmatter, 'order'),
118
+ description: readField(page.frontmatter, 'description'),
139
119
  content: extractLlmsContent(page.source, page.title),
140
120
  version: page.version
141
121
  }));
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The built-in fields: the frontmatter keys svelte-docsmith reads itself, each
3
+ * with the one reader that decides what a valid value is. Every other key is a
4
+ * custom field, carried as written.
5
+ *
6
+ * One table, read three ways: the index builders project a page through these
7
+ * readers, the frontmatter check reports a set key whose reader returns
8
+ * `undefined`, and custom fields are whatever the table doesn't name. Spelling a
9
+ * rule twice is how the checker and the indexes came to disagree about what
10
+ * `order: Infinity` or `section: [Guides, 3]` means.
11
+ */
12
+ export declare const BUILTIN_FIELDS: {
13
+ title: {
14
+ read: (value: unknown) => string | undefined;
15
+ expected: string;
16
+ };
17
+ description: {
18
+ read: (value: unknown) => string | undefined;
19
+ expected: string;
20
+ };
21
+ /** A string is one sidebar group; a list of strings is a nested group path. */
22
+ section: {
23
+ read: (value: unknown) => string | string[] | undefined;
24
+ expected: string;
25
+ };
26
+ order: {
27
+ read: (value: unknown) => number | undefined;
28
+ expected: string;
29
+ };
30
+ lastUpdated: {
31
+ read: (value: unknown) => string | undefined;
32
+ expected: string;
33
+ };
34
+ };
35
+ export type BuiltinKey = keyof typeof BUILTIN_FIELDS;
36
+ /** A built-in field's value, when the page sets it to something valid. */
37
+ export declare function readField<K extends BuiltinKey>(frontmatter: Record<string, unknown>, key: K): ReturnType<(typeof BUILTIN_FIELDS)[K]['read']>;
38
+ /** The built-in fields a page sets to something no reader accepts. */
39
+ export declare function invalidFields(frontmatter: Record<string, unknown>): {
40
+ key: BuiltinKey;
41
+ expected: string;
42
+ }[];
43
+ /** A page's custom fields: every key the table doesn't name, as written. */
44
+ export declare function customFields(frontmatter: Record<string, unknown>): Record<string, unknown>;
45
+ /**
46
+ * The built-in field a custom key was probably meant to be: one edit away
47
+ * (`ordr`, `tilte`, `sections`) or the same key in another case (`Title`).
48
+ */
49
+ export declare function likelyTypoOf(key: string): BuiltinKey | undefined;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The built-in fields: the frontmatter keys svelte-docsmith reads itself, each
3
+ * with the one reader that decides what a valid value is. Every other key is a
4
+ * custom field, carried as written.
5
+ *
6
+ * One table, read three ways: the index builders project a page through these
7
+ * readers, the frontmatter check reports a set key whose reader returns
8
+ * `undefined`, and custom fields are whatever the table doesn't name. Spelling a
9
+ * rule twice is how the checker and the indexes came to disagree about what
10
+ * `order: Infinity` or `section: [Guides, 3]` means.
11
+ */
12
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
13
+ const readString = (value) => (typeof value === 'string' ? value : undefined);
14
+ export const BUILTIN_FIELDS = {
15
+ title: { read: readString, expected: 'a string' },
16
+ description: { read: readString, expected: 'a string' },
17
+ /** A string is one sidebar group; a list of strings is a nested group path. */
18
+ section: {
19
+ read: (value) => {
20
+ if (typeof value === 'string')
21
+ return value;
22
+ const isPath = Array.isArray(value) && value.length > 0 && value.every((s) => typeof s === 'string');
23
+ return isPath ? value : undefined;
24
+ },
25
+ expected: 'a string or a list of strings'
26
+ },
27
+ order: {
28
+ read: (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined,
29
+ expected: 'a number'
30
+ },
31
+ lastUpdated: {
32
+ read: (value) => typeof value === 'string' && ISO_DAY.test(value) ? value : undefined,
33
+ expected: 'a YYYY-MM-DD date'
34
+ }
35
+ };
36
+ const isBuiltin = (key) => Object.hasOwn(BUILTIN_FIELDS, key);
37
+ /** A built-in field's value, when the page sets it to something valid. */
38
+ export function readField(frontmatter, key) {
39
+ return BUILTIN_FIELDS[key].read(frontmatter[key]);
40
+ }
41
+ /** The built-in fields a page sets to something no reader accepts. */
42
+ export function invalidFields(frontmatter) {
43
+ return Object.keys(frontmatter)
44
+ .filter(isBuiltin)
45
+ .filter((key) => BUILTIN_FIELDS[key].read(frontmatter[key]) === undefined)
46
+ .map((key) => ({ key, expected: BUILTIN_FIELDS[key].expected }));
47
+ }
48
+ /** A page's custom fields: every key the table doesn't name, as written. */
49
+ export function customFields(frontmatter) {
50
+ return Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !isBuiltin(key)));
51
+ }
52
+ /**
53
+ * The built-in field a custom key was probably meant to be: one edit away
54
+ * (`ordr`, `tilte`, `sections`) or the same key in another case (`Title`).
55
+ */
56
+ export function likelyTypoOf(key) {
57
+ return Object.keys(BUILTIN_FIELDS).find((builtin) => builtin.toLowerCase() === key.toLowerCase() || withinOneEdit(builtin, key));
58
+ }
59
+ /** Whether one insertion, deletion, substitution or adjacent swap turns `a` into `b`. */
60
+ function withinOneEdit(a, b) {
61
+ if (a === b || Math.abs(a.length - b.length) > 1)
62
+ return false;
63
+ let i = 0;
64
+ while (i < a.length && i < b.length && a[i] === b[i])
65
+ i++;
66
+ const rest = (x, skip) => x.slice(i + skip);
67
+ if (a.length === b.length) {
68
+ const swapped = a[i] === b[i + 1] && a[i + 1] === b[i] && rest(a, 2) === rest(b, 2);
69
+ return swapped || rest(a, 1) === rest(b, 1);
70
+ }
71
+ return a.length > b.length ? rest(a, 1) === rest(b, 0) : rest(a, 0) === rest(b, 1);
72
+ }
@@ -0,0 +1,38 @@
1
+ import type { SourcePage } from './pages.js';
2
+ /**
3
+ * The Standard Schema interface (https://standardschema.dev), copied whole as
4
+ * the spec asks, so no validation library becomes a dependency. Zod 3.24+,
5
+ * Valibot 1+ and ArkType 2+ schemas all satisfy it. Only `validate` is called;
6
+ * `types` is what each library's own infer helper reads.
7
+ */
8
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
9
+ readonly '~standard': {
10
+ readonly version: 1;
11
+ readonly vendor: string;
12
+ readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
13
+ readonly types?: {
14
+ readonly input: Input;
15
+ readonly output: Output;
16
+ } | undefined;
17
+ };
18
+ }
19
+ type StandardSchemaResult<Output> = {
20
+ readonly value: Output;
21
+ readonly issues?: undefined;
22
+ } | {
23
+ readonly issues: ReadonlyArray<StandardSchemaIssue>;
24
+ };
25
+ type StandardSchemaIssue = {
26
+ readonly message: string;
27
+ readonly path?: ReadonlyArray<PropertyKey | {
28
+ readonly key: PropertyKey;
29
+ }> | undefined;
30
+ };
31
+ /**
32
+ * Check every page that has a frontmatter block. Throws one error listing each
33
+ * page's problems; otherwise returns a warning about likely typos, if there
34
+ * are any. A page with no block is left alone: it is a stub the indexes skip,
35
+ * not something the author configured.
36
+ */
37
+ export declare function checkFrontmatter(pages: SourcePage[], schema?: StandardSchemaV1): Promise<string | undefined>;
38
+ export {};