@ninjainfosys/site-kit 0.0.0-stage → 0.2.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 (48) hide show
  1. package/README.md +99 -2
  2. package/bin/site-kit.mjs +24 -0
  3. package/package.json +40 -4
  4. package/src/components/blog/Pager.astro +60 -0
  5. package/src/components/blog/PostCard.astro +53 -0
  6. package/src/components/blog/PostList.astro +21 -0
  7. package/src/components/blog/Story.astro +63 -0
  8. package/src/components/blog/Topics.astro +23 -0
  9. package/src/components/seo/Seo.astro +46 -0
  10. package/src/components/site/CtaBand.astro +21 -0
  11. package/src/components/site/DashainPopup.astro +324 -0
  12. package/src/components/site/Faq.astro +37 -0
  13. package/src/components/site/Footer.astro +66 -0
  14. package/src/components/site/Header.astro +311 -0
  15. package/src/components/site/Related.astro +44 -0
  16. package/src/config.ts +56 -0
  17. package/src/contract.ts +181 -0
  18. package/src/integration.d.mts +4 -0
  19. package/src/integration.mjs +96 -0
  20. package/src/layouts/Base.astro +65 -0
  21. package/src/lib/blog-schema.ts +60 -0
  22. package/src/lib/blog.ts +64 -0
  23. package/src/lib/glossary-types.ts +25 -0
  24. package/src/lib/glossary.ts +21 -0
  25. package/src/lib/posts.ts +22 -0
  26. package/src/lib/rehype-figures.mjs +25 -0
  27. package/src/lib/seo.ts +176 -0
  28. package/src/pages/blog/[slug].astro +274 -0
  29. package/src/pages/blog/index.astro +111 -0
  30. package/src/pages/blog/page/[page].astro +32 -0
  31. package/src/pages/blog/tag/[tag].astro +38 -0
  32. package/src/pages/glossary/[slug].astro +125 -0
  33. package/src/pages/glossary/index.astro +51 -0
  34. package/src/pages/llms.txt.ts +25 -0
  35. package/src/pages/og/[...slug].png.ts +61 -0
  36. package/src/pages/rss.xml.ts +23 -0
  37. package/src/scripts/a11y.mjs +38 -0
  38. package/src/scripts/check-credits.mjs +31 -0
  39. package/src/scripts/check-site.mjs +198 -0
  40. package/src/scripts/commons.mjs +106 -0
  41. package/src/scripts/config.mjs +19 -0
  42. package/src/scripts/indexnow.mjs +25 -0
  43. package/src/scripts/redirects.mjs +55 -0
  44. package/src/scripts/sitemap.mjs +173 -0
  45. package/src/styles/base.css +164 -0
  46. package/src/styles/blog-serif.css +2 -0
  47. package/src/styles/motion.css +20 -0
  48. package/src/virtual.d.ts +4 -0
@@ -0,0 +1,25 @@
1
+ import type { APIContext } from 'astro';
2
+ import { getCollection } from 'astro:content';
3
+ import { published } from '../lib/blog';
4
+ import { SITE_NAME, SITE_URL, kit } from '../config';
5
+
6
+ // Generated from the same data as the pages, so it never drifts.
7
+ export async function GET(_: APIContext) {
8
+ const posts = published(await getCollection('blog'));
9
+ const section = (s: { title: string; items: string[] }) => [`## ${s.title}`, '', ...s.items, ''];
10
+ const out = [
11
+ `# ${SITE_NAME}`,
12
+ '',
13
+ `> ${kit.llms.description}`,
14
+ '',
15
+ ...kit.llms.facts,
16
+ '',
17
+ ...kit.llms.before().flatMap(section),
18
+ ...section({
19
+ title: 'Blog',
20
+ items: posts.length ? posts.map((p) => `- [${p.data.title}](${SITE_URL}/blog/${p.id}): ${p.data.description}`) : ['- No posts yet'],
21
+ }),
22
+ ...kit.llms.after().flatMap(section),
23
+ ];
24
+ return new Response(out.join('\n'), { headers: { 'content-type': 'text/plain; charset=utf-8' } });
25
+ }
@@ -0,0 +1,61 @@
1
+ // One 1200x630 share image per page: the page's title on the site's stage
2
+ // colour with its mark. Built at build time with satori and resvg.
3
+ import type { APIContext } from 'astro';
4
+ import { getCollection } from 'astro:content';
5
+ import { readFileSync } from 'node:fs';
6
+ import { createRequire } from 'node:module';
7
+ import satori from 'satori';
8
+
9
+ // resvg is a native addon. Loading it with require at run time keeps Vite
10
+ // from trying to bundle its .node binary (which fails on Linux builders).
11
+ const { Resvg } = createRequire(import.meta.url)('@resvg/resvg-js') as typeof import('@resvg/resvg-js');
12
+ import { glossary } from '../../lib/glossary';
13
+ import { SITE_NAME, SITE_URL, kit } from '../../config';
14
+
15
+ const { og } = kit;
16
+ const face = og.font ?? { family: 'Poppins', package: 'poppins' };
17
+ const font = (w: number) => readFileSync(`node_modules/@fontsource/${face.package}/files/${face.package}-latin-${w}-normal.woff`);
18
+ const mark = `data:image/svg+xml;base64,${Buffer.from(readFileSync(`public/${og.mark.file}`, 'utf8').replace(og.mark.from ?? '', og.mark.fill ?? '')).toString('base64')}`;
19
+
20
+ export async function getStaticPaths() {
21
+ const posts = await getCollection('blog');
22
+ const pages: { slug: string; title: string }[] = [
23
+ ...og.pages(),
24
+ { slug: 'glossary', title: kit.glossary.ogTitle },
25
+ ...glossary.map((t) => ({ slug: `glossary/${t.slug}`, title: t.full ? `${t.term}: ${t.full}` : t.term })),
26
+ ...posts.map((p) => ({ slug: `blog/${p.id}`, title: p.data.title })),
27
+ ...[...new Set(posts.flatMap((p) => p.data.tags))].map((t) => ({ slug: `blog/tag/${t}`, title: `${t.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase())} articles` })),
28
+ ];
29
+ const n = Math.ceil(posts.length / 10);
30
+ for (let i = 2; i <= n; i++) pages.push({ slug: `blog/page/${i}`, title: `${kit.blog.name}, page ${i}` });
31
+ return pages.map((p) => ({ params: { slug: p.slug }, props: { title: p.title } }));
32
+ }
33
+
34
+ export async function GET({ props }: APIContext) {
35
+ const { title } = props as { title: string };
36
+ const svg = await satori(
37
+ {
38
+ type: 'div',
39
+ props: {
40
+ style: { width: 1200, height: 630, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 72, background: og.background, color: og.ink, fontFamily: face.family },
41
+ children: [
42
+ {
43
+ type: 'div',
44
+ props: {
45
+ style: { display: 'flex', alignItems: 'center', gap: 20 },
46
+ children: [
47
+ { type: 'img', props: { src: mark, width: og.mark.width, height: og.mark.height } },
48
+ { type: 'div', props: { style: { fontSize: og.name?.size ?? 40, fontWeight: og.name?.weight ?? 600 }, children: og.name?.text ?? SITE_NAME } },
49
+ ],
50
+ },
51
+ },
52
+ { type: 'div', props: { style: { fontSize: title.length > 40 ? 64 : 80, fontWeight: 600, lineHeight: 1.1, maxWidth: 1000 }, children: title } },
53
+ { type: 'div', props: { style: { fontSize: 30, color: og.muted }, children: new URL(SITE_URL).host } },
54
+ ],
55
+ },
56
+ },
57
+ { width: 1200, height: 630, fonts: [{ name: face.family, data: font(400), weight: 400 }, { name: face.family, data: font(600), weight: 600 }] },
58
+ );
59
+ const png = new Resvg(svg).render().asPng();
60
+ return new Response(png, { headers: { 'content-type': 'image/png' } });
61
+ }
@@ -0,0 +1,23 @@
1
+ import rss from '@astrojs/rss';
2
+ import { getCollection } from 'astro:content';
3
+ import type { APIContext } from 'astro';
4
+ import { published } from '../lib/blog';
5
+ import { kit } from '../config';
6
+
7
+ // Drafts never reach the feed, even on the dev server.
8
+ export async function GET(context: APIContext) {
9
+ const items = published(await getCollection('blog'));
10
+ return rss({
11
+ title: kit.blog.name,
12
+ description: kit.blog.rssDescription,
13
+ site: context.site!,
14
+ items: items.map((p) => ({
15
+ title: p.data.title,
16
+ description: p.data.description,
17
+ pubDate: p.data.date,
18
+ link: `/blog/${p.id}`,
19
+ categories: p.data.tags,
20
+ })),
21
+ customData: '<language>en</language>',
22
+ });
23
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // axe-core WCAG 2.2 AA scan of every built page at phone and desktop width,
3
+ // using the installed Chrome. Serve dist first: pnpm exec astro preview --port 4363
4
+ import { createRequire } from 'node:module';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ // puppeteer-core and axe-core are the site's own dev dependencies, found from where the command runs.
10
+ const siteRequire = createRequire(`${process.cwd()}/`);
11
+ const puppeteer = (await import(pathToFileURL(siteRequire.resolve('puppeteer-core')).href)).default;
12
+
13
+ const BASE = process.argv[2] ?? 'http://localhost:4363';
14
+ const CHROME = process.env.CHROME ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
15
+ const axe = readFileSync(siteRequire.resolve('axe-core/axe.min.js'), 'utf8');
16
+ const walk = (d) => readdirSync(d).flatMap((n) => (statSync(join(d, n)).isDirectory() ? walk(join(d, n)) : [join(d, n)]));
17
+ const routes = walk('dist').filter((f) => f.endsWith('.html') && !/google[0-9a-f]+\.html$/.test(f))
18
+ .map((f) => f.slice(4).replace(/\.html$/, '').replace(/\/index$/, '/'));
19
+
20
+ const browser = await puppeteer.launch({ executablePath: CHROME, headless: true });
21
+ let total = 0;
22
+ for (const r of routes) for (const width of [375, 1280]) {
23
+ const page = await browser.newPage();
24
+ await page.setViewport({ width, height: 900 });
25
+ // Measure final colours, not text halfway through its fade-in.
26
+ await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'reduce' }]);
27
+ await page.goto(BASE + r, { waitUntil: 'load', timeout: 20000 });
28
+ await page.evaluate(axe);
29
+ // @ts-ignore
30
+ const res = await page.evaluate(() => window.axe.run(document, { runOnly: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] }));
31
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1);
32
+ for (const v of res.violations) { total++; console.log(`${r} @${width}: ${v.id} (${v.impact}) ${v.help} :: ${v.nodes.map((n) => n.target.join(' ')).slice(0, 3).join(' | ')}`); }
33
+ if (overflow) { total++; console.log(`${r} @${width}: horizontal scroll`); }
34
+ await page.close();
35
+ }
36
+ await browser.close();
37
+ console.log(total ? `\n${total} issue(s) on ${routes.length} pages` : `a11y: ${routes.length} pages x 2 widths clean`);
38
+ process.exit(total ? 1 : 0);
@@ -0,0 +1,31 @@
1
+ // Every image a blog post uses must be credited, and every credit must point
2
+ // at a real file. Images live in src/assets/blog/<slug>/; credits are the
3
+ // post's `credits` front matter (see src/lib/blog-schema.ts). Exits 1 on any
4
+ // problem so an uncredited Creative Commons photo never ships.
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
6
+
7
+ const posts = 'src/content/blog';
8
+ const assets = 'src/assets/blog';
9
+ const problems = [];
10
+
11
+ for (const f of readdirSync(posts).filter((x) => x.endsWith('.md'))) {
12
+ const slug = f.replace(/\.md$/, '');
13
+ const src = readFileSync(`${posts}/${f}`, 'utf8');
14
+ const fm = src.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '';
15
+ const credited = new Set([...fm.matchAll(/^\s*-?\s*file:\s*["']?([^"'\n]+?)["']?\s*$/gm)].map((m) => m[1]));
16
+ const dir = `${assets}/${slug}`;
17
+ const files = existsSync(dir) ? readdirSync(dir).filter((x) => !x.startsWith('.')) : [];
18
+ for (const file of files) if (!credited.has(file)) problems.push(`${slug}: ${file} has no credit`);
19
+ for (const file of credited) if (!files.includes(file)) problems.push(`${slug}: credit for missing file ${file}`);
20
+ // Images must come from the post's own folder, so the two lists above cover them.
21
+ for (const m of src.matchAll(/(?:!\[[^\]]*\]\(|cover:\s*)["']?([^"')\s]+\.(?:jpe?g|png|webp|avif|svg|gif))/gi)) {
22
+ if (!m[1].includes(`assets/blog/${slug}/`)) problems.push(`${slug}: image ${m[1]} is outside src/assets/blog/${slug}/`);
23
+ }
24
+ }
25
+
26
+ if (problems.length) {
27
+ console.error(problems.join('\n'));
28
+ console.error(`\n${problems.length} credit problem(s)`);
29
+ process.exit(1);
30
+ }
31
+ console.log('credits: every blog image is credited');
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ // Audits a built site (dist/) against the launch ledger rows that code can
3
+ // check. Prints `ROW path: message` and exits 1 on any finding.
4
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
5
+ import { join, relative, extname, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { parse } from 'node-html-parser';
8
+ import { config, requireSite } from './config.mjs';
9
+
10
+ const SITE = requireSite();
11
+
12
+ const BANNED_COPY = [
13
+ [/\u2014/, 'em-dash'],
14
+ [/\s--\s/, 'double hyphen'],
15
+ [/social media chat|whatsapp|instagram|messenger|viber/i, 'social media chat is off the site'],
16
+ [/world[- ]class|supercharg|seamless|effortless|\bunlock\b|\belevate\b|cutting[- ]edge|revolutioni[sz]e|game[- ]chang/i, 'generic marketing claim'],
17
+ [/\bRs\.?\s?\d|NPR\s?\d|रु\s?\d/, 'price on the site'],
18
+ [/lorem ipsum|TODO|TBD/i, 'placeholder text'],
19
+ ];
20
+ // Posts whose topic is the platforms themselves may name them.
21
+ const PLATFORM_NAMES_ALLOWED = new Set(config.check?.platformNamesAllowed ?? []);
22
+ const BANNED_CLASSES = /\b(lead|subtitle|byline|eyebrow|kicker|tagline|overline)\b/;
23
+ const BANNED_CSS = [
24
+ [/box-shadow\s*:\s*(?!none)/, 'box-shadow'],
25
+ [/linear-gradient|radial-gradient|conic-gradient/, 'gradient'],
26
+ [/backdrop-filter/, 'blur/glass'],
27
+ [/letter-spacing\s*:\s*-/, 'negative letter spacing'],
28
+ [/text-transform\s*:\s*uppercase/, 'uppercase text'],
29
+ [/cubic-bezier\([^)]*-|cubic-bezier\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*,\s*1\.\d/, 'bounce easing'],
30
+ ];
31
+ const SECRET = /sk_[A-Za-z0-9]{20,}|ELEVENLABS_API_KEY/;
32
+
33
+ export function canonicalFor(path) {
34
+ let p = (path || '/').split(/[?#]/)[0].toLowerCase();
35
+ p = p.replace(/\.html$/, '').replace(/\/index$/, '/');
36
+ if (p !== '/') p = p.replace(/\/+$/, '');
37
+ if (!p.startsWith('/')) p = `/${p}`;
38
+ return p === '/' ? `${SITE}/` : `${SITE}${p}`;
39
+ }
40
+
41
+ function walk(dir) {
42
+ const out = [];
43
+ for (const name of readdirSync(dir)) {
44
+ const p = join(dir, name);
45
+ if (statSync(p).isDirectory()) out.push(...walk(p));
46
+ else out.push(p);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ function routeOf(dist, file) {
52
+ let r = '/' + relative(dist, file).split('\\').join('/');
53
+ r = r.replace(/\.html$/, '').replace(/\/index$/, '/');
54
+ return r === '/index' ? '/' : r;
55
+ }
56
+
57
+ function resolves(dist, href) {
58
+ const path = decodeURI(href.split(/[?#]/)[0]);
59
+ if (path === '/' || path === '') return existsSync(join(dist, 'index.html'));
60
+ if (path.endsWith('/')) return false; // trailing slash form is never canonical
61
+ return [path, `${path}.html`, `${path}/index.html`].some((p) => existsSync(join(dist, p)) && statSync(join(dist, p)).isFile());
62
+ }
63
+
64
+ const DESIGN_COLOURS = (() => {
65
+ const f = resolve('DESIGN.md');
66
+ if (!existsSync(f)) return null;
67
+ return new Set([...readFileSync(f, 'utf8').matchAll(/#[0-9A-Fa-f]{6}\b/g)].map((m) => m[0].toUpperCase()));
68
+ })();
69
+
70
+ export function audit(dist, { designColours = DESIGN_COLOURS } = {}) {
71
+ const findings = [];
72
+ const add = (row, file, msg) => findings.push({ row, file: relative(dist, file) || file, msg });
73
+ const files = walk(dist);
74
+ const titles = new Map();
75
+ const descs = new Map();
76
+
77
+ for (const file of files) {
78
+ const ext = extname(file);
79
+ const raw = ext === '.html' || ext === '.css' || ext === '.js' || ext === '.json' || ext === '.xml' || ext === '.txt' ? readFileSync(file, 'utf8') : '';
80
+ if (raw && SECRET.test(raw)) add('SEC-3', file, 'secret or key name in the build');
81
+
82
+ if (ext === '.css') {
83
+ for (const [re, what] of BANNED_CSS) if (re.test(raw)) add('SLOP', file, `${what} in CSS`);
84
+ if (designColours) for (const m of raw.matchAll(/#[0-9A-Fa-f]{6}\b/g)) {
85
+ if (!designColours.has(m[0].toUpperCase())) add('DS-1', file, `colour ${m[0]} not in DESIGN.md`);
86
+ }
87
+ }
88
+ if (ext !== '.html') continue;
89
+ if (/(^|\/)google[0-9a-f]+\.html$/.test(file)) continue; // Search Console verification file
90
+
91
+ const route = routeOf(dist, file);
92
+ const root = parse(raw, { comment: false });
93
+ const robots = root.querySelector('meta[name="robots"]')?.getAttribute('content') ?? '';
94
+ const noindex = /noindex/.test(robots);
95
+ const isRedirect = !!root.querySelector('meta[http-equiv="refresh"]');
96
+ if (isRedirect) continue;
97
+
98
+ // Inline styles count as CSS too.
99
+ for (const s of root.querySelectorAll('style')) {
100
+ for (const [re, what] of BANNED_CSS) if (re.test(s.text)) add('SLOP', file, `${what} in CSS`);
101
+ if (designColours) for (const m of s.text.matchAll(/#[0-9A-Fa-f]{6}\b/g)) {
102
+ if (!designColours.has(m[0].toUpperCase())) add('DS-1', file, `colour ${m[0]} not in DESIGN.md`);
103
+ }
104
+ }
105
+
106
+ if (root.querySelector('html')?.getAttribute('lang') !== 'en') add('A11Y-6', file, 'html lang is not "en"');
107
+
108
+ const h1s = root.querySelectorAll('h1');
109
+ if (h1s.length !== 1) add('SEO-6', file, `${h1s.length} h1 elements`);
110
+ let last = 0;
111
+ for (const h of root.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
112
+ const lvl = Number(h.tagName[1]);
113
+ if (last && lvl > last + 1) add('SEO-6', file, `heading jumps from h${last} to h${lvl} ("${h.text.trim().slice(0, 40)}")`);
114
+ last = lvl;
115
+ }
116
+
117
+ const title = root.querySelector('title')?.text.trim() ?? '';
118
+ if (!title) add('SEO-4', file, 'missing <title>');
119
+ else if (!noindex) titles.set(title, [...(titles.get(title) ?? []), file]);
120
+ const desc = root.querySelector('meta[name="description"]')?.getAttribute('content') ?? '';
121
+ if (desc.length < 70 || desc.length > 160) add('SEO-4', file, `meta description is ${desc.length} chars (70 to 160)`);
122
+ else if (!noindex) descs.set(desc, [...(descs.get(desc) ?? []), file]);
123
+
124
+ const canonical = root.querySelector('link[rel="canonical"]')?.getAttribute('href');
125
+ if (route !== '/404' && canonical !== canonicalFor(route)) add('SEO-2', file, `canonical ${canonical} should be ${canonicalFor(route)}`);
126
+ const og = root.querySelector('meta[property="og:image"]')?.getAttribute('content');
127
+ if (!og) add('SEO-5', file, 'no og:image');
128
+ else if (og.startsWith(SITE) && !existsSync(join(dist, og.slice(SITE.length)))) add('SEO-5', file, `og:image ${og} is not in the build`);
129
+
130
+ for (const s of root.querySelectorAll('script[type="application/ld+json"]')) {
131
+ try {
132
+ const data = JSON.parse(s.text);
133
+ if (JSON.stringify(data).includes('"offers"') && !file.endsWith('pricing.html')) add('SD-2', file, 'JSON-LD carries offers outside the pricing page');
134
+ } catch {
135
+ add('SD-7', file, 'JSON-LD does not parse');
136
+ }
137
+ }
138
+
139
+ const brokenSeen = new Set();
140
+ for (const a of root.querySelectorAll('a[href]')) {
141
+ const href = a.getAttribute('href');
142
+ if (/^(mailto:|tel:|#|javascript:)/.test(href)) continue;
143
+ if (/^https?:\/\//.test(href)) {
144
+ if (href.startsWith(SITE)) add('SEO-14', file, `absolute link to own site: ${href}`);
145
+ if (a.getAttribute('target') === '_blank' && !/noopener/.test(a.getAttribute('rel') ?? '')) add('SEC-4', file, `target=_blank without noopener: ${href}`);
146
+ continue;
147
+ }
148
+ if (!href.startsWith('/')) { add('LN-1', file, `relative link ${href}`); continue; }
149
+ if (!resolves(dist, href) && !brokenSeen.has(href)) { brokenSeen.add(href); add('LN-1', file, `broken internal link ${href}`); }
150
+ }
151
+
152
+ for (const img of root.querySelectorAll('img')) {
153
+ const src = img.getAttribute('src') ?? '';
154
+ if (img.getAttribute('alt') === undefined) add('SEO-13', file, `img without alt: ${src}`);
155
+ if (!img.getAttribute('width') || !img.getAttribute('height')) add('CWV-5', file, `img without width/height: ${src}`);
156
+ }
157
+
158
+ for (const el of root.querySelectorAll('[class]')) {
159
+ if (BANNED_CLASSES.test(el.getAttribute('class'))) add('SLOP', file, `byline/eyebrow class "${el.getAttribute('class')}"`);
160
+ }
161
+
162
+ // Copy checks run on visible text only.
163
+ for (const bad of root.querySelectorAll('script, style, noscript, template')) bad.remove();
164
+ const body = root.querySelector('body') ?? root;
165
+ const text = body.text.replace(/\s+/g, ' ');
166
+ // Call transcripts quote callers' own words, including a shop's prices.
167
+ for (const t of body.querySelectorAll('[data-transcript]')) t.remove();
168
+ // Published prices live only inside [data-prices] (the pricing page).
169
+ for (const t of body.querySelectorAll('[data-prices]')) t.remove();
170
+ const ownText = body.text.replace(/\s+/g, ' ');
171
+ // Legal pages describe the whole service, including app channels.
172
+ for (const t of body.querySelectorAll('[data-legal]')) t.remove();
173
+ const marketingText = body.text.replace(/\s+/g, ' ');
174
+ // Blog posts may quote sourced market prices (owner, 2026-10-19).
175
+ const isPost = /^blog\/[^/]+\.html$/.test(relative(dist, file)) && !/^blog\/(index|page|tag)/.test(relative(dist, file));
176
+ for (const [re, what] of BANNED_COPY) {
177
+ if (what === 'price on the site' && isPost) continue;
178
+ // Blog listing pages quote that post's title and summary, so they may name it too.
179
+ if (what.startsWith('social') && (PLATFORM_NAMES_ALLOWED.has(relative(dist, file)) || /^blog(\.html|\/(page|tag)\/)/.test(relative(dist, file)))) continue;
180
+ const hay = what === 'price on the site' ? ownText : what.startsWith('social') ? marketingText : text;
181
+ const m = hay.match(re);
182
+ if (m) add('CV-8', file, `${what}: "…${hay.slice(Math.max(0, m.index - 30), m.index + 30).trim()}…"`);
183
+ }
184
+ }
185
+
186
+ for (const [t, fs] of titles) if (fs.length > 1) add('SEO-4', fs[1], `title "${t}" also used by ${relative(dist, fs[0])}`);
187
+ for (const [d, fs] of descs) if (fs.length > 1) add('SEO-4', fs[1], `description duplicated from ${relative(dist, fs[0])}`);
188
+ return findings;
189
+ }
190
+
191
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) {
192
+ const dist = process.argv[2] ?? 'dist';
193
+ const findings = audit(dist);
194
+ for (const f of findings) console.log(`${f.row} ${f.file}: ${f.msg}`);
195
+ const pages = walk(dist).filter((f) => f.endsWith('.html')).length;
196
+ console.log(findings.length ? `\n${findings.length} finding(s) across ${pages} pages` : `check-site: ${pages} pages clean`);
197
+ process.exit(findings.length ? 1 : 0);
198
+ }
@@ -0,0 +1,106 @@
1
+ // Fetch an image from Wikimedia Commons into a blog post's folder and print its
2
+ // credit, taken from Commons' own metadata so author and licence are exact.
3
+ //
4
+ // site-kit commons search "<words>" Commons files with licences
5
+ // site-kit commons get <slug> "File:Name.jpg" <out-name.jpg> ["changes"]
6
+ // site-kit commons ov-search "<words>" Openverse (Flickr, museums, Commons...),
7
+ // only licences allowing commercial use + changes
8
+ // site-kit commons ov-get <slug> <openverse-id> <out-name.jpg> ["changes"]
9
+ //
10
+ // `get` downloads a 1600px-wide copy to src/assets/blog/<slug>/<out-name> and
11
+ // prints the YAML credit to paste under `credits:`. Licences that forbid
12
+ // commercial use or changes (NC, ND) are refused.
13
+ import { mkdirSync, writeFileSync } from 'node:fs';
14
+
15
+ const API = 'https://commons.wikimedia.org/w/api.php';
16
+ const UA = { 'User-Agent': 'NinjaInfosysBlogBot/1.0 (info@ninjainfosys.com)' };
17
+ const decode = (h = '') => h.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>');
18
+ const strip = (h = '') => decode(h.replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim();
19
+ // A profile link is kept only when it is a real page (Commons red links are not).
20
+ const goodUrl = (u) => (u && !/redlink=1/.test(u) ? decode(u.startsWith('//') ? `https:${u}` : u) : undefined);
21
+ // Download an image and refuse anything that is not one (error pages, redirects to HTML).
22
+ async function download(url, path) {
23
+ const res = await fetch(url, { headers: UA, redirect: 'follow' });
24
+ const type = res.headers.get('content-type') ?? '';
25
+ const buf = Buffer.from(await res.arrayBuffer());
26
+ if (!res.ok || !type.startsWith('image/') || buf.length < 10000) throw new Error(`not an image (${res.status} ${type}, ${buf.length} bytes): ${url}`);
27
+ writeFileSync(path, buf);
28
+ }
29
+ const LICENCE_MAP = [
30
+ [/^cc0/i, 'CC0 1.0'], [/^public domain|^pd/i, 'Public domain'],
31
+ [/^cc by-sa 4\.0$/i, 'CC BY-SA 4.0'], [/^cc by-sa 3\.0$/i, 'CC BY-SA 3.0'], [/^cc by-sa 2\.5$/i, 'CC BY-SA 2.5'], [/^cc by-sa 2\.0$/i, 'CC BY-SA 2.0'],
32
+ [/^cc by 4\.0$/i, 'CC BY 4.0'], [/^cc by 3\.0$/i, 'CC BY 3.0'], [/^cc by 2\.5$/i, 'CC BY 2.5'], [/^cc by 2\.0$/i, 'CC BY 2.0'],
33
+ ];
34
+ const licenceOf = (short) => (/\b(nc|nd)\b/i.test(short) ? null : LICENCE_MAP.find(([re]) => re.test(short.trim().replace(/\s+/g, ' ')))?.[1] ?? null);
35
+
36
+ async function info(titles) {
37
+ const q = new URLSearchParams({ action: 'query', format: 'json', prop: 'imageinfo', iiprop: 'url|extmetadata|size', iiurlwidth: '1600', titles });
38
+ return Object.values((await (await fetch(`${API}?${q}`, { headers: UA })).json()).query?.pages ?? {});
39
+ }
40
+
41
+ const [cmd, ...args] = process.argv.slice(2);
42
+ if (cmd === 'search') {
43
+ const q = new URLSearchParams({ action: 'query', format: 'json', list: 'search', srnamespace: '6', srlimit: '20', srsearch: `${args.join(' ')} filetype:bitmap` });
44
+ const hits = (await (await fetch(`${API}?${q}`, { headers: UA })).json()).query.search.map((h) => h.title);
45
+ for (const p of await info(hits.join('|'))) {
46
+ const ii = p.imageinfo?.[0]; if (!ii) continue;
47
+ const m = ii.extmetadata ?? {};
48
+ const lic = licenceOf(strip(m.LicenseShortName?.value));
49
+ console.log(`${lic ? 'OK ' : 'NO '} ${ii.width}x${ii.height} ${strip(m.LicenseShortName?.value)} ${p.title}`);
50
+ }
51
+ } else if (cmd === 'get') {
52
+ const [slug, title, out, changes] = args;
53
+ const [p] = await info(title);
54
+ const ii = p?.imageinfo?.[0];
55
+ if (!ii) throw new Error(`not found: ${title}`);
56
+ const m = ii.extmetadata ?? {};
57
+ const short = strip(m.LicenseShortName?.value);
58
+ const licence = licenceOf(short);
59
+ if (!licence) throw new Error(`licence not allowed for our sites: ${short}`);
60
+ const author = strip(m.Artist?.value);
61
+ if (!author || /^unknown/i.test(author)) throw new Error(`no author recorded, cannot credit it properly: ${title}`);
62
+ const authorUrl = goodUrl(m.Artist?.value?.match(/href="([^"]+)"/)?.[1]);
63
+ const dir = `src/assets/blog/${slug}`;
64
+ mkdirSync(dir, { recursive: true });
65
+ await download(ii.thumburl ?? ii.url, `${dir}/${out}`);
66
+ const absUrl = (u) => (u.startsWith('//') ? `https:${u}` : u);
67
+ const lines = [
68
+ ` - file: ${out}`,
69
+ ` title: ${JSON.stringify(strip(m.ObjectName?.value) || title.replace(/^File:/, '').replace(/\.\w+$/, ''))}`,
70
+ ` author: ${JSON.stringify(author)}`,
71
+ ...(authorUrl ? [` authorUrl: ${JSON.stringify(authorUrl)}`] : []),
72
+ ` source: ${JSON.stringify(ii.descriptionurl)}`,
73
+ ` licence: ${licence}`,
74
+ ` changes: ${JSON.stringify(changes ?? 'Resized')}`,
75
+ ];
76
+ console.log(lines.join('\n'));
77
+ } else if (cmd === 'ov-search') {
78
+ const q = new URLSearchParams({ q: args.join(' '), license_type: 'commercial,modification', page_size: '20', mature: 'false' });
79
+ const res = await (await fetch(`https://api.openverse.org/v1/images/?${q}`, { headers: UA })).json();
80
+ for (const r of res.results ?? []) {
81
+ console.log(`${r.id} ${r.width ?? '?'}x${r.height ?? '?'} CC ${r.license.toUpperCase()} ${r.license_version ?? ''} ${r.source} ${r.title}`);
82
+ }
83
+ } else if (cmd === 'ov-get') {
84
+ const [slug, id, out, changes] = args;
85
+ const r = await (await fetch(`https://api.openverse.org/v1/images/${id}/`, { headers: UA })).json();
86
+ if (!r.url) throw new Error(`not found: ${id}`);
87
+ const short = r.license === 'cc0' ? 'cc0' : r.license === 'pdm' ? 'public domain' : `cc ${r.license} ${r.license_version}`;
88
+ const licence = licenceOf(short);
89
+ if (!licence) throw new Error(`licence not allowed for our sites: ${short}`);
90
+ if (!r.creator || /^unknown/i.test(r.creator)) throw new Error(`no author recorded, cannot credit it properly: ${id}`);
91
+ const dir = `src/assets/blog/${slug}`;
92
+ mkdirSync(dir, { recursive: true });
93
+ // Openverse's own thumbnail proxy works when the origin blocks hotlinking.
94
+ await download(r.url, `${dir}/${out}`).catch(() => download(`https://api.openverse.org/v1/images/${id}/thumb/?full_size=true`, `${dir}/${out}`));
95
+ console.log([
96
+ ` - file: ${out}`,
97
+ ` title: ${JSON.stringify(r.title || 'Untitled')}`,
98
+ ` author: ${JSON.stringify(r.creator)}`,
99
+ ...(goodUrl(r.creator_url) ? [` authorUrl: ${JSON.stringify(goodUrl(r.creator_url))}`] : []),
100
+ ` source: ${JSON.stringify(r.foreign_landing_url)}`,
101
+ ` licence: ${licence}`,
102
+ ` changes: ${JSON.stringify(changes ?? 'Resized')}`,
103
+ ].join('\n'));
104
+ } else {
105
+ console.log('usage: commons.mjs search "<words>" | get <slug> "File:Name.jpg" <out.jpg> ["changes"]');
106
+ }
@@ -0,0 +1,19 @@
1
+ // Loads site-kit.config.mjs from the directory the command runs in.
2
+ //
3
+ // export default {
4
+ // site: 'https://example.com', // required by check, sitemap, indexnow, redirects
5
+ // check: { platformNamesAllowed: [] }, // dist pages that may name chat platforms
6
+ // sitemap: { notPages: ['og'] }, // top-level paths that are not pages
7
+ // redirects: { ... }, // see redirects.mjs
8
+ // };
9
+ import { existsSync } from 'node:fs';
10
+ import { resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+
13
+ const file = resolve('site-kit.config.mjs');
14
+ export const config = existsSync(file) ? (await import(pathToFileURL(file).href)).default : {};
15
+
16
+ export function requireSite() {
17
+ if (!config.site) throw new Error('site-kit.config.mjs must export a default object with `site`');
18
+ return config.site.replace(/\/+$/, '');
19
+ }
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ // Tells Bing, Yandex, Seznam and Naver (IndexNow) that pages changed, so they
3
+ // recrawl in hours instead of weeks. Run after a deploy:
4
+ // site-kit indexnow every URL in dist/sitemap.xml
5
+ // site-kit indexnow /blog/x just these paths
6
+ // The key file public/<key>.txt must be live on the site first.
7
+ import { readFileSync, readdirSync } from 'node:fs';
8
+ import { requireSite } from './config.mjs';
9
+
10
+ const HOST = new URL(requireSite()).host;
11
+ const key = readdirSync('public').find((f) => /^[a-f0-9]{32}\.txt$/.test(f))?.slice(0, -4);
12
+ if (!key) throw new Error('no IndexNow key file in public/');
13
+
14
+ const args = process.argv.slice(2);
15
+ const urls = args.length
16
+ ? args.map((p) => `https://${HOST}${p.startsWith('/') ? p : `/${p}`}`)
17
+ : [...readFileSync('dist/sitemap.xml', 'utf8').matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1]);
18
+
19
+ const res = await fetch('https://api.indexnow.org/indexnow', {
20
+ method: 'POST',
21
+ headers: { 'content-type': 'application/json; charset=utf-8' },
22
+ body: JSON.stringify({ host: HOST, key, keyLocation: `https://${HOST}/${key}.txt`, urlList: urls }),
23
+ });
24
+ console.log(`indexnow: ${res.status} ${res.statusText} for ${urls.length} url(s)`);
25
+ if (res.status >= 400) process.exit(1);
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ // Redirects for the whole site, written for nginx and Cloudflare Pages from
3
+ // one list. `site-kit redirects` writes docs/nginx-redirects.conf and
4
+ // public/_redirects. The site's list lives in site-kit.config.mjs:
5
+ //
6
+ // redirects: {
7
+ // app: 'https://app.example.com', // where auth and share links go
8
+ // exact: Map<oldPath, newPath | url>, // exact old URLs, every one a single 301
9
+ // nginx: { share: [...], tail: [...] }, // extra nginx lines before the trailing-slash rule
10
+ // cloudflare: { share: [...], tail: [...] }, // extra _redirects lines after the exact list
11
+ // }
12
+ import { mkdirSync, writeFileSync } from 'node:fs';
13
+ import { dirname, resolve } from 'node:path';
14
+ import { pathToFileURL } from 'node:url';
15
+ import { config, requireSite } from './config.mjs';
16
+
17
+ const SITE = requireSite();
18
+ const r = config.redirects ?? { exact: new Map() };
19
+
20
+ /** Old path (exact, as it was served) -> new target. */
21
+ export const exact = r.exact ?? new Map();
22
+
23
+ export function nginxConf() {
24
+ const lines = [
25
+ '# Generated by site-kit redirects. Do not edit by hand.',
26
+ '# Exact old URLs first, then share links, then one rule that drops any',
27
+ '# trailing slash. Every redirect is a single 301 hop.',
28
+ '',
29
+ ];
30
+ for (const [from, to] of exact) lines.push(`location = ${from} { return 301 ${to.startsWith('http') ? to : SITE + to}; }`);
31
+ lines.push(...(r.nginx?.share ?? []));
32
+ lines.push('', '# Any other trailing slash: drop it (root excepted).');
33
+ lines.push(`location ~ ^(/.+)/$ { return 301 ${SITE}$1$is_args$args; }`);
34
+ lines.push('', '# Real 404 status for missing pages.', 'error_page 404 /404.html;');
35
+ return `${lines.join('\n')}\n`;
36
+ }
37
+
38
+ /**
39
+ * Cloudflare `_redirects`: exact old URLs first, then the site's own extra
40
+ * lines (share links, prefixes that were indexed).
41
+ */
42
+ export function cloudflareRedirects() {
43
+ const lines = ['# Generated by site-kit redirects. Do not edit by hand.'];
44
+ for (const [from, to] of exact) lines.push(`${from} ${to} 301`);
45
+ lines.push(...(r.cloudflare?.tail ?? []));
46
+ return `${lines.join('\n')}\n`;
47
+ }
48
+
49
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
50
+ for (const [file, text] of [['docs/nginx-redirects.conf', nginxConf()], ['public/_redirects', cloudflareRedirects()]]) {
51
+ mkdirSync(dirname(resolve(file)), { recursive: true });
52
+ writeFileSync(file, text);
53
+ }
54
+ console.log(`wrote ${exact.size} exact redirects`);
55
+ }