@zero2webmaster/starter-kit 0.2.0 → 0.2.1

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,782 @@
1
+ // z2w-starter-kit Pro SEO baseline extension.
2
+ //
3
+ // Layered on top of the base nextjs/cf-pages scaffolders' free SEO baseline
4
+ // when the customer has an active paid license and passes --with-pro-seo.
5
+ // Emits five deliverables per directives/license-check.md + HANDOFF.md:
6
+ //
7
+ // 1. src/seo/json-ld.ts — Article/Event/Product/BreadcrumbList helpers
8
+ // 2. scripts/seo-audit.mjs — 11-point pre-launch audit
9
+ // 3. scripts/og-image-gen.mjs — OG image auto-generator skeleton
10
+ // 4. scripts/link-rot.mjs — public-URL link-rot checker
11
+ // 5. .github/workflows/perf-budgets.yml — Lighthouse CI perf budgets
12
+ //
13
+ // Plus PRO_SEO_README.md explaining how to wire them in. The files are
14
+ // additive — they do NOT overwrite the base scaffolder output. The base
15
+ // scaffold's `app/opengraph-image.tsx` placeholder stays put; the Pro
16
+ // generator at `scripts/og-image-gen.mjs` is run from `npm run og:gen`
17
+ // to refresh it ahead of launch.
18
+ export const PRO_SEO_BASELINE_PATHS = Object.freeze([
19
+ "src/seo/json-ld.ts",
20
+ "scripts/seo-audit.mjs",
21
+ "scripts/og-image-gen.mjs",
22
+ "scripts/link-rot.mjs",
23
+ ".github/workflows/perf-budgets.yml",
24
+ "PRO_SEO_README.md",
25
+ ]);
26
+ /**
27
+ * Returns whether the Pro SEO extension applies to a given project type.
28
+ * Only nextjs + cf-pages have a free SEO baseline to extend; other types
29
+ * either have no public web surface (library, protocol-repo, cf-worker,
30
+ * python-service) or use a non-Next.js SEO stack (wp-plugin → RankMath).
31
+ */
32
+ export function proSeoApplies(inputs) {
33
+ if (!inputs.hasWebUi)
34
+ return false;
35
+ return inputs.projectType === "nextjs" || inputs.projectType === "cf-pages";
36
+ }
37
+ export function buildProSeoExtension(inputs) {
38
+ if (!proSeoApplies(inputs))
39
+ return [];
40
+ return [
41
+ { path: "src/seo/json-ld.ts", content: jsonLdHelpers() },
42
+ { path: "scripts/seo-audit.mjs", content: seoAuditScript() },
43
+ { path: "scripts/og-image-gen.mjs", content: ogImageGenScript() },
44
+ { path: "scripts/link-rot.mjs", content: linkRotScript(inputs) },
45
+ { path: ".github/workflows/perf-budgets.yml", content: perfBudgetsWorkflow() },
46
+ { path: "PRO_SEO_README.md", content: proSeoReadme(inputs) },
47
+ ];
48
+ }
49
+ function jsonLdHelpers() {
50
+ return `// Pro SEO baseline — content-type JSON-LD helpers.
51
+ //
52
+ // Pure builders that return JSON-LD-shaped objects ready to be serialized into
53
+ // a <script type="application/ld+json"> tag. Type-safe per schema.org.
54
+ //
55
+ // Usage (Next.js App Router):
56
+ //
57
+ // import { articleJsonLd } from "@/seo/json-ld";
58
+ // export default function Page() {
59
+ // const ld = articleJsonLd({
60
+ // headline: "Post title",
61
+ // datePublished: "2026-06-01",
62
+ // author: { name: "Dr. Kerry Kriger", url: "https://zero2webmaster.com/kerry-kriger" },
63
+ // image: "https://example.com/og.png",
64
+ // url: "https://example.com/posts/post-title",
65
+ // });
66
+ // return <>{/* page body */}<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(ld) }} /></>;
67
+ // }
68
+
69
+ export interface ArticleJsonLdInput {
70
+ headline: string;
71
+ description?: string;
72
+ datePublished: string;
73
+ dateModified?: string;
74
+ author: { name: string; url?: string };
75
+ image: string | string[];
76
+ url: string;
77
+ publisher?: { name: string; logoUrl?: string };
78
+ }
79
+
80
+ export function articleJsonLd(input: ArticleJsonLdInput): Record<string, unknown> {
81
+ const out: Record<string, unknown> = {
82
+ "@context": "https://schema.org",
83
+ "@type": "Article",
84
+ headline: input.headline,
85
+ datePublished: input.datePublished,
86
+ author: { "@type": "Person", name: input.author.name },
87
+ image: input.image,
88
+ mainEntityOfPage: { "@type": "WebPage", "@id": input.url },
89
+ };
90
+ if (input.description) out.description = input.description;
91
+ if (input.dateModified) out.dateModified = input.dateModified;
92
+ if (input.author.url) (out.author as Record<string, unknown>).url = input.author.url;
93
+ if (input.publisher) {
94
+ out.publisher = {
95
+ "@type": "Organization",
96
+ name: input.publisher.name,
97
+ ...(input.publisher.logoUrl
98
+ ? { logo: { "@type": "ImageObject", url: input.publisher.logoUrl } }
99
+ : {}),
100
+ };
101
+ }
102
+ return out;
103
+ }
104
+
105
+ export interface EventJsonLdInput {
106
+ name: string;
107
+ description?: string;
108
+ startDate: string;
109
+ endDate?: string;
110
+ location: { name: string; address?: string } | { name: "Online"; url: string };
111
+ image?: string | string[];
112
+ organizer?: { name: string; url?: string };
113
+ url: string;
114
+ }
115
+
116
+ export function eventJsonLd(input: EventJsonLdInput): Record<string, unknown> {
117
+ const isOnline = "url" in input.location && input.location.name === "Online";
118
+ const location = isOnline
119
+ ? {
120
+ "@type": "VirtualLocation",
121
+ url: (input.location as { url: string }).url,
122
+ }
123
+ : {
124
+ "@type": "Place",
125
+ name: input.location.name,
126
+ ...((input.location as { address?: string }).address
127
+ ? { address: (input.location as { address: string }).address }
128
+ : {}),
129
+ };
130
+ const out: Record<string, unknown> = {
131
+ "@context": "https://schema.org",
132
+ "@type": "Event",
133
+ name: input.name,
134
+ startDate: input.startDate,
135
+ location,
136
+ url: input.url,
137
+ eventAttendanceMode: isOnline
138
+ ? "https://schema.org/OnlineEventAttendanceMode"
139
+ : "https://schema.org/OfflineEventAttendanceMode",
140
+ eventStatus: "https://schema.org/EventScheduled",
141
+ };
142
+ if (input.description) out.description = input.description;
143
+ if (input.endDate) out.endDate = input.endDate;
144
+ if (input.image) out.image = input.image;
145
+ if (input.organizer) {
146
+ out.organizer = {
147
+ "@type": "Organization",
148
+ name: input.organizer.name,
149
+ ...(input.organizer.url ? { url: input.organizer.url } : {}),
150
+ };
151
+ }
152
+ return out;
153
+ }
154
+
155
+ export interface ProductJsonLdInput {
156
+ name: string;
157
+ description?: string;
158
+ image: string | string[];
159
+ sku?: string;
160
+ brand?: string;
161
+ offers: {
162
+ price: string | number;
163
+ priceCurrency: string;
164
+ availability?: "InStock" | "OutOfStock" | "PreOrder";
165
+ url: string;
166
+ };
167
+ }
168
+
169
+ export function productJsonLd(input: ProductJsonLdInput): Record<string, unknown> {
170
+ const out: Record<string, unknown> = {
171
+ "@context": "https://schema.org",
172
+ "@type": "Product",
173
+ name: input.name,
174
+ image: input.image,
175
+ offers: {
176
+ "@type": "Offer",
177
+ price: input.offers.price,
178
+ priceCurrency: input.offers.priceCurrency,
179
+ availability:
180
+ "https://schema.org/" + (input.offers.availability ?? "InStock"),
181
+ url: input.offers.url,
182
+ },
183
+ };
184
+ if (input.description) out.description = input.description;
185
+ if (input.sku) out.sku = input.sku;
186
+ if (input.brand) {
187
+ out.brand = { "@type": "Brand", name: input.brand };
188
+ }
189
+ return out;
190
+ }
191
+
192
+ export interface BreadcrumbItem {
193
+ name: string;
194
+ url: string;
195
+ }
196
+
197
+ export function breadcrumbListJsonLd(items: BreadcrumbItem[]): Record<string, unknown> {
198
+ return {
199
+ "@context": "https://schema.org",
200
+ "@type": "BreadcrumbList",
201
+ itemListElement: items.map((item, index) => ({
202
+ "@type": "ListItem",
203
+ position: index + 1,
204
+ name: item.name,
205
+ item: item.url,
206
+ })),
207
+ };
208
+ }
209
+ `;
210
+ }
211
+ function seoAuditScript() {
212
+ return `#!/usr/bin/env node
213
+ // Pro SEO baseline — 11-point pre-launch audit.
214
+ //
215
+ // Reads the built output (Next.js .next/ or cf-pages dist/) and the source
216
+ // tree to verify the 11 SEO baseline requirements per the 2026-05-30 Z2W
217
+ // standing requirement. Exits non-zero if any required item is missing.
218
+ //
219
+ // Usage: \`node scripts/seo-audit.mjs\` (or \`npm run seo:audit\` once wired).
220
+
221
+ import { promises as fs } from "node:fs";
222
+ import * as path from "node:path";
223
+
224
+ const CHECKS = [
225
+ {
226
+ id: "1-ssr",
227
+ label: "Server-rendered HTML (SSR/SSG)",
228
+ description:
229
+ "Primary content must be present in the initial HTML, not client-only rendered.",
230
+ },
231
+ {
232
+ id: "2-metadata",
233
+ label: "Per-page metadata (title/description/canonical/OG/Twitter)",
234
+ description:
235
+ "Every page has a unique <title>, <meta name=\\"description\\">, canonical URL, and OpenGraph + Twitter Card tags.",
236
+ },
237
+ {
238
+ id: "3-h1",
239
+ label: "Exactly one <h1> per page + semantic HTML",
240
+ description:
241
+ "Every page emits one <h1> and uses semantic <main>/<header>/<footer>/<article>.",
242
+ },
243
+ {
244
+ id: "4-alt",
245
+ label: "Descriptive alt text on every meaningful <img>",
246
+ description:
247
+ "Decorative images use alt=\\"\\"; informational images carry alt that describes the content.",
248
+ },
249
+ {
250
+ id: "5-jsonld",
251
+ label: "JSON-LD structured data where content type warrants",
252
+ description:
253
+ "Article/Event/Product/BreadcrumbList — built via src/seo/json-ld.ts helpers.",
254
+ },
255
+ {
256
+ id: "6-sitemap-robots",
257
+ label: "sitemap.xml + robots.txt + preview-noindex",
258
+ description:
259
+ "Production is indexable; preview/staging is NOT indexable (Vercel preview / *.pages.dev).",
260
+ },
261
+ {
262
+ id: "7-fathom",
263
+ label: "Fathom Analytics snippet present + firing",
264
+ description:
265
+ "Per [[fathom-analytics]] — NOT Google Analytics, NOT Plausible.",
266
+ },
267
+ {
268
+ id: "8-canonical",
269
+ label: "Internal links + canonicals match the production hostname",
270
+ description:
271
+ "No raw *.vercel.app URLs leaked as canonicals.",
272
+ },
273
+ {
274
+ id: "9-og-image",
275
+ label: "OG image is a real image (not a placeholder)",
276
+ description:
277
+ "Either bespoke or generated by scripts/og-image-gen.mjs.",
278
+ },
279
+ {
280
+ id: "10-link-rot",
281
+ label: "No internal link-rot",
282
+ description:
283
+ "scripts/link-rot.mjs reports zero internal 404s.",
284
+ },
285
+ {
286
+ id: "11-perf-budgets",
287
+ label: "Perf budgets enforced in CI",
288
+ description:
289
+ "Lighthouse-style budgets on LCP / CLS / TBT / TTI / bundle size run on every PR.",
290
+ },
291
+ ];
292
+
293
+ async function exists(p) {
294
+ try {
295
+ await fs.access(p);
296
+ return true;
297
+ } catch {
298
+ return false;
299
+ }
300
+ }
301
+
302
+ async function isNextJs(cwd) {
303
+ return exists(path.join(cwd, "next.config.js"))
304
+ .then((a) => a || exists(path.join(cwd, "next.config.mjs")))
305
+ .then((a) => a || exists(path.join(cwd, "next.config.ts")));
306
+ }
307
+
308
+ async function readIfExists(p) {
309
+ try {
310
+ return await fs.readFile(p, "utf8");
311
+ } catch {
312
+ return null;
313
+ }
314
+ }
315
+
316
+ async function audit(cwd) {
317
+ const results = [];
318
+ const nextJs = await isNextJs(cwd);
319
+
320
+ // Helper: record a pass/warn/fail.
321
+ const record = (id, status, detail) =>
322
+ results.push({ id, status, detail: detail ?? "" });
323
+
324
+ // Check 1: SSR — heuristic on Next.js \`app/\` exists or cf-pages \`dist/\` has HTML.
325
+ const hasAppDir = await exists(path.join(cwd, "app"));
326
+ const hasDist = await exists(path.join(cwd, "dist"));
327
+ record(
328
+ "1-ssr",
329
+ hasAppDir || hasDist ? "pass" : "warn",
330
+ nextJs
331
+ ? "Next.js app/ directory present"
332
+ : hasDist
333
+ ? "dist/ output present"
334
+ : "No app/ or dist/ found — confirm SSR/SSG is configured.",
335
+ );
336
+
337
+ // Check 2: metadata — look for either Next.js metadata exports OR <meta> in index.html.
338
+ let metadataOk = false;
339
+ if (nextJs) {
340
+ const layout =
341
+ (await readIfExists(path.join(cwd, "app/layout.tsx"))) ??
342
+ (await readIfExists(path.join(cwd, "app/layout.ts"))) ??
343
+ "";
344
+ metadataOk = /export const metadata\\s*=|generateMetadata/.test(layout);
345
+ } else {
346
+ const indexHtml = await readIfExists(path.join(cwd, "public/index.html"))
347
+ ?? await readIfExists(path.join(cwd, "index.html")) ?? "";
348
+ metadataOk =
349
+ /<meta name=["']description["']/.test(indexHtml) &&
350
+ /<link rel=["']canonical["']/.test(indexHtml);
351
+ }
352
+ record(
353
+ "2-metadata",
354
+ metadataOk ? "pass" : "fail",
355
+ metadataOk ? "" : "Add per-page metadata exports / <meta> tags.",
356
+ );
357
+
358
+ // Check 3 + 4 are content-quality — surface as advisory.
359
+ record("3-h1", "advisory", "Manually verify every route emits exactly one <h1>.");
360
+ record("4-alt", "advisory", "Manually verify image alt text in your content.");
361
+
362
+ // Check 5: JSON-LD helpers present.
363
+ const jsonLdPresent = await exists(path.join(cwd, "src/seo/json-ld.ts"));
364
+ record(
365
+ "5-jsonld",
366
+ jsonLdPresent ? "pass" : "warn",
367
+ jsonLdPresent
368
+ ? "src/seo/json-ld.ts present"
369
+ : "Pro SEO helpers missing — re-run scaffolder with --with-pro-seo.",
370
+ );
371
+
372
+ // Check 6: sitemap + robots.
373
+ const sitemapOk =
374
+ (await exists(path.join(cwd, "app/sitemap.ts"))) ||
375
+ (await exists(path.join(cwd, "public/sitemap.xml"))) ||
376
+ (await exists(path.join(cwd, "sitemap.xml")));
377
+ const robotsOk =
378
+ (await exists(path.join(cwd, "app/robots.ts"))) ||
379
+ (await exists(path.join(cwd, "public/robots.txt"))) ||
380
+ (await exists(path.join(cwd, "robots.txt")));
381
+ record(
382
+ "6-sitemap-robots",
383
+ sitemapOk && robotsOk ? "pass" : "fail",
384
+ \`sitemap=\${sitemapOk ? "ok" : "MISSING"} robots=\${robotsOk ? "ok" : "MISSING"}\`,
385
+ );
386
+
387
+ // Check 7: Fathom presence — grep source for site-id env-var reference.
388
+ const grepDirs = ["app", "src", "components"];
389
+ let fathomFound = false;
390
+ for (const dir of grepDirs) {
391
+ if (!(await exists(path.join(cwd, dir)))) continue;
392
+ const entries = await fs.readdir(path.join(cwd, dir), { recursive: true });
393
+ for (const entry of entries) {
394
+ if (typeof entry !== "string") continue;
395
+ if (!/\\.(tsx?|jsx?|html)$/.test(entry)) continue;
396
+ const c = await readIfExists(path.join(cwd, dir, entry));
397
+ if (c && /FATHOM_SITE_ID|cdn\\.usefathom\\.com|usefathom\\.com\\/script\\.js/.test(c)) {
398
+ fathomFound = true;
399
+ break;
400
+ }
401
+ }
402
+ if (fathomFound) break;
403
+ }
404
+ record(
405
+ "7-fathom",
406
+ fathomFound ? "pass" : "warn",
407
+ fathomFound
408
+ ? "Fathom reference found"
409
+ : "Fathom snippet not detected — wire NEXT_PUBLIC_FATHOM_SITE_ID per [[fathom-analytics]].",
410
+ );
411
+
412
+ // Checks 8 / 9 / 10 / 11 — advisories pointing at the helper scripts.
413
+ record("8-canonical", "advisory", "Manually verify canonicals match production hostname.");
414
+ record(
415
+ "9-og-image",
416
+ "advisory",
417
+ "Run scripts/og-image-gen.mjs (or replace app/opengraph-image.tsx) before launch.",
418
+ );
419
+ record(
420
+ "10-link-rot",
421
+ "advisory",
422
+ "Run \\\`node scripts/link-rot.mjs\\\` against staging before launch.",
423
+ );
424
+ record(
425
+ "11-perf-budgets",
426
+ (await exists(path.join(cwd, ".github/workflows/perf-budgets.yml")))
427
+ ? "pass"
428
+ : "warn",
429
+ "Perf-budgets workflow at .github/workflows/perf-budgets.yml.",
430
+ );
431
+
432
+ return results;
433
+ }
434
+
435
+ const cwd = process.cwd();
436
+ const results = await audit(cwd);
437
+
438
+ let failCount = 0;
439
+ let warnCount = 0;
440
+ for (const r of results) {
441
+ const check = CHECKS.find((c) => c.id === r.id);
442
+ const label = check?.label ?? r.id;
443
+ const glyph =
444
+ r.status === "pass"
445
+ ? "[✓]"
446
+ : r.status === "advisory"
447
+ ? "[i]"
448
+ : r.status === "warn"
449
+ ? "[!]"
450
+ : "[X]";
451
+ // eslint-disable-next-line no-console
452
+ console.log(\`\${glyph} \${r.id} \${label}\${r.detail ? " — " + r.detail : ""}\`);
453
+ if (r.status === "fail") failCount++;
454
+ if (r.status === "warn") warnCount++;
455
+ }
456
+
457
+ // eslint-disable-next-line no-console
458
+ console.log(
459
+ \`\\nSEO audit: \${failCount} fail / \${warnCount} warn / advisories above. \` +
460
+ \`Address fails before launch.\`,
461
+ );
462
+ process.exit(failCount > 0 ? 1 : 0);
463
+ `;
464
+ }
465
+ function ogImageGenScript() {
466
+ return `#!/usr/bin/env node
467
+ // Pro SEO baseline — OG image auto-generator skeleton.
468
+ //
469
+ // The base scaffolder ships an empty \`app/opengraph-image.tsx\` placeholder.
470
+ // This script regenerates it from the project's brand + slug + tagline to
471
+ // produce a launch-ready 1200x630 PNG before launch.
472
+ //
473
+ // v0.3.0 ships the skeleton; you wire your preferred image library
474
+ // (@vercel/og, satori, sharp + canvas, etc.) into the body. The skeleton
475
+ // emits a Next.js \`ImageResponse\` template that uses brand colors from
476
+ // the scaffold's BRAND_PRESET. For cf-pages projects, adapt the template
477
+ // to your image pipeline of choice.
478
+ //
479
+ // Usage: \`node scripts/og-image-gen.mjs\` (or \`npm run og:gen\`).
480
+
481
+ import { promises as fs } from "node:fs";
482
+ import * as path from "node:path";
483
+
484
+ const BRAND_PRIMARY = process.env.BRAND_PRIMARY ?? "#82C92B";
485
+ const BRAND_ACCENT = process.env.BRAND_ACCENT ?? "#FFD700";
486
+ const SITE_NAME = process.env.SITE_NAME ?? "Your Site";
487
+ const TAGLINE = process.env.TAGLINE ?? "Tagline goes here";
488
+
489
+ const TEMPLATE = \`// Auto-generated by scripts/og-image-gen.mjs. Edit there, not here.
490
+ //
491
+ // Renders a 1200x630 OG image via Next.js Image Response. Brand colors are
492
+ // pinned at generation time; re-run \\\`npm run og:gen\\\` to refresh after a
493
+ // brand change.
494
+
495
+ import { ImageResponse } from "next/og";
496
+
497
+ export const runtime = "edge";
498
+ export const alt = "\${SITE_NAME}";
499
+ export const size = { width: 1200, height: 630 };
500
+ export const contentType = "image/png";
501
+
502
+ export default function OgImage() {
503
+ return new ImageResponse(
504
+ (
505
+ <div
506
+ style={{
507
+ width: "100%",
508
+ height: "100%",
509
+ background: "\${BRAND_PRIMARY}",
510
+ color: "white",
511
+ display: "flex",
512
+ flexDirection: "column",
513
+ justifyContent: "center",
514
+ alignItems: "center",
515
+ padding: 80,
516
+ fontFamily: "system-ui, sans-serif",
517
+ }}
518
+ >
519
+ <div style={{ fontSize: 96, fontWeight: 700, textAlign: "center" }}>
520
+ \${SITE_NAME}
521
+ </div>
522
+ <div
523
+ style={{
524
+ fontSize: 36,
525
+ marginTop: 40,
526
+ color: "\${BRAND_ACCENT}",
527
+ textAlign: "center",
528
+ }}
529
+ >
530
+ \${TAGLINE}
531
+ </div>
532
+ </div>
533
+ ),
534
+ size,
535
+ );
536
+ }
537
+ \`;
538
+
539
+ const target = path.join(process.cwd(), "app/opengraph-image.tsx");
540
+ await fs.mkdir(path.dirname(target), { recursive: true });
541
+ await fs.writeFile(target, TEMPLATE, "utf8");
542
+ // eslint-disable-next-line no-console
543
+ console.log(
544
+ \`Wrote \${target} (brand=\${BRAND_PRIMARY} accent=\${BRAND_ACCENT} name="\${SITE_NAME}")\`,
545
+ );
546
+ `;
547
+ }
548
+ function linkRotScript(inputs) {
549
+ const defaultRoot = inputs.slug
550
+ ? `https://${inputs.slug}.example.com`
551
+ : "https://example.com";
552
+ return `#!/usr/bin/env node
553
+ // Pro SEO baseline — link-rot checker.
554
+ //
555
+ // Crawls a site starting at a root URL, follows internal links, and reports
556
+ // any 4xx/5xx responses. Internal-only by default (off-host links are not
557
+ // checked); pass --external to also check off-host links.
558
+ //
559
+ // Usage:
560
+ // node scripts/link-rot.mjs ${defaultRoot}
561
+ // node scripts/link-rot.mjs https://your-site.example.com --external
562
+ //
563
+ // Exits non-zero if any internal link returns a non-2xx/3xx status.
564
+
565
+ const args = process.argv.slice(2);
566
+ const rootArg = args.find((a) => !a.startsWith("--"));
567
+ const includeExternal = args.includes("--external");
568
+
569
+ if (!rootArg) {
570
+ // eslint-disable-next-line no-console
571
+ console.error(
572
+ "usage: node scripts/link-rot.mjs <root-url> [--external]\\n" +
573
+ " (default root used in scaffold: ${defaultRoot})",
574
+ );
575
+ process.exit(2);
576
+ }
577
+
578
+ const root = new URL(rootArg);
579
+ const queue = [root.toString()];
580
+ const visited = new Set();
581
+ const broken = [];
582
+
583
+ const HREF_RE = /<a[^>]+href=["']([^"'#]+)["']/gi;
584
+
585
+ async function checkOne(url) {
586
+ if (visited.has(url)) return;
587
+ visited.add(url);
588
+ let response;
589
+ try {
590
+ response = await fetch(url, { redirect: "follow" });
591
+ } catch (err) {
592
+ broken.push({ url, status: 0, message: err.message });
593
+ return;
594
+ }
595
+ const isInternal = new URL(url).host === root.host;
596
+ if (!response.ok) {
597
+ broken.push({ url, status: response.status, message: response.statusText });
598
+ return;
599
+ }
600
+ if (!isInternal) return; // don't crawl off-host pages even when --external
601
+ const contentType = response.headers.get("content-type") ?? "";
602
+ if (!contentType.includes("text/html")) return;
603
+ const body = await response.text();
604
+ HREF_RE.lastIndex = 0;
605
+ let match;
606
+ while ((match = HREF_RE.exec(body)) !== null) {
607
+ let candidate;
608
+ try {
609
+ candidate = new URL(match[1], url).toString();
610
+ } catch {
611
+ continue;
612
+ }
613
+ const candidateHost = new URL(candidate).host;
614
+ if (!includeExternal && candidateHost !== root.host) continue;
615
+ if (!visited.has(candidate)) queue.push(candidate);
616
+ }
617
+ }
618
+
619
+ while (queue.length > 0) {
620
+ const next = queue.shift();
621
+ if (!next) break;
622
+ await checkOne(next);
623
+ }
624
+
625
+ // eslint-disable-next-line no-console
626
+ console.log(
627
+ \`Checked \${visited.size} URL(s); \${broken.length} broken.\`,
628
+ );
629
+ for (const b of broken) {
630
+ // eslint-disable-next-line no-console
631
+ console.log(\` [\${b.status || "ERR"}] \${b.url} \${b.message}\`);
632
+ }
633
+ process.exit(broken.length > 0 ? 1 : 0);
634
+ `;
635
+ }
636
+ function perfBudgetsWorkflow() {
637
+ return `# Pro SEO baseline — perf budgets in CI.
638
+ #
639
+ # Runs Lighthouse against PR previews and fails the build if Core Web Vitals
640
+ # (or bundle size) regress past the configured budget. Adjust the budget
641
+ # thresholds in .lighthouserc.json (create it alongside this file).
642
+ #
643
+ # Requires: a deploy preview URL passed in via the \`preview-url\` input. Wire
644
+ # this from your Vercel / Cloudflare Pages preview deployment.
645
+
646
+ name: perf-budgets
647
+
648
+ on:
649
+ pull_request:
650
+ branches: [main]
651
+ workflow_dispatch:
652
+ inputs:
653
+ preview-url:
654
+ description: "Preview URL to audit"
655
+ required: true
656
+
657
+ jobs:
658
+ lighthouse:
659
+ runs-on: ubuntu-latest
660
+ steps:
661
+ - uses: actions/checkout@v4
662
+ - uses: actions/setup-node@v4
663
+ with:
664
+ node-version: "20"
665
+ - name: Install Lighthouse CI
666
+ run: npm i -g @lhci/cli@0.13.x
667
+ - name: Run Lighthouse CI
668
+ env:
669
+ # Replace with your actual preview URL pattern.
670
+ PREVIEW_URL: \${{ github.event.inputs.preview-url || format('https://preview-{0}.example.com', github.event.pull_request.number) }}
671
+ run: |
672
+ lhci collect --url="$PREVIEW_URL"
673
+ lhci assert --preset=lighthouse:recommended
674
+
675
+ # Optional: persist results so regressions surface across PRs.
676
+ # - name: Upload results
677
+ # uses: actions/upload-artifact@v4
678
+ # with:
679
+ # name: lighthouse-results
680
+ # path: .lighthouseci
681
+ `;
682
+ }
683
+ function proSeoReadme(inputs) {
684
+ const kind = inputs.projectType === "nextjs" ? "Next.js" : "Cloudflare Pages";
685
+ return `# Pro SEO Baseline — ${inputs.slug}
686
+
687
+ This project was scaffolded with \`--with-pro-seo\`, so it ships with the **Pro SEO baseline extension** layered on top of the standard 7-item SEO baseline. Five deliverables landed:
688
+
689
+ | File | Purpose |
690
+ |---|---|
691
+ | \`src/seo/json-ld.ts\` | Content-type JSON-LD helpers (\`articleJsonLd\`, \`eventJsonLd\`, \`productJsonLd\`, \`breadcrumbListJsonLd\`) |
692
+ | \`scripts/seo-audit.mjs\` | 11-point pre-launch audit; exits non-zero on any failure |
693
+ | \`scripts/og-image-gen.mjs\` | OG image regenerator skeleton (1200x630 PNG; wire your image library of choice) |
694
+ | \`scripts/link-rot.mjs\` | Internal link-rot crawler; exits non-zero on any broken link |
695
+ | \`.github/workflows/perf-budgets.yml\` | Lighthouse CI perf budgets on every PR |
696
+
697
+ ## Wire it in
698
+
699
+ Add the following to your \`package.json\` scripts:
700
+
701
+ \`\`\`json
702
+ {
703
+ "scripts": {
704
+ "seo:audit": "node scripts/seo-audit.mjs",
705
+ "seo:link-rot": "node scripts/link-rot.mjs",
706
+ "og:gen": "node scripts/og-image-gen.mjs"
707
+ }
708
+ }
709
+ \`\`\`
710
+
711
+ ## Use the JSON-LD helpers
712
+
713
+ ${inputs.projectType === "nextjs"
714
+ ? `\`\`\`tsx
715
+ // app/posts/[slug]/page.tsx
716
+ import { articleJsonLd } from "@/seo/json-ld";
717
+
718
+ export default async function PostPage({ params }: { params: { slug: string } }) {
719
+ const post = await loadPost(params.slug);
720
+ const ld = articleJsonLd({
721
+ headline: post.title,
722
+ datePublished: post.publishedAt,
723
+ author: { name: "Dr. Kerry Kriger", url: "https://zero2webmaster.com/kerry-kriger" },
724
+ image: post.ogImage,
725
+ url: \\\`https://\${inputs.slug}.example.com/posts/\${params.slug}\\\`,
726
+ });
727
+ return (
728
+ <article>
729
+ {/* ... post body ... */}
730
+ <script
731
+ type="application/ld+json"
732
+ dangerouslySetInnerHTML={{ __html: JSON.stringify(ld) }}
733
+ />
734
+ </article>
735
+ );
736
+ }
737
+ \`\`\``
738
+ : `\`\`\`html
739
+ <!-- public/posts/post-title.html -->
740
+ <article>
741
+ <!-- ... post body ... -->
742
+ </article>
743
+ <script type="application/ld+json">
744
+ // Generate at build time from src/seo/json-ld.ts (import + serialize).
745
+ </script>
746
+ \`\`\`
747
+
748
+ For ${kind} you'll typically run the helper at build time and inline the result into your HTML output.`}
749
+
750
+ ## Run the pre-launch audit
751
+
752
+ \`\`\`bash
753
+ npm run seo:audit
754
+ \`\`\`
755
+
756
+ 11 checks; the script exits non-zero on any fail. Some are advisory (manual verification of <h1> / alt text / canonicals); some are automatic (sitemap presence, Fathom reference, perf-budget workflow presence).
757
+
758
+ ## Regenerate the OG image
759
+
760
+ \`\`\`bash
761
+ SITE_NAME="${inputs.slug}" TAGLINE="..." npm run og:gen
762
+ \`\`\`
763
+
764
+ Rewrites \`app/opengraph-image.tsx\`${inputs.projectType === "cf-pages" ? " (or your cf-pages OG handler)" : ""} with a Next.js Image Response template. The default uses your brand primary + accent colors; wire your image library of choice into the template body for production output.
765
+
766
+ ## Catch link rot before launch
767
+
768
+ \`\`\`bash
769
+ node scripts/link-rot.mjs https://your-staging-host.example.com
770
+ \`\`\`
771
+
772
+ Crawls internal links starting at the root URL. Pass \`--external\` to also check off-host references. CI hint: run this against your preview deployment URL.
773
+
774
+ ## CI perf budgets
775
+
776
+ \`.github/workflows/perf-budgets.yml\` runs Lighthouse against PR preview deployments. Adjust the budget thresholds in \`.lighthouserc.json\` (create it alongside the workflow file when you're ready to enforce strict budgets).
777
+
778
+ ---
779
+
780
+ *Generated by \`@zero2webmaster/starter-kit --with-pro-seo\`. Updates ship via the Templates mirror at \`templates.z2w.us\` while your subscription is active.*
781
+ `;
782
+ }