diff --git a/CHANGELOG.md b/CHANGELOG.md index b7a2ddb..754291f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.8.0 + +Regenerated output changes for every provider: the front matter `description:` of every resource and service page. + +- docgen: per-page descriptions. Resource pages take the first sentence of the resource description (HTML tags and Markdown links stripped, inline code backticks dropped, entities decoded, whitespace collapsed, capped at 160 characters on a word boundary), falling back to `Query, deploy and manage the resource in the service using SQL` when the resource has none, so no resource page carries the former provider-wide line and no two share a description. Service index pages read `Query, deploy and manage resources using SQL`. The provider index page keeps the description from `headerContent1.txt`. Applies to `generateDocs` and `generateDocsv2` +- docgen: front matter descriptions are written as YAML double-quoted scalars (`JSON.stringify`), so a description containing a colon, quotes, `#` or a newline still parses +- new helpers: `metaDescription(text, fallback)`, `yamlString(value)` and `META_DESCRIPTION_MAX` in `src/docgen/helpers.js`; `resourceFallbackDescription(resourceName, providerName, serviceName)` in `src/docgen/resource/overview.js`. Covered by tests/docgen/descriptions.test.js + ## 0.7.12 - docgen: `generateDocsv2` (CLI: `generate-docs-v2`) ends each Provider Summary row with the two-space Markdown hard break the v1 template already uses, so `total services`, `total resources` and `source project` render on separate lines instead of one paragraph. v1 output is unchanged. Covered by tests/docgen/summary.test.js diff --git a/docs/docgen.md b/docs/docgen.md index 47f4234..8fec51b 100644 --- a/docs/docgen.md +++ b/docs/docgen.md @@ -193,6 +193,16 @@ Resource documentation includes: - Example queries - Request and response details +### Page descriptions + +Each generated page's front matter `description:` becomes its meta description (and the `WebPage.description` of any structured data built from it), so it is set per page rather than repeated across the site: + +- Resource pages: the first sentence of the resource's `description` in the provider spec, with HTML tags and Markdown links stripped (their text kept), inline code backticks dropped, entities decoded and whitespace collapsed, capped at 160 characters on a word boundary (`...` marks a cut). A resource with no description (or one that is empty after cleanup) gets `Query, deploy and manage the resource in the service using SQL`, so resource pages never share the provider-wide line or each other's description. +- Service index pages: `Query, deploy and manage resources using SQL`. +- The provider index page: whatever `headerContent1.txt` sets; docgen does not touch it. + +Values are written as YAML double-quoted scalars (`JSON.stringify`), so colons, quotes, `#` and newlines in a description cannot break the front matter. Applies to `generateDocs` and `generateDocsv2`. + ## Example Header Content Files ### headerContent1.txt diff --git a/package-lock.json b/package-lock.json index cabe8d2..0a00d7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@stackql/provider-utils", - "version": "0.7.12", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@stackql/provider-utils", - "version": "0.7.12", + "version": "0.8.0", "license": "MIT", "dependencies": { "@apidevtools/swagger-parser": "^10.1.1", diff --git a/package.json b/package.json index eda741b..566a7de 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@stackql/provider-utils", - "version": "0.7.12", + "version": "0.8.0", "description": "Utilities for building StackQL providers from OpenAPI specifications.", "type": "module", "main": "./src/index.js", diff --git a/src/docgen/generator.js b/src/docgen/generator.js index 12c9408..cbbc41d 100644 --- a/src/docgen/generator.js +++ b/src/docgen/generator.js @@ -4,6 +4,7 @@ import fs from 'fs'; import path from 'path'; import yaml from 'js-yaml'; import { createResourceIndexContent, createResourceIndexContentv2 } from './resource-content.js'; +import { yamlString } from './helpers.js'; import SwaggerParser from '@apidevtools/swagger-parser'; import * as deno_openapi_dereferencer from "@stackql/deno-openapi-dereferencer"; @@ -262,7 +263,7 @@ keywords: - infrastructure-as-code - configuration-as-data - cloud inventory -description: Query, deploy and manage ${providerName} resources using SQL +description: ${yamlString(`Query, deploy and manage ${providerName} ${serviceName} resources using SQL`)} custom_edit_url: null image: /img/stackql-${providerName}-provider-featured-image.png --- diff --git a/src/docgen/helpers.js b/src/docgen/helpers.js index 4f78a66..00e52ce 100644 --- a/src/docgen/helpers.js +++ b/src/docgen/helpers.js @@ -25,6 +25,87 @@ export function getIndefiniteArticle(resourceName) { return article; } +// Longest meta description a generated page carries; search engines cut +// the snippet at about this length anyway. +export const META_DESCRIPTION_MAX = 160; + +// Words whose trailing period does not end a sentence. +const NON_TERMINAL_ABBREVIATION = /(?:^|[\s(])(?:e\.g|i\.e|etc|vs|approx|incl|cf|inc|ltd|co|no)\.$/i; + +const HTML_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }; + +function decodeEntities(text) { + return text.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (match, entity) => { + if (entity[0] === '#') { + const code = entity[1] === 'x' || entity[1] === 'X' ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10); + const valid = Number.isFinite(code) && code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff); + return valid ? String.fromCodePoint(code) : match; + } + return HTML_ENTITIES[entity.toLowerCase()] ?? match; + }); +} + +// The first sentence: up to the first '.', '!' or '?' followed by whitespace +// or the end, skipping abbreviations such as "e.g.". The whole text when no +// sentence end is found. +function firstSentence(text) { + const end = /[.!?](?=\s|$)/g; + let match; + while ((match = end.exec(text)) !== null) { + const sentence = text.slice(0, match.index + 1); + if (!NON_TERMINAL_ABBREVIATION.test(sentence)) return sentence; + } + return text; +} + +/** + * The front matter `description:` (the page's meta description) for a + * generated page, derived from a description that may carry HTML and + * Markdown: HTML tags and Markdown links stripped (link text kept), inline + * code backticks and bold markers dropped, entities decoded, whitespace + * collapsed, then the first sentence, capped at META_DESCRIPTION_MAX + * characters on a word boundary ("..." marks a cut). + * @param {string} text - The source description (may be empty) + * @param {string} fallback - Returned as given (not capped) when nothing is + * left after cleanup + * @return {string} - Plain text: at most META_DESCRIPTION_MAX characters + * when derived from `text`, otherwise `fallback` + */ +export function metaDescription(text, fallback) { + const plain = decodeEntities( + String(text ?? '') + .replace(//g, ' ') + .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replace(/<\/?(?:br|p|div|li|ul|ol|tr|td|th|table|tbody|thead|h[1-6]|blockquote|pre)\b[^>]*>/gi, ' ') + .replace(/<\/?[a-z][^>]*>/gi, '') + .replace(/`/g, '') + .replace(/\*\*/g, '') + ) + .replace(/\s+/g, ' ') + .trim(); + if (!plain) return fallback; + + const sentence = firstSentence(plain); + if (sentence.length <= META_DESCRIPTION_MAX) return sentence; + const room = META_DESCRIPTION_MAX - 3; + let cut = sentence.slice(0, room + 1); + const space = cut.lastIndexOf(' '); + cut = space > 0 ? cut.slice(0, space) : sentence.slice(0, room); + return `${cut.replace(/[\s,;:.\-]+$/, '')}...`; +} + +/** + * A YAML double-quoted scalar for a front matter value. JSON string syntax + * is a subset of YAML's double-quoted style, so colons, quotes, '#' and + * newlines in the value cannot break the front matter. + * @param {string} value + * @return {string} + */ +export function yamlString(value) { + return JSON.stringify(String(value)); +} + /** * Sanitizes HTML with special handling for allowed tags and backticked content * @param {string} text - The text to sanitize diff --git a/src/docgen/resource/overview.js b/src/docgen/resource/overview.js index cce558b..0b87681 100644 --- a/src/docgen/resource/overview.js +++ b/src/docgen/resource/overview.js @@ -1,8 +1,21 @@ // src/docgen/resource/overview.js import { getIndefiniteArticle, + metaDescription, + yamlString, } from '../helpers.js'; +// The page's meta description: the resource description's first sentence +// when there is one, otherwise a line naming the resource, its service and +// the provider, so no two resource pages share a description. +export function resourceFallbackDescription(resourceName, providerName, serviceName) { + return `Query, deploy and manage the ${resourceName} resource in the ${providerName} ${serviceName} service using SQL`; +} + +function resourcePageDescription(resourceDescription, resourceName, providerName, serviceName) { + return yamlString(metaDescription(resourceDescription, resourceFallbackDescription(resourceName, providerName, serviceName))); +} + export function createOverviewSection(resourceName, resourceType, resourceDescription, providerName, serviceName) { let content = `--- @@ -16,7 +29,7 @@ keywords: - infrastructure-as-code - configuration-as-data - cloud inventory -description: Query, deploy and manage ${providerName} resources using SQL +description: ${resourcePageDescription(resourceDescription, resourceName, providerName, serviceName)} custom_edit_url: null image: /img/stackql-${providerName}-provider-featured-image.png --- @@ -56,7 +69,7 @@ keywords: - infrastructure-as-code - configuration-as-data - cloud inventory -description: Query, deploy and manage ${providerName} resources using SQL +description: ${resourcePageDescription(resourceDescription, resourceName, providerName, serviceName)} custom_edit_url: null image: /img/stackql-${providerName}-provider-featured-image.png --- diff --git a/tests/docgen/descriptions.test.js b/tests/docgen/descriptions.test.js new file mode 100644 index 0000000..05dd30c --- /dev/null +++ b/tests/docgen/descriptions.test.js @@ -0,0 +1,218 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import yaml from 'js-yaml'; +import { fileURLToPath } from 'url'; +import { generateDocs, generateDocsv2 } from '../../src/docgen/generator.js'; +import { metaDescription, yamlString, META_DESCRIPTION_MAX } from '../../src/docgen/helpers.js'; +import { resourceFallbackDescription } from '../../src/docgen/resource/overview.js'; + +// Per-page front matter descriptions: resource pages take the first +// sentence of the resource description, or a line naming the resource, +// service and provider; service index pages name the service; the provider +// index keeps the one in headerContent1.txt. + +const here = path.dirname(fileURLToPath(import.meta.url)); +const providerDir = path.join(here, 'src', 'homebrew', 'v00.00.00000'); +const providerDataDir = path.join(here, 'provider-data', 'homebrew'); +// The provider-wide line resource pages used to share; none may carry it now. +const PROVIDER_WIDE = 'Query, deploy and manage homebrew resources using SQL'; +const fallback = (resource) => `Query, deploy and manage the ${resource} resource in the homebrew formula service using SQL`; + +// The description of every generated resource page (resource -> description). +function resourceDescriptions(outputDir) { + const dir = path.join(outputDir, 'docs', 'services', 'formula'); + return Object.fromEntries(fs.readdirSync(dir, { withFileTypes: true }) + .filter((e) => e.isDirectory()) + .map((e) => [e.name, frontMatter(path.join(dir, e.name, 'index.md')).description])); +} + +const tmpDirs = []; +function tmpdir() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'docgen-descriptions-')); + tmpDirs.push(dir); + return dir; +} + +// The parsed front matter of a generated page. js-yaml throws on anything +// that is not valid YAML, which is part of what these tests check. +function frontMatter(file) { + const text = fs.readFileSync(file, 'utf8'); + const match = text.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n/); + if (!match) throw new Error(`no front matter in ${file}`); + return yaml.load(match[1]); +} + +const resourcePage = (outputDir, resource) => path.join(outputDir, 'docs', 'services', 'formula', resource, 'index.md'); + +// A copy of the homebrew fixture whose resources carry the descriptions +// given (resource name -> description; null deletes the description). +function fixtureWith(descriptions) { + const dir = tmpdir(); + fs.cpSync(providerDir, dir, { recursive: true }); + const file = path.join(dir, 'services', 'formula.yaml'); + const doc = yaml.load(fs.readFileSync(file, 'utf8')); + const resources = doc.components['x-stackQL-resources']; + for (const [name, description] of Object.entries(descriptions)) { + if (description === null) delete resources[name].description; + else resources[name].description = description; + } + fs.writeFileSync(file, yaml.dump(doc, { lineWidth: -1 })); + return dir; +} + +const silenced = {}; +beforeAll(() => { + // the generators log every service, resource and method they document + for (const level of ['log', 'info', 'warn', 'error']) { + silenced[level] = console[level]; + console[level] = () => {}; + } +}); + +afterAll(() => { + for (const level of Object.keys(silenced)) console[level] = silenced[level]; + for (const dir of tmpDirs) fs.rmSync(dir, { recursive: true, force: true }); +}); + +describe('metaDescription', () => { + test('strips HTML tags and Markdown links, keeping the text', () => { + expect(metaDescription('Lists formula entries from Homebrew.', 'x')) + .toBe('Lists formula entries from Homebrew.'); + expect(metaDescription('See [the API](https://formulae.brew.sh/docs/api/) for fields.', 'x')) + .toBe('See the API for fields.'); + expect(metaDescription('Line one
line two.', 'x')).toBe('Line one line two.'); + }); + + test('drops inline code backticks and decodes entities', () => { + expect(metaDescription('The `vw_info` view & friends.', 'x')).toBe('The vw_info view & friends.'); + // numeric entities decode, except surrogate code points, which stay as written + expect(metaDescription('A / B A � C.', 'x')).toBe('A / B A � C.'); + }); + + test('collapses whitespace and takes the first sentence', () => { + expect(metaDescription(' First sentence\n here. Second sentence. ', 'x')).toBe('First sentence here.'); + expect(metaDescription('Does it work? Yes.', 'x')).toBe('Does it work?'); + expect(metaDescription('No terminal punctuation', 'x')).toBe('No terminal punctuation'); + }); + + test('does not end a sentence at an abbreviation or inside a token', () => { + expect(metaDescription('Tools, e.g. brew, and more. Next.', 'x')).toBe('Tools, e.g. brew, and more.'); + expect(metaDescription('Runs on Node.js and v1.2 builds. Next.', 'x')).toBe('Runs on Node.js and v1.2 builds.'); + }); + + test(`caps at ${META_DESCRIPTION_MAX} characters on a word boundary`, () => { + const long = `${'word '.repeat(60).trim()}.`; + const out = metaDescription(long, 'x'); + expect(out.length).toBeLessThanOrEqual(META_DESCRIPTION_MAX); + expect(out).toMatch(/^(word )+word\.\.\.$/); + const unbroken = 'x'.repeat(300); + expect(metaDescription(unbroken, 'y')).toBe(`${'x'.repeat(META_DESCRIPTION_MAX - 3)}...`); + const exact = `${'a'.repeat(META_DESCRIPTION_MAX - 1)}.`; + expect(metaDescription(exact, 'y')).toBe(exact); + }); + + test('falls back when nothing is left', () => { + for (const empty of [undefined, null, '', ' \n ', '
', '']) { + expect(metaDescription(empty, 'fallback')).toBe('fallback'); + } + }); + + test('yamlString round-trips through js-yaml', () => { + for (const value of ['plain', 'a: b', 'say "hi"', "it's", 'line\nbreak', '# not a comment', '- not a list', 'tab\there', '{x}']) { + expect(yaml.load(`description: ${yamlString(value)}`)).toEqual({ description: value }); + } + }); +}); + +describe.each([ + ['generateDocs', generateDocs], + ['generateDocsv2', generateDocsv2], +])('%s front matter descriptions', (_, generate) => { + test('as-is fixture: the described resource gets its first sentence, the rest a per-resource fallback', async () => { + const out = tmpdir(); + await generate({ providerName: 'homebrew', providerDir, providerDataDir, outputDir: out }); + + expect(frontMatter(resourcePage(out, 'vw_info')).description) + .toBe('The vw_info view provides detailed information about the StackQL formula in the Homebrew package manager.'); + for (const resource of ['formula', 'vw_build_errors', 'vw_versions']) { + expect(frontMatter(resourcePage(out, resource)).description).toBe(fallback(resource)); + } + // no resource page carries the provider-wide line, and no two share one + const all = resourceDescriptions(out); + expect(Object.keys(all).length).toBeGreaterThan(5); + expect(Object.values(all)).not.toContain(PROVIDER_WIDE); + expect(new Set(Object.values(all)).size).toBe(Object.keys(all).length); + // service index names the service + expect(frontMatter(path.join(out, 'docs', 'services', 'formula', 'index.md')).description) + .toBe('Query, deploy and manage homebrew formula resources using SQL'); + // provider index keeps headerContent1.txt's description, whatever it says + expect(frontMatter(path.join(out, 'docs', 'index.md')).description) + .toBe(frontMatter(path.join(providerDataDir, 'headerContent1.txt')).description); + }, 30000); + + test('described resources get distinct descriptions that parse whatever they contain', async () => { + const descriptions = { + formula: 'Formula metadata: names, versions and taps.', + vw_info: 'Shows "info" for \'stackql\' only. Second sentence.', + vw_build_errors: 'Build errors\nper formula and OS.', + vw_conflicts: 'Conflicts between formula entries, see brew.', + vw_dependencies: 'Dependencies of each formula # with a hash.', + vw_lifecycle: '', + vw_urls: null, + }; + const out = tmpdir(); + await generate({ providerName: 'homebrew', providerDir: fixtureWith(descriptions), providerDataDir, outputDir: out }); + + const got = Object.fromEntries(Object.keys(descriptions).map((r) => [r, frontMatter(resourcePage(out, r)).description])); + expect(got).toEqual({ + formula: 'Formula metadata: names, versions and taps.', + vw_info: 'Shows "info" for \'stackql\' only.', + vw_build_errors: 'Build errors per formula and OS.', + vw_conflicts: 'Conflicts between formula entries, see brew.', + vw_dependencies: 'Dependencies of each formula # with a hash.', + vw_lifecycle: fallback('vw_lifecycle'), + vw_urls: fallback('vw_urls'), + }); + expect(new Set(Object.values(got)).size).toBe(Object.keys(descriptions).length); + + // every generated page's front matter is valid YAML + const pages = fs.readdirSync(path.join(out, 'docs', 'services', 'formula'), { recursive: true }) + .filter((f) => f.endsWith('index.md')); + expect(pages.length).toBeGreaterThan(1); + for (const page of pages) { + expect(() => frontMatter(path.join(out, 'docs', 'services', 'formula', page))).not.toThrow(); + } + }, 30000); + + test('resources without descriptions get different fallbacks naming the resource, service and provider', async () => { + // every resource stripped of its description + const names = Object.keys(resourceDescriptions(await (async () => { + const probe = tmpdir(); + await generate({ providerName: 'homebrew', providerDir, providerDataDir, outputDir: probe }); + return probe; + })())); + const out = tmpdir(); + await generate({ + providerName: 'homebrew', + providerDir: fixtureWith(Object.fromEntries(names.map((n) => [n, null]))), + providerDataDir, + outputDir: out, + }); + const got = resourceDescriptions(out); + + expect(got.vw_lifecycle).not.toBe(got.vw_urls); + for (const [resource, description] of Object.entries(got)) { + expect(description).toBe(fallback(resource)); + expect(description).toContain(resource); + expect(description).toContain('formula'); + expect(description).toContain('homebrew'); + } + expect(new Set(Object.values(got)).size).toBe(names.length); + }, 30000); +}); + +test('resourceFallbackDescription names the resource, provider and service', () => { + expect(resourceFallbackDescription('zones_settings', 'cloudflare', 'zones')) + .toBe('Query, deploy and manage the zones_settings resource in the cloudflare zones service using SQL'); +});