@charmland/gem-vite 0.1.0 → 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.
package/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  // src/index.ts
2
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
3
- import { createRequire as createRequire2 } from "node:module";
4
- import { extname, join as join2, relative, resolve, sep } from "node:path";
5
- import { CONFIG_NAMES, compileSite, loadConfig, parseFrontmatter } from "@charmland/gem-compiler";
2
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { extname as extname2, join as join3, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { CONFIG_NAMES, compileSite, loadConfig, normalizeBase, parseFrontmatter } from "@charmland/gem-compiler";
6
7
 
7
8
  // src/output.ts
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { resolve } from "node:path";
8
11
  function markdownFile(route) {
9
12
  if (route === "/" || route === "")
10
13
  return "index.md";
@@ -13,11 +16,137 @@ function markdownFile(route) {
13
16
  function markdownRoute(route) {
14
17
  return `/${markdownFile(route)}`;
15
18
  }
16
- function absoluteUrl(origin, route) {
19
+ function withBase(base, route) {
20
+ const prefix = base && base !== "/" ? base.replace(/\/+$/, "") : "";
21
+ const path = route === "/" || route === "" ? "/" : route.startsWith("/") ? route : `/${route}`;
22
+ if (prefix === "")
23
+ return path;
24
+ return path === "/" ? `${prefix}/` : `${prefix}${path}`;
25
+ }
26
+ function originOnly(raw) {
27
+ const value = raw.trim();
28
+ if (!value)
29
+ return null;
30
+ const withScheme = /^https?:\/\//i.test(value) ? value : `https://${value}`;
31
+ try {
32
+ return new URL(withScheme).origin;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ function absoluteUrl(origin, route, base = "/") {
17
38
  if (!origin)
18
39
  return null;
19
- const path = route === "/" ? "/" : route;
20
- return `${origin.replace(/\/$/, "")}${path}`;
40
+ return `${origin.replace(/\/$/, "")}${withBase(base, route)}`;
41
+ }
42
+ function assetUrl(origin, path, base = "/") {
43
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(path))
44
+ return path;
45
+ const route = path.startsWith("/") ? path : `/${path}`;
46
+ return absoluteUrl(origin, route, base) ?? withBase(base, route);
47
+ }
48
+ function isRemote(value) {
49
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value);
50
+ }
51
+ function publicAsset(publicDir, value) {
52
+ if (isRemote(value))
53
+ return null;
54
+ const relative = value.replace(/^\/+/, "").split(/[?#]/, 1)[0] ?? "";
55
+ if (!publicDir || !relative)
56
+ return null;
57
+ const candidate = resolve(publicDir, relative);
58
+ return existsSync(candidate) ? candidate : null;
59
+ }
60
+ function localAssetExists(publicDir, value) {
61
+ if (isRemote(value))
62
+ return true;
63
+ if (!publicDir)
64
+ return true;
65
+ return publicAsset(publicDir, value) !== null;
66
+ }
67
+ function readLocalAsset(publicDir, value) {
68
+ const path = publicAsset(publicDir, value);
69
+ if (!path)
70
+ return null;
71
+ try {
72
+ return readFileSync(path);
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+ function warnOnce(warn) {
78
+ const seen = new Set;
79
+ return (message) => {
80
+ if (seen.has(message))
81
+ return;
82
+ seen.add(message);
83
+ warn(message);
84
+ };
85
+ }
86
+ function imageSize(data) {
87
+ if (data.length >= 24 && data.readUInt32BE(0) === 2303741511) {
88
+ return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
89
+ }
90
+ if (data.length >= 10 && data.subarray(0, 4).toString("ascii") === "GIF8") {
91
+ return { width: data.readUInt16LE(6), height: data.readUInt16LE(8) };
92
+ }
93
+ if (data.length >= 30 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") {
94
+ return webpSize(data);
95
+ }
96
+ if (data.length >= 4 && data[0] === 255 && data[1] === 216) {
97
+ return jpegSize(data);
98
+ }
99
+ return null;
100
+ }
101
+ function jpegSize(data) {
102
+ let offset = 2;
103
+ while (offset + 9 <= data.length) {
104
+ if (data[offset] !== 255) {
105
+ offset += 1;
106
+ continue;
107
+ }
108
+ const marker = data[offset + 1];
109
+ if (marker === undefined)
110
+ return null;
111
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
112
+ offset += 2;
113
+ continue;
114
+ }
115
+ const length = data.readUInt16BE(offset + 2);
116
+ const isSof = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
117
+ if (isSof) {
118
+ return {
119
+ height: data.readUInt16BE(offset + 5),
120
+ width: data.readUInt16BE(offset + 7)
121
+ };
122
+ }
123
+ offset += 2 + length;
124
+ }
125
+ return null;
126
+ }
127
+ function webpSize(data) {
128
+ const chunk = data.subarray(12, 16).toString("ascii");
129
+ if (chunk === "VP8X") {
130
+ return {
131
+ width: 1 + data.readUIntLE(24, 3),
132
+ height: 1 + data.readUIntLE(27, 3)
133
+ };
134
+ }
135
+ if (chunk === "VP8 ") {
136
+ return {
137
+ width: data.readUInt16LE(26) & 16383,
138
+ height: data.readUInt16LE(28) & 16383
139
+ };
140
+ }
141
+ if (chunk === "VP8L") {
142
+ if (data[20] !== 47)
143
+ return null;
144
+ return {
145
+ width: 1 + ((data[22] & 63) << 8 | data[21]),
146
+ height: 1 + ((data[24] & 15) << 10 | data[23] << 2 | (data[22] & 192) >> 6)
147
+ };
148
+ }
149
+ return null;
21
150
  }
22
151
  function ogFile(route) {
23
152
  if (route === "/" || route === "")
@@ -27,8 +156,8 @@ function ogFile(route) {
27
156
  function ogRoute(route) {
28
157
  return `/${ogFile(route)}`;
29
158
  }
30
- function sitemapXml(pages, origin) {
31
- const entries = pages.map((page) => absoluteUrl(origin, page.route)).filter((url) => url !== null).map((url) => ` <url><loc>${escapeXml(url)}</loc></url>`).join(`
159
+ function sitemapXml(pages, origin, base = "/") {
160
+ const entries = pages.map((page) => absoluteUrl(origin, page.route, base)).filter((url) => url !== null).map((url) => ` <url><loc>${escapeXml(url)}</loc></url>`).join(`
32
161
  `);
33
162
  return [
34
163
  `<?xml version="1.0" encoding="UTF-8"?>`,
@@ -39,15 +168,16 @@ function sitemapXml(pages, origin) {
39
168
  ].join(`
40
169
  `);
41
170
  }
42
- function robotsTxt(origin) {
171
+ function robotsTxt(origin, base = "/") {
43
172
  const lines = ["User-agent: *", "Allow: /"];
44
- if (origin)
45
- lines.push("", `Sitemap: ${origin.replace(/\/$/, "")}/sitemap.xml`);
173
+ if (origin) {
174
+ lines.push("", `Sitemap: ${origin.replace(/\/$/, "")}${withBase(base, "/sitemap.xml")}`);
175
+ }
46
176
  return `${lines.join(`
47
177
  `)}
48
178
  `;
49
179
  }
50
- function llmsTxt(site, origin) {
180
+ function llmsTxt(site, origin, base = "/") {
51
181
  const lines = [`# ${site.site.title}`, ""];
52
182
  if (site.site.description)
53
183
  lines.push(`> ${site.site.description}`, "");
@@ -55,31 +185,83 @@ function llmsTxt(site, origin) {
55
185
  lines.push(`## ${doc.label}`, "");
56
186
  for (const item of flatten(doc.nav)) {
57
187
  const page = site.pages.find((candidate) => candidate.route === item.route);
58
- const url = absoluteUrl(origin, item.route) ?? markdownRoute(item.route);
188
+ const url = absoluteUrl(origin, item.route, base) ?? withBase(base, markdownRoute(item.route));
59
189
  const summary = page?.summary ? `: ${page.summary}` : "";
60
190
  lines.push(`- [${item.title}](${url})${summary}`);
61
191
  }
62
192
  lines.push("");
63
193
  }
194
+ const full = absoluteUrl(origin, "/llms-full.txt", base) ?? withBase(base, "/llms-full.txt");
195
+ lines.push(`## Full text`, "", `- [Every page inlined](${full})`, "");
64
196
  return `${lines.join(`
65
197
  `)}
66
198
  `;
67
199
  }
68
- function jsonLd(site, page, origin) {
69
- const url = page ? absoluteUrl(origin, page.route) : origin;
70
- const data = page ? {
200
+ function llmsFullTxt(site, bodies, origin, base = "/") {
201
+ const lines = [`# ${site.site.title}`, ""];
202
+ if (site.site.description)
203
+ lines.push(`> ${site.site.description}`, "");
204
+ const collections = [];
205
+ for (const doc of site.docs) {
206
+ const sections = [];
207
+ for (const item of flatten(doc.nav)) {
208
+ const body = bodies.get(item.route)?.trim();
209
+ if (!body)
210
+ continue;
211
+ const url = absoluteUrl(origin, item.route, base) ?? withBase(base, markdownRoute(item.route));
212
+ sections.push(`### [${item.title}](${url})
213
+
214
+ ${body}`);
215
+ }
216
+ if (sections.length > 0)
217
+ collections.push(`## ${doc.label}
218
+
219
+ ${sections.join(`
220
+
221
+ ---
222
+
223
+ `)}`);
224
+ }
225
+ if (collections.length > 0)
226
+ lines.push(collections.join(`
227
+
228
+ ---
229
+
230
+ `), "");
231
+ return `${lines.join(`
232
+ `).trimEnd()}
233
+ `;
234
+ }
235
+ function jsonLd(site, page, origin, base = "/", image = null) {
236
+ const url = page ? absoluteUrl(origin, page.route, base) : base && base !== "/" ? absoluteUrl(origin, "/", base) : origin;
237
+ const home = absoluteUrl(origin, "/", base) ?? origin;
238
+ const language = site.seo.locale ? site.seo.locale.replace(/_/g, "-") : site.site.lang || undefined;
239
+ const publisher = {
240
+ "@type": "Organization",
241
+ name: site.seo.publisher || site.site.title,
242
+ ...home ? { url: home } : {}
243
+ };
244
+ const isHome = !page || page.isIndex || page.route === (site.docs[0]?.root ?? "/");
245
+ const data = isHome ? {
71
246
  "@context": "https://schema.org",
72
- "@type": "TechArticle",
73
- headline: page.title,
74
- description: page.description || page.summary || site.site.description,
247
+ "@type": "WebSite",
248
+ name: page ? page.title : site.site.title,
249
+ description: page && (page.description || page.summary) || site.site.description,
75
250
  url: url ?? undefined,
76
- isPartOf: { "@type": "WebSite", name: site.site.title }
251
+ inLanguage: language,
252
+ image: image ?? undefined,
253
+ publisher
77
254
  } : {
78
255
  "@context": "https://schema.org",
79
- "@type": "WebSite",
80
- name: site.site.title,
81
- description: site.site.description,
82
- url: url ?? undefined
256
+ "@type": "TechArticle",
257
+ headline: page?.title,
258
+ description: page && (page.description || page.summary) || site.site.description,
259
+ url: url ?? undefined,
260
+ isPartOf: { "@type": "WebSite", name: site.site.title },
261
+ mainEntityOfPage: url ? { "@type": "WebPage", "@id": url } : undefined,
262
+ inLanguage: language,
263
+ image: image ?? undefined,
264
+ publisher
83
265
  };
84
266
  return JSON.stringify(data).replace(/</g, "\\u003c");
85
267
  }
@@ -114,6 +296,34 @@ function landingRedirect(route) {
114
296
  `);
115
297
  }
116
298
 
299
+ // src/theme.ts
300
+ import { relative, resolve as resolve2, sep } from "node:path";
301
+
302
+ // src/paths.ts
303
+ function joinBase(base, file) {
304
+ return `${base.replace(/\/$/, "")}/${file.replace(/^\//, "")}`;
305
+ }
306
+
307
+ // src/theme.ts
308
+ var THEME_JS = "@charmland/gem/theme.js";
309
+ var THEME_CSS = "@charmland/gem/theme.css";
310
+ var FONT_ORIGIN = "https://stuff.charm.land";
311
+ var FONT_CSS = `${FONT_ORIGIN}/fonts/charmform/charmform.css`;
312
+ function devStyles(content, root, configuredEntry) {
313
+ const styles = [];
314
+ if (content.theme.css)
315
+ styles.push(joinBase(content.base, cssUrl(root, content.theme.css)));
316
+ if (!configuredEntry && !content.theme.entry) {
317
+ styles.push(joinBase(content.base, `@id/${THEME_CSS}`));
318
+ }
319
+ return styles;
320
+ }
321
+ function cssUrl(root, css) {
322
+ const file = resolve2(root, css);
323
+ const path = relative(root, file).split(sep).join("/");
324
+ return path.startsWith("..") ? `@fs${file.split(sep).join("/")}` : path;
325
+ }
326
+
117
327
  // src/html.ts
118
328
  function routeFile(route) {
119
329
  if (route === "/" || route === "")
@@ -129,15 +339,33 @@ function documentHtml(options) {
129
339
  styles,
130
340
  client = false,
131
341
  origin = null,
132
- ogImage = false
342
+ ogImage = false,
343
+ staticImageSize = null,
344
+ basePath = "/"
133
345
  } = options;
134
346
  const meta = site.site;
347
+ const seo = site.seo;
135
348
  const landing = site.docs[0]?.root ?? "/";
136
349
  const title = page && page.route !== landing ? `${page.title} - ${meta.title}` : meta.title;
137
350
  const description = page && page.description || meta.description || "";
138
- const canonical = page ? absoluteUrl(origin, page.route) : origin;
139
- const image = ogImage && page ? absoluteUrl(origin, ogRoute(page.route)) : null;
351
+ const canonical = page ? absoluteUrl(origin, page.route, basePath) : basePath && basePath !== "/" ? absoluteUrl(origin, "/", basePath) : origin;
352
+ const generatedImage = !meta.ogImage && ogImage && page !== null;
353
+ const image = meta.ogImage ? assetUrl(origin, meta.ogImage, basePath) : generatedImage && page ? absoluteUrl(origin, ogRoute(page.route), basePath) : null;
354
+ const imageType = generatedImage ? "image/png" : image ? imageTypeOf(image) : null;
355
+ const imageWidth = image ? generatedImage ? site.og.width : seo.imageWidth ?? staticImageSize?.width ?? null : null;
356
+ const imageHeight = image ? generatedImage ? site.og.height : seo.imageHeight ?? staticImageSize?.height ?? null : null;
357
+ const imageAlt = image ? imageAltOf(seo.imageAlt, page, meta.title) : null;
358
+ const locale = (seo.locale ?? localeFromLang(meta.lang))?.replace("-", "_") ?? null;
359
+ const favicon = meta.favicon ? assetUrl(origin, meta.favicon, basePath) : null;
360
+ const ogType = !page || page.isIndex || page.route === landing ? "website" : "article";
361
+ const twitterCard = seo.twitterCard ?? (image ? "summary_large_image" : "summary");
140
362
  const keywords = page && page.tags.length ? page.tags.join(", ") : "";
363
+ const extraMeta = seo.meta.map((tag) => {
364
+ const key = tag.property ? "property" : "name";
365
+ const value = tag.property ?? tag.name ?? "";
366
+ return `<meta ${key}="${escapeAttribute(value)}" content="${escapeAttribute(tag.content)}" />`;
367
+ }).join(`
368
+ `);
141
369
  const allowSystem = site.theme?.system ? "true" : "false";
142
370
  const modeScript = `<script>(function(){try{` + `var p=localStorage.getItem("gem-theme"),s=${allowSystem};` + `if(p!=="light"&&p!=="dark"&&p!=="system")p="system";` + `var t=p==="system"?(!window.matchMedia||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"):p;` + `var r=document.documentElement;r.setAttribute("data-theme",t);r.style.colorScheme=t` + `}catch(e){}})()</script>`;
143
371
  return `<!doctype html>
@@ -148,23 +376,39 @@ function documentHtml(options) {
148
376
  <title>${escapeHtml(title)}</title>
149
377
  ${description ? `<meta name="description" content="${escapeAttribute(description)}" />` : ""}
150
378
  ${keywords ? `<meta name="keywords" content="${escapeAttribute(keywords)}" />` : ""}
151
- <meta name="robots" content="index, follow" />
379
+ <meta name="robots" content="${escapeAttribute(seo.robots)}" />
380
+ ${seo.themeColor ? `<meta name="theme-color" content="${escapeAttribute(seo.themeColor)}" />` : ""}
152
381
  ${canonical ? `<link rel="canonical" href="${escapeAttribute(canonical)}" />` : ""}
153
- <meta property="og:type" content="article" />
382
+ ${favicon ? `<link rel="icon" href="${escapeAttribute(favicon)}" />` : ""}
383
+ ${extraMeta}
384
+ <meta property="og:type" content="${ogType}" />
154
385
  <meta property="og:site_name" content="${escapeAttribute(meta.title)}" />
155
386
  <meta property="og:title" content="${escapeAttribute(title)}" />
156
387
  ${description ? `<meta property="og:description" content="${escapeAttribute(description)}" />` : ""}
157
388
  ${canonical ? `<meta property="og:url" content="${escapeAttribute(canonical)}" />` : ""}
389
+ ${locale ? `<meta property="og:locale" content="${escapeAttribute(locale)}" />` : ""}
390
+ ${seo.localeAlternates.map((alternate) => `<meta property="og:locale:alternate" content="${escapeAttribute(alternate)}" />`).join(`
391
+ `)}
158
392
  ${image ? `<meta property="og:image" content="${escapeAttribute(image)}" />` : ""}
159
- <meta name="twitter:card" content="${image ? "summary_large_image" : "summary"}" />
393
+ ${imageAlt ? `<meta property="og:image:alt" content="${escapeAttribute(imageAlt)}" />` : ""}
394
+ ${imageType ? `<meta property="og:image:type" content="${escapeAttribute(imageType)}" />` : ""}
395
+ ${imageWidth ? `<meta property="og:image:width" content="${String(imageWidth)}" />` : ""}
396
+ ${imageHeight ? `<meta property="og:image:height" content="${String(imageHeight)}" />` : ""}
397
+ <meta name="twitter:card" content="${escapeAttribute(twitterCard)}" />
160
398
  <meta name="twitter:title" content="${escapeAttribute(title)}" />
161
399
  ${description ? `<meta name="twitter:description" content="${escapeAttribute(description)}" />` : ""}
400
+ ${seo.twitterSite ? `<meta name="twitter:site" content="${escapeAttribute(seo.twitterSite)}" />` : ""}
401
+ ${seo.twitterCreator ? `<meta name="twitter:creator" content="${escapeAttribute(seo.twitterCreator)}" />` : ""}
162
402
  ${image ? `<meta name="twitter:image" content="${escapeAttribute(image)}" />` : ""}
163
- <script type="application/ld+json">${jsonLd(site, page, origin)}</script>
403
+ ${imageAlt ? `<meta name="twitter:image:alt" content="${escapeAttribute(imageAlt)}" />` : ""}
404
+ <script type="application/ld+json">${jsonLd(site, page, origin, basePath, image)}</script>
164
405
  ${modeScript}
165
406
  ${styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join(`
166
407
  `)}
167
- ${client ? `<script type="module" src="/@vite/client"></script>` : ""}
408
+ <link rel="preconnect" href="${FONT_ORIGIN}" crossorigin />
409
+ <link rel="stylesheet" href="${FONT_CSS}" media="print" onload="this.media='all'" />
410
+ <noscript><link rel="stylesheet" href="${FONT_CSS}" /></noscript>
411
+ ${client ? `<script type="module" src="${escapeAttribute(clientScript(basePath))}"></script>` : ""}
168
412
  </head>
169
413
  <body>${body}</body>
170
414
  ${scripts.map((src) => `<script type="module" src="${escapeAttribute(src)}"></script>`).join(`
@@ -172,118 +416,409 @@ function documentHtml(options) {
172
416
  </html>
173
417
  `;
174
418
  }
419
+ function localeFromLang(lang) {
420
+ return /^[a-z]{2}[-_][a-z]{2}$/i.test(lang) ? lang.replace("-", "_") : null;
421
+ }
422
+ function imageAltOf(configured, page, siteTitle) {
423
+ const pageTitle = page ? page.title : siteTitle;
424
+ return (configured ?? "{title}").replace(/\{title\}/g, () => pageTitle).replace(/\{site\}/g, () => siteTitle);
425
+ }
426
+ var IMAGE_TYPES = {
427
+ png: "image/png",
428
+ jpg: "image/jpeg",
429
+ jpeg: "image/jpeg",
430
+ webp: "image/webp",
431
+ gif: "image/gif",
432
+ avif: "image/avif",
433
+ svg: "image/svg+xml"
434
+ };
435
+ function imageTypeOf(src) {
436
+ const match = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(src);
437
+ return match ? IMAGE_TYPES[match[1].toLowerCase()] ?? null : null;
438
+ }
175
439
  function escapeHtml(value) {
176
440
  return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
177
441
  }
178
442
  function escapeAttribute(value) {
179
443
  return escapeHtml(value).replace(/"/g, "&quot;");
180
444
  }
445
+ function clientScript(basePath) {
446
+ const prefix = basePath === "/" || basePath === "" ? "" : basePath.replace(/\/$/, "");
447
+ return `${prefix}/@vite/client`;
448
+ }
181
449
 
182
450
  // src/og.ts
183
- import { readFileSync } from "node:fs";
184
- import { createRequire } from "node:module";
185
- import { join } from "node:path";
186
- import { Resvg } from "@resvg/resvg-js";
187
- import satori from "satori";
188
- var WIDTH = 1200;
189
- var HEIGHT = 630;
190
- function require_(root) {
191
- return createRequire(join(root, "package.json"));
192
- }
193
- var fontData = null;
194
- var fontLoaded = false;
195
- function loadFont(root) {
196
- if (fontLoaded)
197
- return fontData;
198
- fontLoaded = true;
451
+ import { readFileSync as readFileSync2, statSync } from "node:fs";
452
+ import { join, resolve as resolve3 } from "node:path";
453
+ var DEFAULT_FONT_FAMILY = "Charmform Web";
454
+ var CUSTOM_FONT_FAMILY = "GemCover";
455
+ var REMOTE_TIMEOUT_MS = 1e4;
456
+ var fonts = new Map;
457
+ function readFont(path) {
199
458
  try {
200
- const path = require_(root).resolve("@charmland/gem/fonts/PPFraktionSans-Variable.ttf");
201
- fontData = readFileSync(path);
459
+ const mtime = statSync(path).mtimeMs;
460
+ const key = `${path}:${mtime}`;
461
+ const cached = fonts.get(key);
462
+ if (cached)
463
+ return cached;
464
+ const data = readFileSync2(path);
465
+ const entry = { data, mtime };
466
+ fonts.set(key, entry);
467
+ return entry;
202
468
  } catch {
203
- fontData = null;
469
+ return null;
204
470
  }
205
- return fontData;
206
471
  }
207
- async function renderOgImage(site, page, root) {
208
- const font = loadFont(root);
209
- if (!font)
472
+ var remoteFont = null;
473
+ async function fetchOk(url) {
474
+ const response = await fetch(url, { signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS) });
475
+ if (!response.ok)
476
+ throw new Error(`${response.status} ${response.statusText}`);
477
+ return response;
478
+ }
479
+ async function remoteDefaultFont(warn) {
480
+ try {
481
+ const css = await (await fetchOk(FONT_CSS)).text();
482
+ const match = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(css);
483
+ if (!match?.[1])
484
+ throw new Error("the stylesheet names no font file");
485
+ const src = new URL(match[1], FONT_CSS).href;
486
+ const data = Buffer.from(await (await fetchOk(src)).arrayBuffer());
487
+ return { path: src, data, mtime: 0, name: DEFAULT_FONT_FAMILY, weight: null, style: null };
488
+ } catch (error) {
489
+ const reason = error instanceof Error ? error.message : String(error);
490
+ warn(`og: default cover font unavailable (${reason}); covers use the fallback face`);
210
491
  return null;
211
- const accent = site.theme.accent || "#b8461f";
492
+ }
493
+ }
494
+ var defaultFont = (warn) => {
495
+ remoteFont ??= remoteDefaultFont(warn);
496
+ return remoteFont;
497
+ };
498
+ async function resolveFonts(root, site, warn, loadDefault) {
499
+ const og = site.og;
500
+ const declared = og.fonts.length ? og.fonts.map((font) => ({
501
+ src: font.src,
502
+ name: font.name ?? og.fontName ?? CUSTOM_FONT_FAMILY,
503
+ weight: font.weight,
504
+ style: font.style
505
+ })) : og.font ? [
506
+ {
507
+ src: og.font,
508
+ name: og.fontName ?? CUSTOM_FONT_FAMILY,
509
+ weight: null,
510
+ style: null
511
+ }
512
+ ] : [];
513
+ const loaded = [];
514
+ for (const font of declared) {
515
+ const path = resolve3(root, font.src);
516
+ const entry = readFont(path);
517
+ if (!entry) {
518
+ warn(`og: font "${font.src}" not found; skipping it`);
519
+ continue;
520
+ }
521
+ loaded.push({
522
+ path,
523
+ data: entry.data,
524
+ mtime: entry.mtime,
525
+ name: font.name,
526
+ weight: font.weight,
527
+ style: font.style
528
+ });
529
+ }
530
+ if (loaded.length > 0)
531
+ return loaded;
532
+ const fallback = await loadDefault(warn);
533
+ return fallback ? [fallback] : [];
534
+ }
535
+ var renderers = new Map;
536
+ function loadRenderer(fonts) {
537
+ const key = fonts.map((font) => `${font.path}:${font.mtime}:${font.name}:${font.weight ?? ""}:${font.style ?? ""}`).join("|");
538
+ const existing = renderers.get(key);
539
+ if (existing)
540
+ return existing;
541
+ const pending = (async () => {
542
+ const { Renderer } = await import("@takumi-rs/core");
543
+ const instance = new Renderer;
544
+ for (const font of fonts) {
545
+ await instance.registerFont({
546
+ name: font.name,
547
+ data: font.data,
548
+ ...font.weight !== null ? { weight: font.weight } : {},
549
+ ...font.style !== null ? { style: font.style } : {}
550
+ });
551
+ }
552
+ return instance;
553
+ })().catch((error) => {
554
+ renderers.delete(key);
555
+ throw error;
556
+ });
557
+ renderers.set(key, pending);
558
+ return pending;
559
+ }
560
+ function textFor(node, site, page) {
561
+ switch (node.field) {
562
+ case "title":
563
+ return page ? page.title : site.site.title;
564
+ case "site":
565
+ return site.site.title;
566
+ case "description":
567
+ return page && (page.description || page.summary) || site.site.description;
568
+ case "route":
569
+ return page ? page.route : "/";
570
+ case "category":
571
+ return page?.category ?? "";
572
+ case "literal":
573
+ return node.text ?? "";
574
+ }
575
+ }
576
+ async function coverNode(site, page, options) {
577
+ const og = site.og;
578
+ const warn = options.warn ?? (() => {});
579
+ const custom = og.text.length > 0 || og.images.length > 0;
580
+ if (!custom)
581
+ return builtinNode(site, page, options.family);
582
+ const children = [];
583
+ for (const image of og.images) {
584
+ const src = image.src.replace(/\{logo_image\}/g, () => site.site.logoImage ?? "");
585
+ if (!src) {
586
+ warn(`og: image "${image.src}" has no value for {logo_image}`);
587
+ continue;
588
+ }
589
+ const data = await options.loadImage(src);
590
+ if (!data)
591
+ continue;
592
+ children.push(imageNode(image, data));
593
+ }
594
+ for (const text of og.text) {
595
+ const value = textFor(text, site, page);
596
+ if (!value)
597
+ continue;
598
+ children.push(textNode(text, value, options.family));
599
+ }
600
+ return {
601
+ type: "container",
602
+ style: {
603
+ position: "relative",
604
+ width: og.width,
605
+ height: og.height,
606
+ boxSizing: "border-box",
607
+ backgroundColor: og.background,
608
+ color: "#f5f0e8",
609
+ fontFamily: options.family
610
+ },
611
+ children
612
+ };
613
+ }
614
+ function textNode(text, value, family) {
615
+ return {
616
+ type: "text",
617
+ text: value,
618
+ style: {
619
+ position: "absolute",
620
+ left: text.x,
621
+ top: text.y,
622
+ width: text.width ?? undefined,
623
+ height: text.height ?? undefined,
624
+ overflow: text.height !== null ? "hidden" : undefined,
625
+ fontFamily: family,
626
+ fontSize: text.fontSize ?? 32,
627
+ fontWeight: text.fontWeight ?? undefined,
628
+ lineHeight: text.lineHeight ?? undefined,
629
+ letterSpacing: text.letterSpacing ?? undefined,
630
+ color: text.color ?? "#f5f0e8",
631
+ textAlign: text.align,
632
+ opacity: text.opacity ?? undefined,
633
+ fontStyle: text.fontStyle ?? undefined,
634
+ ...text.family ? { fontFamily: text.family } : {}
635
+ }
636
+ };
637
+ }
638
+ function imageNode(image, src) {
639
+ return {
640
+ type: "image",
641
+ src,
642
+ width: image.width,
643
+ height: image.height,
644
+ style: {
645
+ position: "absolute",
646
+ left: image.x,
647
+ top: image.y,
648
+ width: image.width,
649
+ height: image.height,
650
+ objectFit: image.fit,
651
+ borderRadius: image.radius ?? undefined,
652
+ opacity: image.opacity ?? undefined
653
+ }
654
+ };
655
+ }
656
+ function builtinNode(site, page, family) {
657
+ const og = site.og;
658
+ const accent = og.accent || site.theme.accent || "#b8461f";
212
659
  const title = page ? page.title : site.site.title;
213
660
  const eyebrow = page ? site.site.title : site.site.description || site.site.title;
214
- const node = {
215
- type: "div",
216
- props: {
217
- style: {
218
- width: "100%",
219
- height: "100%",
220
- display: "flex",
221
- flexDirection: "column",
222
- justifyContent: "space-between",
223
- padding: "72px 80px",
224
- background: "#141414",
225
- color: "#f5f0e8",
226
- fontFamily: "Fraktion"
227
- },
228
- children: [
229
- {
230
- type: "div",
231
- props: {
232
- style: {
233
- display: "flex",
234
- alignItems: "center",
235
- gap: "20px",
236
- fontSize: 30,
237
- color: "#a8a29e"
238
- },
239
- children: [
240
- {
241
- type: "div",
242
- props: {
243
- style: { width: "52px", height: "10px", background: accent, borderRadius: "5px" }
244
- }
245
- },
246
- { type: "div", props: { children: eyebrow } }
247
- ]
248
- }
661
+ const scale = Math.max(0.4, Math.min(og.width / 1200, og.height / 630));
662
+ const size = (value) => Math.round(value * scale);
663
+ return {
664
+ type: "container",
665
+ style: {
666
+ width: og.width,
667
+ height: og.height,
668
+ display: "flex",
669
+ flexDirection: "column",
670
+ justifyContent: "space-between",
671
+ boxSizing: "border-box",
672
+ padding: `${size(72)}px ${size(80)}px`,
673
+ backgroundColor: og.background,
674
+ color: "#f5f0e8",
675
+ fontFamily: family
676
+ },
677
+ children: [
678
+ {
679
+ type: "container",
680
+ style: {
681
+ display: "flex",
682
+ alignItems: "center",
683
+ gap: `${size(20)}px`,
684
+ fontSize: size(30),
685
+ color: "#a8a29e"
249
686
  },
250
- {
251
- type: "div",
252
- props: {
687
+ children: [
688
+ {
689
+ type: "container",
253
690
  style: {
254
691
  display: "flex",
255
- fontSize: title.length > 48 ? 62 : 76,
256
- lineHeight: 1.1,
257
- letterSpacing: "-0.02em"
258
- },
259
- children: title
260
- }
692
+ width: `${size(52)}px`,
693
+ height: `${size(10)}px`,
694
+ backgroundColor: accent,
695
+ borderRadius: `${size(5)}px`
696
+ }
697
+ },
698
+ { type: "text", text: eyebrow }
699
+ ]
700
+ },
701
+ {
702
+ type: "container",
703
+ style: {
704
+ display: "flex",
705
+ fontSize: size(title.length > 48 ? 62 : 76),
706
+ lineHeight: 1.1,
707
+ letterSpacing: "-0.02em"
261
708
  },
262
- {
263
- type: "div",
264
- props: {
265
- style: { display: "flex", fontSize: 26, color: "#78716c" },
266
- children: page ? page.route : "/"
267
- }
709
+ children: [{ type: "text", text: title }]
710
+ },
711
+ {
712
+ type: "container",
713
+ style: { display: "flex", fontSize: size(26), color: "#78716c" },
714
+ children: [{ type: "text", text: page ? page.route : "/" }]
715
+ }
716
+ ]
717
+ };
718
+ }
719
+ function coverImageLoader(root, warn, publicDir = join(root, "public")) {
720
+ const cache = new Map;
721
+ const load = async (src) => {
722
+ if (/^data:/i.test(src)) {
723
+ const match = /^data:([^;,]*)(;base64)?,([\s\S]*)$/i.exec(src);
724
+ if (!match) {
725
+ warn("og: malformed data: image URL");
726
+ return null;
727
+ }
728
+ const payload = match[3] ?? "";
729
+ if (match[2] && !/^[a-z0-9+/=\s]+$/i.test(payload)) {
730
+ warn("og: malformed data: image URL");
731
+ return null;
732
+ }
733
+ try {
734
+ const bytes = new Uint8Array(Buffer.from(match[2] ? payload : decodeURIComponent(payload), match[2] ? "base64" : "utf8"));
735
+ if (bytes.length === 0) {
736
+ warn("og: malformed data: image URL");
737
+ return null;
268
738
  }
269
- ]
739
+ return bytes;
740
+ } catch {
741
+ warn("og: malformed data: image URL");
742
+ return null;
743
+ }
744
+ }
745
+ if (/^https?:/i.test(src)) {
746
+ try {
747
+ const response = await fetch(src, {
748
+ signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS)
749
+ });
750
+ if (!response.ok)
751
+ throw new Error(`HTTP ${response.status}`);
752
+ return new Uint8Array(await response.arrayBuffer());
753
+ } catch (error) {
754
+ const message = error instanceof Error ? error.message : String(error);
755
+ warn(`og: could not fetch "${src}": ${message}`);
756
+ return null;
757
+ }
270
758
  }
759
+ const relative = src.replace(/^\/+/, "").split(/[?#]/, 1)[0] ?? "";
760
+ const bases = publicDir ? [publicDir, root] : [root];
761
+ for (const base of bases) {
762
+ try {
763
+ return readFileSync2(resolve3(base, relative));
764
+ } catch {}
765
+ }
766
+ warn(`og: image "${src}" not found`);
767
+ return null;
768
+ };
769
+ return async (src) => {
770
+ if (cache.has(src))
771
+ return cache.get(src) ?? null;
772
+ const value = await load(src);
773
+ cache.set(src, value);
774
+ return value;
271
775
  };
776
+ }
777
+ async function renderOgImage(site, page, root, onWarn, loadImage, loadDefaultFont = defaultFont) {
778
+ const warn = onWarn ?? (() => {});
779
+ const og = site.og;
780
+ const fonts = await resolveFonts(root, site, warn, loadDefaultFont);
781
+ const node = await coverNode(site, page, {
782
+ family: fonts[0]?.name ?? DEFAULT_FONT_FAMILY,
783
+ loadImage: loadImage ?? coverImageLoader(root, warn),
784
+ warn
785
+ });
272
786
  try {
273
- const svg = await satori(node, {
274
- width: WIDTH,
275
- height: HEIGHT,
276
- fonts: [{ name: "Fraktion", data: font, weight: 400, style: "normal" }]
787
+ const takumi = await loadRenderer(fonts);
788
+ return await takumi.render(node, {
789
+ width: og.width,
790
+ height: og.height,
791
+ format: "png"
277
792
  });
278
- const resvg = new Resvg(svg, { fitTo: { mode: "width", value: WIDTH } });
279
- return resvg.render().asPng();
280
- } catch {
793
+ } catch (error) {
794
+ warn(`og: cover render failed: ${error instanceof Error ? error.message : String(error)}`);
281
795
  return null;
282
796
  }
283
797
  }
284
798
 
799
+ // src/preview.ts
800
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
801
+ import { extname, join as join2 } from "node:path";
802
+ function previewHtml(outDir) {
803
+ return (req, res, next) => {
804
+ if (req.method !== "GET" && req.method !== "HEAD")
805
+ return next();
806
+ const path = (req.url || "/").split("?")[0] ?? "/";
807
+ if (extname(path) || path.includes(".."))
808
+ return next();
809
+ const route = join2(outDir, routeFile(path));
810
+ const notFound = join2(outDir, "404.html");
811
+ const file = existsSync2(route) ? route : existsSync2(notFound) ? notFound : null;
812
+ if (!file)
813
+ return next();
814
+ res.statusCode = file === route ? 200 : 404;
815
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
816
+ res.end(req.method === "HEAD" ? undefined : readFileSync3(file));
817
+ };
818
+ }
819
+
285
820
  // src/prerender.ts
286
- import { existsSync, readFileSync as readFileSync2 } from "node:fs";
821
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
287
822
  var cached = null;
288
823
  function resolveModule(elm, path) {
289
824
  return path.split(".").reduce((scope, part) => scope && typeof scope === "object" ? scope[part] : null, elm);
@@ -291,9 +826,9 @@ function resolveModule(elm, path) {
291
826
  function loadThemeBundle(path) {
292
827
  if (cached && cached.path === path)
293
828
  return cached.source;
294
- if (!existsSync(path))
829
+ if (!existsSync3(path))
295
830
  return null;
296
- const source = readFileSync2(path, "utf8");
831
+ const source = readFileSync4(path, "utf8");
297
832
  cached = { path, source };
298
833
  return source;
299
834
  }
@@ -305,11 +840,12 @@ async function renderRoute(options) {
305
840
  if (!/Not implemented/.test(error.message))
306
841
  console.warn(`[gem] ${error.message}`);
307
842
  });
843
+ const origin = originOnly(content.site.url) ?? "https://gem.local";
308
844
  const dom = new JSDOM(html, {
309
845
  runScripts: "dangerously",
310
846
  pretendToBeVisual: true,
311
847
  virtualConsole,
312
- url: `${content.site.url || "https://gem.local"}${route}`
848
+ url: `${origin}${withBase(content.base, route)}`
313
849
  });
314
850
  try {
315
851
  dom.window.eval(source);
@@ -318,7 +854,11 @@ async function renderRoute(options) {
318
854
  if (!theme) {
319
855
  throw new Error(`theme bundle did not expose Elm.${moduleName}`);
320
856
  }
321
- theme.init({ flags: content, node: dom.window.document.body });
857
+ const flags = {
858
+ ...content,
859
+ theme: { ...content.theme, mode: content.theme.mode ?? "system" }
860
+ };
861
+ theme.init({ flags, node: dom.window.document.body });
322
862
  await new Promise((resolve) => dom.window.requestAnimationFrame(() => resolve()));
323
863
  return dom.window.document.body.innerHTML;
324
864
  } finally {
@@ -329,18 +869,22 @@ async function renderRoute(options) {
329
869
  // src/index.ts
330
870
  var CONTENT = "virtual:gem/content";
331
871
  var ENTRY = "virtual:gem/entry";
872
+ var MACHINE_FILES = new Set(["/robots.txt", "/sitemap.xml", "/llms.txt", "/llms-full.txt"]);
332
873
  var PROJECT_ASSET = /\.(elm|ts|tsx|js|jsx|mjs|mts|css|scss|sass|html|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|txt|xml|webmanifest|pdf)$/i;
333
874
  var GENERATED = /(^|[\\/])(node_modules|\.git|elm-stuff|\.cache)([\\/]|$)/;
334
875
  function gem(options = {}) {
335
876
  let root = process.cwd();
336
877
  let site = null;
878
+ let devImageSize = null;
337
879
  let scope = { content: [], config: [], theme: [] };
338
880
  let revision = 0;
339
881
  let pending = null;
340
882
  let pendingRevision = -1;
341
883
  let server = null;
342
884
  let isBuild = false;
885
+ let servesHtml = false;
343
886
  let base = "/";
887
+ let basePath = "/";
344
888
  let outDir = "";
345
889
  let publicDir = "";
346
890
  let logger = console;
@@ -355,9 +899,9 @@ function gem(options = {}) {
355
899
  const loaded = loadConfig(root, { file: options.configFile });
356
900
  const config = loaded.config;
357
901
  scope = {
358
- content: config.docs.map((doc) => resolve(root, doc.dir)),
359
- config: [...new Set([...CONFIG_NAMES.map((name) => join2(root, name)), loaded.file ?? ""])].filter((path) => path !== ""),
360
- theme: [options.entry, config.theme.entry, config.theme.css].filter((path) => Boolean(path)).map((path) => resolve(root, path))
902
+ content: config.docs.map((doc) => resolve4(root, doc.dir)),
903
+ config: [...new Set([...CONFIG_NAMES.map((name) => join3(root, name)), loaded.file ?? ""])].filter((path) => path !== ""),
904
+ theme: [options.entry, config.theme.entry, config.theme.css].filter((path) => Boolean(path)).map((path) => resolve4(root, path))
361
905
  };
362
906
  };
363
907
  const watchScope = () => {
@@ -374,9 +918,10 @@ function gem(options = {}) {
374
918
  return pending;
375
919
  const at = ++revision;
376
920
  pendingRevision = at;
377
- pending = compileSite({ root, configFile: options.configFile, onWarn: warn }).then((document) => {
921
+ pending = compileSite({ root, configFile: options.configFile, base: basePath, onWarn: warn }).then((document) => {
378
922
  if (at === revision)
379
923
  site = document;
924
+ devImageSize = document.site.ogImage ? imageSize(readLocalAsset(publicDir, document.site.ogImage) ?? Buffer.alloc(0)) : null;
380
925
  return document;
381
926
  }).finally(() => {
382
927
  if (pendingRevision === at)
@@ -389,7 +934,7 @@ function gem(options = {}) {
389
934
  revision++;
390
935
  };
391
936
  const reload = (environment, file) => {
392
- logger.info(`[gem] page reload ${relative(root, file)}`, { clear: true, timestamp: true });
937
+ logger.info(`[gem] page reload ${relative2(root, file)}`, { clear: true, timestamp: true });
393
938
  environment.hot.send({ type: "full-reload" });
394
939
  };
395
940
  return {
@@ -397,11 +942,12 @@ function gem(options = {}) {
397
942
  enforce: "pre",
398
943
  config(userConfig) {
399
944
  if (options.root)
400
- root = resolve(options.root);
945
+ root = resolve4(options.root);
401
946
  if (userConfig.root)
402
- root = resolve(userConfig.root);
403
- if (existsSync2(join2(root, "index.html")))
947
+ root = resolve4(userConfig.root);
948
+ if (existsSync4(join3(root, "index.html")))
404
949
  return;
950
+ servesHtml = true;
405
951
  return {
406
952
  appType: "custom",
407
953
  build: { rollupOptions: { input: ENTRY } }
@@ -411,7 +957,8 @@ function gem(options = {}) {
411
957
  root = resolved.root;
412
958
  isBuild = resolved.command === "build";
413
959
  base = resolved.base || "/";
414
- outDir = resolve(root, resolved.build.outDir);
960
+ basePath = normalizeBase(base);
961
+ outDir = resolve4(root, resolved.build.outDir);
415
962
  publicDir = resolved.publicDir;
416
963
  logger = resolved.logger;
417
964
  },
@@ -456,7 +1003,7 @@ function gem(options = {}) {
456
1003
  return `export default ${JSON.stringify(await compile())};`;
457
1004
  }
458
1005
  if (id === `\x00${ENTRY}`) {
459
- return entrySource(await compile(), root, options.entry);
1006
+ return entrySource(await compile(), root, options.entry, isBuild);
460
1007
  }
461
1008
  return null;
462
1009
  },
@@ -467,7 +1014,13 @@ function gem(options = {}) {
467
1014
  server.middlewares.use((req, res, next) => {
468
1015
  if (req.method !== "GET" && req.method !== "HEAD")
469
1016
  return next();
470
- const path = (req.url || "/").split("?")[0];
1017
+ const raw = req.url || "/";
1018
+ const [rawPath, ...rawQuery] = raw.split("?");
1019
+ const query = rawQuery.length ? `?${rawQuery.join("?")}` : "";
1020
+ const stripped = stripBasePath(basePath, rawPath ?? "/");
1021
+ if (stripped === null)
1022
+ return next();
1023
+ const path = stripped;
471
1024
  if (path.startsWith("/@") || path.startsWith("/node_modules"))
472
1025
  return next();
473
1026
  if (path.endsWith(".md")) {
@@ -480,41 +1033,63 @@ function gem(options = {}) {
480
1033
  return;
481
1034
  }
482
1035
  res.setHeader("Content-Type", "text/markdown; charset=utf-8");
483
- res.end(parseFrontmatter(readFileSync3(join2(root, page.source), "utf8")).body);
1036
+ res.end(parseFrontmatter(readFileSync5(join3(root, page.source), "utf8")).body);
1037
+ });
1038
+ return;
1039
+ }
1040
+ if (MACHINE_FILES.has(path)) {
1041
+ compile().then((content) => {
1042
+ const file = machineFile(content, path, devOrigin(req.headers.host), root);
1043
+ if (!file) {
1044
+ res.statusCode = 404;
1045
+ res.end("not found");
1046
+ return;
1047
+ }
1048
+ res.setHeader("Content-Type", file.type);
1049
+ res.end(file.body);
484
1050
  });
485
1051
  return;
486
1052
  }
487
- if (extname(path))
1053
+ if (extname2(path))
488
1054
  return next();
489
1055
  if (path.startsWith("/src") || path.startsWith("/public") || path.startsWith("/assets")) {
490
1056
  return next();
491
1057
  }
492
1058
  compile().then((content) => {
493
1059
  const route = normalizeRoute(path);
1060
+ const documentBase = content.base;
494
1061
  const landing = landingPage(content);
495
1062
  if (route === "/" && landing && landing !== "/") {
496
1063
  res.statusCode = 302;
497
- res.setHeader("Location", landing);
1064
+ res.setHeader("Location", `${joinBase(documentBase, landing)}${query}`);
498
1065
  res.end();
499
1066
  return;
500
1067
  }
501
1068
  const page = content.pages.find((item) => item.route === route) || null;
502
- const host = req.headers.host;
503
- const origin = host ? `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}` : null;
1069
+ const origin = devOrigin(req.headers.host);
504
1070
  res.statusCode = page ? 200 : 404;
505
1071
  res.setHeader("Content-Type", "text/html; charset=utf-8");
506
1072
  res.end(documentHtml({
507
1073
  site: content,
508
1074
  page,
509
1075
  body: "",
510
- scripts: [`/@id/${ENTRY}`],
511
- styles: [],
1076
+ scripts: [joinBase(documentBase, `@id/${ENTRY}`)],
1077
+ styles: devStyles(content, root, options.entry),
512
1078
  client: true,
513
- origin
1079
+ basePath: documentBase,
1080
+ origin,
1081
+ staticImageSize: devImageSize
514
1082
  }));
515
1083
  }, next);
516
1084
  });
517
1085
  },
1086
+ configurePreviewServer(preview) {
1087
+ if (!servesHtml)
1088
+ return;
1089
+ return () => {
1090
+ preview.middlewares.use(previewHtml(outDir));
1091
+ };
1092
+ },
518
1093
  async buildStart() {
519
1094
  await compile(true);
520
1095
  },
@@ -532,47 +1107,77 @@ function gem(options = {}) {
532
1107
  }
533
1108
  const themePath = resolveTheme(root, options.theme);
534
1109
  const bundleSource = themePath ? loadThemeBundle(themePath) : null;
535
- const origin = resolveOrigin(content.site.url);
1110
+ const documentBase = content.base;
1111
+ const { origin, ignoredPath } = resolveOrigin(content.site.url);
1112
+ if (ignoredPath) {
1113
+ warn(`site.url path "${ignoredPath}" is ignored; deploy under a subpath with the Vite \`base\` option (currently "${documentBase}").`);
1114
+ }
536
1115
  if (!origin) {
537
1116
  warn("seo: no site.url and no deploy env; canonical, sitemap and og:url are skipped.");
538
1117
  }
539
1118
  if (!bundleSource && options.prerender !== false) {
540
1119
  warn("prerender skipped: no theme bundle. Set `theme` or build @charmland/gem first.");
541
1120
  }
542
- this.emitFile({ type: "asset", fileName: "robots.txt", source: robotsTxt(origin) });
543
- this.emitFile({ type: "asset", fileName: "llms.txt", source: llmsTxt(content, origin) });
1121
+ const ogWarn = warnOnce(warn);
1122
+ for (const [name, value] of [
1123
+ ["favicon", content.site.favicon],
1124
+ ["og_image", content.site.ogImage]
1125
+ ]) {
1126
+ if (value && !localAssetExists(publicDir, value)) {
1127
+ warn(`seo: ${name} "${value}" was not found in the Vite public dir.`);
1128
+ }
1129
+ }
1130
+ const configuredImageSize = content.site.ogImage ? imageSize(readLocalAsset(publicDir, content.site.ogImage) ?? Buffer.alloc(0)) : null;
1131
+ const coverImage = coverImageLoader(root, ogWarn, publicDir);
1132
+ this.emitFile({ type: "asset", fileName: "robots.txt", source: robotsTxt(origin, documentBase) });
1133
+ this.emitFile({
1134
+ type: "asset",
1135
+ fileName: "llms.txt",
1136
+ source: llmsTxt(content, origin, documentBase)
1137
+ });
544
1138
  if (origin) {
545
1139
  this.emitFile({
546
1140
  type: "asset",
547
1141
  fileName: "sitemap.xml",
548
- source: sitemapXml(content.pages, origin)
1142
+ source: sitemapXml(content.pages, origin, documentBase)
549
1143
  });
550
1144
  }
1145
+ const pages = content.pages;
1146
+ const bundleText = typeof bundleSource === "string" ? bundleSource : "";
1147
+ const canRender = bundleText !== "";
1148
+ const startedAt = performance.now();
1149
+ const timing = { covers: 0, renders: 0, notFound: 0 };
551
1150
  const images = new Set;
552
- for (const page of content.pages) {
553
- const cover = await renderOgImage(content, page, root);
554
- if (!cover)
555
- continue;
556
- images.add(page.route);
557
- this.emitFile({ type: "asset", fileName: ogFile(page.route), source: cover });
1151
+ if (!content.site.ogImage) {
1152
+ const coversStarted = performance.now();
1153
+ for (const page of pages) {
1154
+ const cover = await renderOgImage(content, page, root, ogWarn, coverImage);
1155
+ if (!cover)
1156
+ continue;
1157
+ images.add(page.route);
1158
+ this.emitFile({ type: "asset", fileName: ogFile(page.route), source: cover });
1159
+ }
1160
+ timing.covers += performance.now() - coversStarted;
558
1161
  }
559
- for (const page of content.pages) {
560
- const markdownSource = readFileSync3(join2(root, page.source), "utf8");
561
- this.emitFile({
562
- type: "asset",
563
- fileName: markdownFile(page.route),
564
- source: parseFrontmatter(markdownSource).body
565
- });
566
- const rendered = bundleSource && typeof bundleSource === "string" ? await renderRoute({
567
- source: bundleSource,
1162
+ const rendersStarted = performance.now();
1163
+ const bodies = new Map;
1164
+ for (const page of pages) {
1165
+ const markdownSource = readFileSync5(join3(root, page.source), "utf8");
1166
+ const body = parseFrontmatter(markdownSource).body;
1167
+ bodies.set(page.route, body);
1168
+ this.emitFile({ type: "asset", fileName: markdownFile(page.route), source: body });
1169
+ const rendered = canRender ? await renderRoute({
1170
+ source: bundleText,
568
1171
  html: documentHtml({
569
1172
  site: content,
570
1173
  page,
571
1174
  body: "",
572
1175
  scripts: [],
573
1176
  styles,
1177
+ basePath: documentBase,
574
1178
  origin,
575
- ogImage: images.has(page.route)
1179
+ ogImage: images.has(page.route),
1180
+ staticImageSize: configuredImageSize
576
1181
  }),
577
1182
  content,
578
1183
  route: page.route,
@@ -590,25 +1195,36 @@ function gem(options = {}) {
590
1195
  body: rendered,
591
1196
  scripts,
592
1197
  styles,
1198
+ basePath: documentBase,
593
1199
  origin,
594
- ogImage: images.has(page.route)
1200
+ ogImage: images.has(page.route),
1201
+ staticImageSize: configuredImageSize
595
1202
  })
596
1203
  });
597
1204
  }
1205
+ timing.renders += performance.now() - rendersStarted;
1206
+ this.emitFile({
1207
+ type: "asset",
1208
+ fileName: "llms-full.txt",
1209
+ source: llmsFullTxt(content, bodies, origin, documentBase)
1210
+ });
598
1211
  const landing = landingPage(content);
599
1212
  if (landing && landing !== "/") {
600
1213
  this.emitFile({ type: "asset", fileName: "index.html", source: landingRedirect(landing) });
601
1214
  }
1215
+ const notFoundStarted = performance.now();
602
1216
  const notFoundHtml = documentHtml({
603
1217
  site: content,
604
1218
  page: null,
605
1219
  body: "",
606
1220
  scripts: [],
607
1221
  styles,
608
- origin
1222
+ basePath: documentBase,
1223
+ origin,
1224
+ staticImageSize: configuredImageSize
609
1225
  });
610
- const notFoundBody = bundleSource && typeof bundleSource === "string" ? await renderRoute({
611
- source: bundleSource,
1226
+ const notFoundBody = canRender ? await renderRoute({
1227
+ source: bundleText,
612
1228
  html: notFoundHtml,
613
1229
  content,
614
1230
  route: "/404",
@@ -623,9 +1239,13 @@ function gem(options = {}) {
623
1239
  body: notFoundBody,
624
1240
  scripts,
625
1241
  styles,
1242
+ basePath: documentBase,
626
1243
  origin
627
1244
  })
628
1245
  });
1246
+ timing.notFound += performance.now() - notFoundStarted;
1247
+ const total = performance.now() - startedAt;
1248
+ logger.info(`[gem] build timings: ${pages.length} pages; covers ${(timing.covers / 1000).toFixed(1)}s; ` + `prerender ${(timing.renders / 1000).toFixed(1)}s; ` + `404 ${(timing.notFound / 1000).toFixed(1)}s; ` + `total ${(total / 1000).toFixed(1)}s`);
629
1249
  }
630
1250
  };
631
1251
  }
@@ -635,22 +1255,57 @@ function landingPage(content) {
635
1255
  return null;
636
1256
  return content.pages.some((page) => page.route === root) ? root : null;
637
1257
  }
1258
+ function devOrigin(host) {
1259
+ if (!host)
1260
+ return null;
1261
+ return `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}`;
1262
+ }
1263
+ function machineFile(content, path, origin, root) {
1264
+ const base = content.base;
1265
+ if (path === "/robots.txt") {
1266
+ return { body: robotsTxt(origin, base), type: "text/plain; charset=utf-8" };
1267
+ }
1268
+ if (path === "/sitemap.xml") {
1269
+ if (!origin)
1270
+ return null;
1271
+ return { body: sitemapXml(content.pages, origin, base), type: "application/xml; charset=utf-8" };
1272
+ }
1273
+ if (path === "/llms.txt") {
1274
+ return { body: llmsTxt(content, origin, base), type: "text/plain; charset=utf-8" };
1275
+ }
1276
+ if (path === "/llms-full.txt") {
1277
+ const bodies = new Map;
1278
+ for (const page of content.pages) {
1279
+ const source = readFileSync5(join3(root, page.source), "utf8");
1280
+ bodies.set(page.route, parseFrontmatter(source).body);
1281
+ }
1282
+ return { body: llmsFullTxt(content, bodies, origin, base), type: "text/plain; charset=utf-8" };
1283
+ }
1284
+ return null;
1285
+ }
638
1286
  function resolveOrigin(configured) {
639
1287
  const raw = configured || process.env.GEM_URL || process.env.VERCEL_URL || process.env.CF_PAGES_URL || process.env.URL || "";
640
- if (!raw)
641
- return null;
642
- const value = raw.replace(/\/$/, "");
643
- return /^https?:\/\//.test(value) ? value : `https://${value}`;
1288
+ if (!raw.trim())
1289
+ return { origin: null, ignoredPath: null };
1290
+ const value = raw.trim();
1291
+ const withScheme = /^https?:\/\//i.test(value) ? value : `https://${value}`;
1292
+ try {
1293
+ const url = new URL(withScheme);
1294
+ const path = url.pathname;
1295
+ return { origin: url.origin, ignoredPath: path && path !== "/" ? path : null };
1296
+ } catch {
1297
+ return { origin: originOnly(value), ignoredPath: null };
1298
+ }
644
1299
  }
645
- function entrySource(content, root, configuredEntry) {
1300
+ function entrySource(content, root, configuredEntry, includeCss) {
646
1301
  const custom = configuredEntry || content.theme.entry;
647
- const extra = content.theme.css ? `import ${JSON.stringify(resolve(root, content.theme.css))};` : "";
1302
+ const extra = includeCss && content.theme.css ? `import ${JSON.stringify(resolve4(root, content.theme.css))};` : "";
648
1303
  if (custom) {
649
- return [`import ${JSON.stringify(resolve(root, custom))};`, extra].filter(Boolean).join(`
1304
+ return [`import ${JSON.stringify(resolve4(root, custom))};`, extra].filter(Boolean).join(`
650
1305
  `);
651
1306
  }
652
1307
  return [
653
- `import "@charmland/gem/theme.css";`,
1308
+ includeCss ? `import ${JSON.stringify(THEME_CSS)};` : "",
654
1309
  extra,
655
1310
  `import { boot } from "@charmland/gem/boot";`,
656
1311
  `import content from ${JSON.stringify(CONTENT)};`,
@@ -660,9 +1315,9 @@ function entrySource(content, root, configuredEntry) {
660
1315
  }
661
1316
  function resolveTheme(root, explicit) {
662
1317
  if (explicit)
663
- return resolve(root, explicit);
1318
+ return resolve4(root, explicit);
664
1319
  try {
665
- return createRequire2(join2(root, "package.json")).resolve("@charmland/gem/theme.js");
1320
+ return createRequire(join3(root, "package.json")).resolve(THEME_JS);
666
1321
  } catch {
667
1322
  return null;
668
1323
  }
@@ -675,11 +1330,18 @@ function normalizeRoute(path) {
675
1330
  function inDirectory(file, directory) {
676
1331
  if (file === directory)
677
1332
  return true;
678
- const base = directory.endsWith(sep) ? directory : directory + sep;
1333
+ const base = directory.endsWith(sep2) ? directory : directory + sep2;
679
1334
  return file.startsWith(base);
680
1335
  }
681
- function joinBase(base, file) {
682
- return `${base.replace(/\/$/, "")}/${file.replace(/^\//, "")}`;
1336
+ function stripBasePath(basePath, path) {
1337
+ if (basePath === "/")
1338
+ return path;
1339
+ const prefix = basePath.replace(/\/$/, "");
1340
+ if (path === prefix || path === basePath)
1341
+ return "/";
1342
+ if (path.startsWith(basePath))
1343
+ return `/${path.slice(basePath.length)}`;
1344
+ return null;
683
1345
  }
684
1346
  function errorMessage(error) {
685
1347
  return error instanceof Error ? error.message : String(error);